diff --git a/docs/BUG_HISTORY.md b/docs/BUG_HISTORY.md index b3c8dd55c..01175b856 100644 --- a/docs/BUG_HISTORY.md +++ b/docs/BUG_HISTORY.md @@ -22213,7 +22213,7 @@ ## BUG-1628 | 点「开始 / 继续」生时校正,先闪一下空白首页才进校正对话 -- 状态:fixed-pending-verify(代码 + 回归测试;登录态真机未测) +- 状态:superseded(2026-11-06 被 BUG-1644 取代:对话式生时校正整体下线,本条修的开案 / 打开路径随之删除;原状态 fixed-pending-verify) - 首次发现 / 最近更新:2026-11-05(产品负责人截图反馈:「先到首页图一,然后才到图二,很割裂」)/ 2026-11-05 - 影响面:`frontend/src/app/(app)/page.tsx`、`hooks/use-rectification-surface.ts`、`components/page-curtain.tsx`、`hooks/use-page-curtain.ts`、`lib/page-curtain-store.ts`。 - 现象:在 /rectification 点「开始校正 / 继续上次 / 新建一次」,或在侧栏点一条生时校正对话,先出现空白首页(「你来啦,××」,输入框写「正在打开生时校正…」),一两秒后才换成校正对话。 @@ -22228,7 +22228,7 @@ ## BUG-1629 | 生时校正不能直接进对话:开案请求要等首页挂上后才发 -- 状态:fixed-pending-verify(代码 + 回归测试;登录态真机未测) +- 状态:superseded(2026-11-06 被 BUG-1644 取代:对话式生时校正整体下线,本条修的开案 / 打开路径随之删除;原状态 fixed-pending-verify) - 首次发现 / 最近更新:2026-11-05(产品负责人:「为什么不能直接进入生时纠正对话」,选方案 B)/ 2026-11-05 - 影响面:新增 `frontend/src/lib/rectification-open-prefetch.ts`;`hooks/use-rectification-surface.ts`(`openRectificationCase`)、`components/rectification-page/rectification-entry-page.tsx`、`app/(app)/layout.tsx`(侧栏校正行)。 - 现象:BUG-1628 用幕布盖住了打开过程,但打开本身仍是串行的:点击 → 跳首页 → 首页挂上 → effect 排队 → 才发开案请求 → 再读案与来源 → 再等校正界面代码。 @@ -22477,3 +22477,26 @@ - 关联记录:BUG-1355(每小时上限的来源,报告部分在此撤回)、BUG-1637。 - 复发自:无 - 修复版本:分支 `codex/report-no-daily-cap-20261105`。 + +## BUG-1644 | 生时校正录了 10 件大事、答了题,范围仍是整窗、「按现有信息分不开」:事件打分在 30 分钟窗口里没有区分力,整条对话式校正下线,改为「生时纠正」选盘页 + +- 状态:fixed-pending-verify(代码 + 回归测试;未推 staging,真机未看) +- 首次发现 / 最近更新:2026-11-06(产品负责人实测:10 件带年月的大事 + 2 道追问,每题都回「这一题没有让范围变窄」,最后交付整个 31 分钟窗口,D9 / D10 都「分不开」;原话「稀里糊涂的」「这部分太影响体验了」)/ 2026-11-06 +- 影响面:删除——前端 `src/lib/rectification-agentic/**`(core + v9)、`src/lib/rectification-*.ts`(除 in-chat、adopted-chart-tiers、policy)、`src/lib/birth-time-{journey,dynamic,guide,guided,scoring,evidence}*`、`src/mastra/agentic-rectification.ts`、`src/mastra/rectification-v9-tools.ts`、`src/components/rectification-*`(除 in-chat-cards)、`conversational-birth-time-rectification*`、`birth-time-assessment-overlay`、`src/hooks/use-rectification-*`、`use-birth-time-*`、`src/app/api/rectification/**`、`/api/birth-time-guide`、`/api/birth-time-journey`、后台校正统计页;Python `scripts/rectification/` 的 V5 打分链(api_service、scoring_service、decision_policy、diagnostics_service、sealed_holdout 等)、`dynamic_rectification*`、`minute_rectification_*` 评测、依赖它们的 `scripts/research/*`,以及 `jyotish_api_server.py` 的 `/api/rectification/v5/{score,diagnostics,candidate-features,vedastro-validate,block_scan,versions}`、`/api/active_rectification_events_v4`、`/api/dynamic_rectification_*`。保留——上游技能层(MCP 问卷、`/api/rectification_gate`、`/api/active_rectification_{questions,score,events}`)及其模块;咨询用的 `/api/rectification/v5/range_reading`(迁到 `scripts/birth_window_range_reading.py`);星盘页的 `/api/rectification/v5/varga-segments`;报告读旧采用结果的 `adopted-segment-summary.ts` / `rectification-adopted-chart-tiers.ts`;咨询提议卡与旧消息里的提议 / 返回记录渲染;数据库表一张未删(下一轮单独迁移)。 +- 现象:见首次发现。另:「方法 1:9/10 件事件吻合」在每个候选上都一样,不提供区分。 +- 触发条件:任何出生时间范围不足以让 D1 / 大运主星变化的校正(典型 ±15 分钟)。 +- 根因(已确认): + 1. 30 分钟内 D1 上升与 Vimshottari 主 / 次运主星不变,打分里权重最大的几项(MD 2.0、AD 1.5、Narayana 2/1、D1 宫位 / 宫主)对每个候选加同样的分;随分钟变化的分盘项每件事最多约 1 分,再经比例归一(BUG-560)压到 7–9%,领先 8 分的门槛到不了;单题 ±2 分永远推不过 8 分。 + 2. 方法本身:2026-11-06 在 holdout v5(77 例 Rodden AA、约 960 件有出处事件)上模拟,30 分钟窗口按 D1/D9/D10 切段,线上打分器头名段命中真值 0.19、只保留段间差异项的打分 0.20、均匀随机 0.20、直接取报的时间所在段 0.34;跨 D1 换座的 120 分钟窗口:事件打分 0.55、随机 0.55、报的时间 0.70。与 BUG-1091 结论一致;上游 yinduzhanxing 用同一套公式,照搬上游同样分不开。外部旁证:Stellium 计算型生时纠正研究(单项目报告,非同行评审)同样得出事件计时技法在定位出生时间上为随机水平。 + 3. 在不可区分的打分上叠加卡片、门槛、开关,累计约 251 条相关 BUG 记录,体验表现为「问了不收窄」。 +- 修复:整条对话式校正下线,换成无状态的「生时纠正」页(`/rectification`,独立页面,不带右侧星盘): + - 引擎 `scripts/chart_choice/`:在用户给的范围里精确到秒算出 D1/D2/D4/D9/D10/D12/D24 上升换座的分界线;同一度数一起换的分盘合并成一条线;范围超过 60 分钟先引导缩小(日出在范围内就问「天亮了吗」,否则对半);只比较离报的时间最近的一条线,按领域列出线前 / 线后的盘面差异(大白话),每张越线分盘一道自选题(最多 5 题,可选「说不清」)。 + - 决定规则(产品 2026-11-06 定):报的时间离线 < 5 分钟或是整刻钟时按回答多数定,平局保留报的时间;否则需 ≥4 题偏另一边且偏本边 ≤1 题才换;回答与结果相反的领域标「两版都读」。 + - 保存:`chart_choice_adopt_v1`(迁移 `20261106010000_chart_choice_adopt.sql`)写入既有的 `active_birth_*` 列,`birth_time_status = accepted`,`active_birth_provenance` 记 `source = user_choice`、规则、计数、回答和两版都读的领域;分钟由服务端从存储的出生声明重算,浏览器只交回答。页面不计费。 + - 咨询:提议卡不再读旧案件和价格,只看产品开关;直达入口不再续旧案。旧的 birth_time_rectification 会话不再出现在侧栏和会话列表。 +- 验证:`tests/test_chart_choice.py` 20 条(分界线精确到秒且同度数合并、D9 线不因浮点丢失、段与保存分钟、规则四种情形、窄窗 / 宽窗 / 跨午夜 / 报的时间不在范围、坏输入);Python quick gate 910 通过,1 条与本单无关的顺序相关抖动(`test_consultation_native_layers::test_the_new_layer_leaves_every_existing_output_unchanged`,单独跑在本分支与 staging 均通过);前端 tsc / eslint / 全量测试见提交说明。 +- 防复发:不再提出用事件打分或卡片追问去收窄出生分钟(定论数字见上与 BUG-1091);生时纠正的结果只能写成「本人选择」,不得写成验证结果。 +- 已知未做:「两版都读」接入咨询(下一轮);旧校正相关数据库表与迁移清理(下一轮);`JYOTISH_DYNAMIC_RECTIFICATION_TOKEN` 仍在部署环境校验脚本里(无害,下一轮清理)。 +- 关联记录:BUG-560、BUG-1084、BUG-1085、BUG-1089、BUG-1090、BUG-1091、BUG-1628(superseded)、BUG-1629(superseded)。 +- 复发自:BUG-1084(同一现象:收集事件后范围不收窄)。当时只关掉了事件收集,没有处理打分本身没有区分力。 +- 修复版本:分支 `codex/rectification-rebuild-20261106`(基于 staging `945e8691`),未推送。 diff --git a/scripts/active_rectification_events_v4.py b/scripts/active_rectification_events_v4.py deleted file mode 100644 index 507170cf5..000000000 --- a/scripts/active_rectification_events_v4.py +++ /dev/null @@ -1,18 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [] -# /// -"""Compatibility entrypoint backed by the formal V5 score service.""" -from __future__ import annotations - -from typing import Any - -from scripts.rectification.api_service import score_candidates - - -def score_life_events_v4(request: dict[str, Any]) -> dict[str, Any]: - return score_candidates(request) - - -if __name__ == "__main__": - raise SystemExit("Import score_life_events_v4 from the worker or API server.") diff --git a/scripts/active_rectification_scoring.py b/scripts/active_rectification_scoring.py deleted file mode 100644 index 0deb12bc8..000000000 --- a/scripts/active_rectification_scoring.py +++ /dev/null @@ -1,178 +0,0 @@ -"""Build and score deterministic birth-time rectification questions.""" - -from __future__ import annotations - -from collections.abc import Mapping -from dataclasses import dataclass -from typing import Final, Literal, TypeAlias, TypedDict - -AnswerChoice: TypeAlias = Literal["A", "B", "C", "D"] -JsonScalar: TypeAlias = str | int | float | bool | None -JsonValue: TypeAlias = JsonScalar | list["JsonValue"] | dict[str, "JsonValue"] - - -class QuestionOption(TypedDict): - key: AnswerChoice - label: str - score: int - - -class ScoringRule(TypedDict): - effect: str - cluster: str - points: int - - -class RectificationQuestion(TypedDict): - id: str - round: int - domain: str - sensitivity: list[str] - window: str - prompt: str - options: list[QuestionOption] - scoring_map: dict[AnswerChoice, ScoringRule] - - -class AppliedScore(TypedDict): - id: str - answer: str - cluster: str - points: int - - -class ClusterRanking(TypedDict): - cluster: str - score: int - - -class InvalidAnswer(TypedDict): - id: str - answer: str - - -class ScoringResult(TypedDict): - scope: str - schema_version: int - answered_count: int - candidate_cluster_rankings: list[ClusterRanking] - next_round: int | None - next_round_questions: list[dict[str, JsonValue]] - applied_scoring: list[AppliedScore] - unknown_question_ids: list[str] - invalid_answers: list[InvalidAnswer] - boundary: str - - -@dataclass(frozen=True, slots=True) -class QuestionTemplate: - id: str - round: int - domain: str - sensitivity: tuple[str, ...] - window: str - prompt: str - yes_bias: str - no_bias: str - - -OPTIONS: Final[tuple[QuestionOption, ...]] = ( - {"key": "A", "label": "明确有,且时间大致吻合", "score": 2}, - {"key": "B", "label": "有类似,但时间略偏或不够重大", "score": 1}, - {"key": "C", "label": "没有明显发生", "score": -2}, - {"key": "D", "label": "不确定 / 不记得", "score": 0}, -) - -QUESTION_TEMPLATES: Final[tuple[QuestionTemplate, ...]] = ( - QuestionTemplate("education_environment_shift", 1, "education", ("D24", "D4", "Dasha"), "age_16_to_18", "16-18岁附近,是否有明显学业、学校、专业方向或学习环境变化?", "middle_candidate_cluster", "against_D24_sensitive_cluster"), - QuestionTemplate("residence_relocation_shift", 1, "residence", ("D4", "12H", "Rahu/Ketu", "Transit"), "age_20_to_24", "20-24岁附近,是否有搬家、离乡、长期异地、住宿或居住结构变化?", "D4_relocation_cluster", "against_D4_relocation_cluster"), - QuestionTemplate("relationship_or_partner_entry", 1, "relationship", ("D9", "UL", "A7", "7H"), "age_21_to_26", "21-26岁附近,是否有关系对象进入、关系断裂、暧昧升级或关系观明显转变?", "D9_UL_A7_cluster", "against_relationship_cluster"), - QuestionTemplate("career_responsibility_pressure", 1, "career", ("D10", "A10", "Saturn", "10H"), "age_26_to_30", "26-30岁附近,是否有责任增加、合作压力、工作结构变化或长期压力阶段?", "D10_A10_saturn_cluster", "against_career_pressure_cluster"), - QuestionTemplate("finance_resource_shift", 1, "finance", ("D2", "2H", "11H"), "resource_change_window", "是否有收入结构、重要资产、资助、负债或资源渠道发生明显变化的阶段?", "D2_resource_cluster", "against_D2_resource_cluster"), - QuestionTemplate("research_tool_expression_shift", 1, "career_learning", ("D10", "D24", "Mercury", "A10"), "recent_three_years", "近三年是否明显进入写作、技术、系统化学习、工具搭建、内容表达、AI/研究类方向?", "Mercury_D24_A10_cluster", "against_learning_expression_cluster"), - QuestionTemplate("health_crisis_or_low_period", 2, "health_pressure", ("D30", "6H", "8H", "Saturn/Mars"), "largest_pressure_window", "某个压力窗口附近,是否有健康、事故、低谷、睡眠/精神压力或身体负担明显阶段?", "D30_crisis_cluster", "against_D30_crisis_cluster"), - QuestionTemplate("public_role_or_project_visibility", 2, "public_work", ("A10", "D10", "AmK", "Karakamsha"), "career_visibility_window", "某个事业窗口附近,是否有项目公开、作品产出、职位/身份变化或被他人看见的机会?", "A10_public_visibility_cluster", "against_A10_cluster"), - QuestionTemplate("sequence_inner_vs_outer", 3, "fine_timing", ("KP_cusp", "Pratyantar", "Dasha_boundary"), "top_candidate_window", "关键变化更像先有内在转向、后有外部结果,还是几乎同时发生?", "fine_boundary_cluster", "neutral"), -) - - -def build_questions() -> list[RectificationQuestion]: - return [ - { - "id": template.id, - "round": template.round, - "domain": template.domain, - "sensitivity": list(template.sensitivity), - "window": template.window, - "prompt": template.prompt, - "options": list(OPTIONS), - "scoring_map": { - "A": {"effect": "support", "cluster": template.yes_bias, "points": 2}, - "B": {"effect": "weak_support", "cluster": template.yes_bias, "points": 1}, - "C": {"effect": "exclude_or_penalize", "cluster": template.no_bias, "points": -2}, - "D": {"effect": "neutral", "cluster": "neutral", "points": 0}, - }, - } - for template in QUESTION_TEMPLATES - ] - - -def score_answers( - questionnaire: Mapping[str, JsonValue], - answers: Mapping[str, str], -) -> ScoringResult: - questions_value = questionnaire.get("questions") - questions = questions_value if isinstance(questions_value, list) else [] - by_id = { - question["id"]: question - for question in questions - if isinstance(question, dict) and isinstance(question.get("id"), str) - } - canonical_by_id = {question["id"]: question for question in build_questions()} - cluster_scores: dict[str, int] = {} - applied: list[AppliedScore] = [] - unknown_ids: list[str] = [] - invalid_answers: list[InvalidAnswer] = [] - - for question_id, raw_choice in answers.items(): - question = by_id.get(question_id) - if not question: - unknown_ids.append(question_id) - continue - choice = raw_choice.strip().upper() - scoring_map = question.get("scoring_map") - if not isinstance(scoring_map, dict): - canonical = canonical_by_id.get(question_id) - scoring_map = canonical["scoring_map"] if canonical else None - scoring = scoring_map.get(choice) if isinstance(scoring_map, dict) else None - if not isinstance(scoring, dict): - invalid_answers.append({"id": question_id, "answer": raw_choice}) - continue - cluster_value = scoring.get("cluster") - points_value = scoring.get("points") - cluster = cluster_value if isinstance(cluster_value, str) else "neutral" - points = int(points_value) if isinstance(points_value, int | float | str) else 0 - if cluster != "neutral": - cluster_scores[cluster] = cluster_scores.get(cluster, 0) + points - applied.append({"id": question_id, "answer": choice, "cluster": cluster, "points": points}) - - answered_ids = {item["id"] for item in applied} - unanswered = [question for question in questions if question.get("id") not in answered_ids] - round_values = [question.get("round") for question in unanswered] - next_round = min((int(value) for value in round_values if isinstance(value, int | float | str)), default=None) - rankings = [ - {"cluster": cluster, "score": score} - for cluster, score in sorted(cluster_scores.items(), key=lambda item: (-item[1], item[0])) - ] - return { - "scope": "active_birth_time_rectification_scoring", - "schema_version": 1, - "answered_count": len(applied), - "candidate_cluster_rankings": rankings, - "next_round": next_round, - "next_round_questions": [question for question in unanswered if question.get("round") == next_round], - "applied_scoring": applied, - "unknown_question_ids": unknown_ids, - "invalid_answers": invalid_answers, - "boundary": "This narrows candidate clusters only; final rectification requires scoring answers against actual candidate chart differences.", - } diff --git a/scripts/api_heavy_compute_gate.py b/scripts/api_heavy_compute_gate.py index 6dedfa1a0..70694b9b8 100644 --- a/scripts/api_heavy_compute_gate.py +++ b/scripts/api_heavy_compute_gate.py @@ -28,16 +28,8 @@ HEAVY_COMPUTE_PATHS = frozenset( { "/api/rectification/sensitivity_scan", "/api/active_rectification_events", - "/api/active_rectification_events_v4", - "/api/rectification/v5/candidate-features", - "/api/rectification/v5/score", "/api/rectification/v5/varga-segments", - "/api/rectification/v5/diagnostics", - "/api/rectification/v5/vedastro-validate", "/api/rectification/v5/range_reading", - "/api/rectification/v5/block_scan", - "/api/dynamic_rectification_opportunities", - "/api/dynamic_rectification_score", "/api/high_rigor_workflow", "/api/consultation_workflow", "/api/professional_reading", diff --git a/scripts/api_process_pool/pool.py b/scripts/api_process_pool/pool.py index a089aa3fe..f5715e494 100644 --- a/scripts/api_process_pool/pool.py +++ b/scripts/api_process_pool/pool.py @@ -27,8 +27,6 @@ from typing import Any ENV_PROCESSES = "JYOTISH_HEAVY_COMPUTE_PROCESSES" POOLED_METHODS = frozenset({ - "_compute_rectification_v5_score", - "_compute_rectification_v5_block_scan", "professional_report_reference", }) diff --git a/scripts/birth_window_range_reading.py b/scripts/birth_window_range_reading.py new file mode 100644 index 000000000..be4b699d3 --- /dev/null +++ b/scripts/birth_window_range_reading.py @@ -0,0 +1,87 @@ +"""Stable vs minute-sensitive reading themes across a declared birth window. + +Serves `/api/rectification/v5/range_reading` for consultation (a person whose +birth time is a range). Moved out of the retired rectification V5 API service +on 2026-11-06; behaviour unchanged. +""" +from __future__ import annotations + +from typing import Any, Mapping + + +def range_reading(request: Mapping[str, Any]) -> dict[str, Any]: + """Stable vs minute-sensitive themes for one unresolved clock window.""" + from types import SimpleNamespace + + from scripts.jyotish_engine import _build_birth_time_sensitivity + + body = dict(request or {}) + birth_date = str(body.get("birth_date") or "").strip() + if birth_date: + year_text, month_text, day_text = birth_date.split("-", 2) + year, month, day = int(year_text), int(month_text), int(day_text) + else: + year, month, day = int(body["year"]), int(body["month"]), int(body["day"]) + representative = str(body.get("representative_time") or "")[:5] + if len(representative) == 5 and representative[2] == ":": + hour, minute = int(representative[:2]), int(representative[3:]) + else: + hour = int(body.get("hour") or 12) + minute = int(body.get("minute") or 0) + representative = f"{hour:02d}:{minute:02d}" + raw_range = body.get("candidate_range") + if isinstance(raw_range, Mapping): + start_time = str(raw_range.get("start_time") or "")[:5] + end_time = str(raw_range.get("end_time") or "")[:5] + representative = str(raw_range.get("representative_time") or representative)[:5] + else: + start_time = str(body.get("start_time") or "")[:5] + end_time = str(body.get("end_time") or "")[:5] + hour, minute = int(representative[:2]), int(representative[3:]) + accuracy = str(body.get("birth_time_accuracy") or "provisional") + args = SimpleNamespace( + year=year, + month=month, + day=day, + hour=hour, + minute=minute, + second=0, + lat=float(body["lat"]), + lon=float(body["lon"]), + tz=float(body["tz"]), + ayanamsa=body.get("ayanamsa") or "raman", + node_mode=body.get("node_mode") or "mean", + birth_time_accuracy=accuracy, + candidate_range={ + "start_time": start_time, + "end_time": end_time, + "representative_time": representative, + }, + representative_time=representative, + declared_window_start=None, + declared_window_end=None, + uncertainty_before_minutes=None, + uncertainty_after_minutes=None, + ) + sensitivity = _build_birth_time_sensitivity(args) + themes = sensitivity.get("theme_sensitivity") + themes = themes if isinstance(themes, dict) else {} + stable = [ + key for key, row in themes.items() + if isinstance(row, dict) and row.get("status") == "stable" + ] + sensitive = [ + key for key, row in themes.items() + if isinstance(row, dict) and row.get("status") == "sensitive" + ] + return { + "window": sensitivity.get("window"), + "stable_themes": stable, + "sensitive_themes": sensitive, + "claim_boundary": sensitivity.get("claim_boundary"), + "theme_sensitivity": themes, + "accuracy": sensitivity.get("accuracy"), + "status": sensitivity.get("status"), + } + + diff --git a/scripts/conversational_minute_rectification_replay.py b/scripts/conversational_minute_rectification_replay.py deleted file mode 100644 index 5e4227b2e..000000000 --- a/scripts/conversational_minute_rectification_replay.py +++ /dev/null @@ -1,204 +0,0 @@ -#!/usr/bin/env python3 -"""Replay public structured events and a fixture-labeled transport filter.""" -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.minute_rectification_blind_eval import ( # noqa: E402 - _candidate_moments, - _clock_distance, - _opaque_winner, - _request, -) -from scripts.minute_rectification_fact_ranker_v4 import ( # noqa: E402 - rank_fact_rows, - score_fact_ranker_v4, -) -from scripts.minute_rectification_feature_facts_v4 import build_feature_fact_rows # noqa: E402 - -DEFAULT_MANIFEST = ROOT / "references/real_case_calibration/conversational_rectification_development_v1.json" - - -def _load(path: Path) -> dict[str, Any]: - return json.loads(path.read_text(encoding="utf-8")) - - -def _source_cases(manifest: dict[str, Any], manifest_path: Path) -> dict[str, dict[str, Any]]: - source_path = ROOT / manifest["source_manifest"] - source = _load(source_path) - return {case["case_id"]: case for case in source["cases"]} - - -def _step_result(benchmark_id: str, case: dict[str, Any], events: list[dict[str, Any]]) -> dict[str, Any]: - if not events: - return { - "scored_event_count": 0, - "true_rank": None, - "predicted_time": None, - "minute_error": None, - "winning_segment": None, - "would_safely_converge": False, - "result_reasons": ["no_scoreable_events"], - } - request = _request(case, events) - candidates = _candidate_moments(case) - fact_rows = build_feature_fact_rows(request, candidates=candidates) - ranked_rows, _ = rank_fact_rows(fact_rows, request["events"]) - result = score_fact_ranker_v4(fact_rows, request["events"]) - truth = case["birth"]["time"] - truth_row = next(row for row in ranked_rows if row["time"] == truth) - top_score = max(row["score"] for row in ranked_rows) - top_score_class_size = sum(row["score"] == top_score for row in ranked_rows) - event_signature = ",".join(event["id"] for event in events) - deterministic_tiebreak = _opaque_winner( - f"{benchmark_id}:{event_signature}", case["case_id"], ranked_rows - ) - true_rank = 1 + sum(row["score"] > truth_row["score"] for row in ranked_rows) - segment = result["winning_segment"] - neighbor_passed = result["stability_diagnostics"]["neighbor_stability"]["all_required_passed"] - leave_one_out_passed = result["stability_diagnostics"]["leave_one_event_out"]["status"] == "pass" - blocking_reasons = [reason for reason in result["reasons"] if reason != "fact_ranker_v4_holdout_not_ready"] - runtime_confirmation_candidate = ( - len(events) >= 5 - and len({event["domain"] for event in events}) >= 3 - and segment is not None - and segment["width_minutes"] == 1 - and neighbor_passed - and leave_one_out_passed - and not blocking_reasons - ) - predicted = deterministic_tiebreak if segment and segment["width_minutes"] == 1 else None - offline_truth_qualified_success = ( - runtime_confirmation_candidate - and true_rank == 1 - and predicted is not None - and _clock_distance(predicted, truth) <= 2 - ) - return { - "scored_event_count": len(events), - "true_rank": true_rank, - "truth_in_top_score_tie": truth_row["score"] == top_score, - "top_score_class_size": top_score_class_size, - "predicted_time": predicted, - "minute_error": _clock_distance(predicted, truth) if predicted else None, - "deterministic_tiebreak_time": deterministic_tiebreak, - "deterministic_tiebreak_error": _clock_distance(deterministic_tiebreak, truth), - "winning_segment": segment, - "neighbor_stability_passed": neighbor_passed, - "leave_one_event_out_passed": leave_one_out_passed, - "runtime_confirmation_candidate": runtime_confirmation_candidate, - "offline_truth_qualified_success": offline_truth_qualified_success, - "result_reasons": result["reasons"], - } - - -def run(manifest_path: Path = DEFAULT_MANIFEST) -> dict[str, Any]: - manifest = _load(manifest_path) - sources = _source_cases(manifest, manifest_path) - case_results = [] - for replay_case in manifest["cases"]: - case = sources[replay_case["case_id"]] - by_event_id = {event["id"]: event for event in case["events"]} - oracle_events: list[dict[str, Any]] = [] - product_events: list[dict[str, Any]] = [] - turns = [] - for turn_index, disclosure in enumerate(replay_case["disclosure_order"], start=1): - event = by_event_id[disclosure["event_id"]] - oracle_events.append(event) - if disclosure["expected_route_scoreable"]: - product_events.append(event) - turns.append({ - "turn": turn_index, - "event_id": event["id"], - "user_utterance": disclosure["user_utterance"], - "route_scoreable": disclosure["expected_route_scoreable"], - "oracle_structured": _step_result( - manifest["benchmark_id"], case, oracle_events, - ), - "simulated_current_transport_filter": _step_result( - manifest["benchmark_id"], case, product_events, - ), - }) - final_oracle = turns[-1]["oracle_structured"] - final_product = turns[-1]["simulated_current_transport_filter"] - case_results.append({ - "case_id": case["case_id"], - "published_time": case["birth"]["time"], - "turns": turns, - "final_oracle_structured": final_oracle, - "final_simulated_current_transport_filter": final_product, - }) - - def summary(key: str) -> dict[str, Any]: - finals = [case[key] for case in case_results] - segments = [item["winning_segment"] for item in finals if item["winning_segment"]] - return { - "case_count": len(finals), - "cases_reaching_five_scoreable_events": sum( - item["scored_event_count"] >= 5 for item in finals - ), - "truth_rank_le_3_rate": round( - sum((item["true_rank"] or 999) <= 3 for item in finals) / len(finals), 4 - ), - "deterministic_tiebreak_mean_absolute_error": round( - sum(item["deterministic_tiebreak_error"] for item in finals) / len(finals), 4 - ), - "truth_in_top_score_tie_rate": round( - sum(item["truth_in_top_score_tie"] for item in finals) / len(finals), 4 - ), - "unique_minute_count": sum( - segment["width_minutes"] == 1 for segment in segments - ), - "mean_winning_segment_width_minutes": round( - sum(segment["width_minutes"] for segment in segments) / len(segments), 4 - ) if segments else None, - "neighbor_stability_pass_count": sum(item["neighbor_stability_passed"] for item in finals), - "leave_one_event_out_pass_count": sum(item["leave_one_event_out_passed"] for item in finals), - "runtime_confirmation_candidate_count": sum( - item["runtime_confirmation_candidate"] for item in finals - ), - "offline_truth_qualified_success_count": sum( - item["offline_truth_qualified_success"] for item in finals - ), - } - - return { - "scope": "conversational_minute_rectification_entry_smoke_replay", - "benchmark_id": manifest["benchmark_id"], - "status": "diagnostics_available", - "cases": case_results, - "summary": { - "oracle_structured": summary("final_oracle_structured"), - "simulated_current_transport_filter": summary( - "final_simulated_current_transport_filter" - ), - }, - "excluded_from_holdout": True, - "may_open_release_gate": False, - "boundary": ( - "This is a structured-event smoke replay. TypeScript tests separately assert the " - "fixture's current extractor behavior; the Python filter is not an end-to-end product " - "transport. Cases below five scoreable events cannot evaluate Skill-level convergence." - ), - } - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) - parser.add_argument("--output", type=Path) - args = parser.parse_args() - result = run(args.manifest) - rendered = json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True) - if args.output: - args.output.write_text(rendered + "\n", encoding="utf-8") - else: - print(rendered) diff --git a/scripts/dynamic_rectification.py b/scripts/dynamic_rectification.py deleted file mode 100644 index 978e125c2..000000000 --- a/scripts/dynamic_rectification.py +++ /dev/null @@ -1,250 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [] -# /// -# ─── How to run ─── -# .venv/bin/python -m pytest -q tests/test_dynamic_rectification_scoring.py -"""Public dynamic-rectification packet and deterministic scoring entrypoints.""" - -from __future__ import annotations - -from collections.abc import Sequence -from typing import Literal, TypedDict -from uuid import NAMESPACE_URL, uuid5 - -from scripts.dynamic_rectification_opportunities import ( - ALGORITHM_VERSION, - OPPORTUNITY_MODEL_VERSION, - SUPPORTED_DIMENSIONS, - candidate_times, - candidate_window_rows, - canonical_hash, - compute_candidate_model, - experience_windows, - historical_event_fingerprint, - opportunities, - validate_candidate_model, -) - -Confidence = Literal["low", "medium", "high"] -_candidate_times = candidate_times -_candidate_window_rows = candidate_window_rows -_canonical_hash = canonical_hash -_experience_windows = experience_windows -_opportunities = opportunities -_validate_candidate_model = validate_candidate_model - - -class ChoiceRow(TypedDict): - time: str - score: float - - -class WinningSegment(TypedDict): - start_time: str - end_time: str - representative_time: str - width_minutes: int - - -def _compute_candidate_model(request: dict) -> dict: - return compute_candidate_model(request, _candidate_window_rows) - - -def build_difference_packet(request: dict) -> dict: - """Build reusable candidate activations and unused high-gain opportunities.""" - candidates = _candidate_times( - request["birth_date"], request["start_time"], request["end_time"] - ) - _validated_choice_evidence(request.get("evidence"), candidates) - persisted = request.get("candidate_model") - model = ( - _compute_candidate_model(request) - if persisted is None - or persisted.get("opportunity_model_version") != OPPORTUNITY_MODEL_VERSION - or persisted.get("historical_event_fingerprint") != historical_event_fingerprint(request) - else _validate_candidate_model(persisted, request) - ) - dismissed = set(request.get("dismissed_opportunity_ids", [])) - fingerprints = set(request.get("partition_fingerprints", [])) - unused = [ - item for item in _opportunities(model) - if item["opportunity_id"] not in dismissed - and item["candidate_partition_fingerprint"] not in fingerprints - ] - return { - "case_id": request["case_id"], - "scoring_version": ALGORITHM_VERSION, - "current_range": { - "start_time": request["start_time"], "end_time": request["end_time"] - }, - "opportunities": unused, - "asked_question_fingerprints": list(request.get("question_fingerprints", [])), - "candidate_partition_fingerprints": list(request.get("partition_fingerprints", [])), - "recent_range_history": list(request.get("recent_ranges", [])), - "candidate_model": model, - } - - -def _minute_value(value: str) -> int: - hour, minute = value.split(":", maxsplit=1) - return int(hour) * 60 + int(minute) - - -def _winning_segments(rows: Sequence[ChoiceRow], top_score: float) -> list[list[ChoiceRow]]: - segments: list[list[ChoiceRow]] = [] - for row in rows: - if row["score"] != top_score: - continue - follows = bool(segments) and ( - _minute_value(row["time"]) - _minute_value(segments[-1][-1]["time"]) - ) % 1_440 == 1 - if follows: - segments[-1].append(row) - else: - segments.append([row]) - return segments - - -def adjudicate_choice_rows( - rows: Sequence[ChoiceRow], *, effective_answer_count: int, dimension_count: int, - missing_layers: Sequence[str], request_fingerprint: str = "", -) -> dict: - """Apply v2 confidence gates while preserving submitted candidate chronology.""" - ranked = list(rows) - scores = sorted({row["score"] for row in ranked}, reverse=True) - top_score = scores[0] if scores else 0.0 - second_score = scores[1] if len(scores) > 1 else top_score - segments = _winning_segments(ranked, top_score) if ranked else [] - winning_rows = segments[0] if len(segments) == 1 else [] - segment: WinningSegment | None = None - if winning_rows: - segment = { - "start_time": winning_rows[0]["time"], - "end_time": winning_rows[-1]["time"], - "representative_time": winning_rows[(len(winning_rows) - 1) // 2]["time"], - "width_minutes": len(winning_rows), - } - margin = round((top_score - second_score) / max(abs(top_score), 1.0) * 100, 2) - blocked = len(segments) != 1 or bool(missing_layers) - high = ( - not blocked and effective_answer_count >= 4 and dimension_count >= 3 - and segment is not None and segment["width_minutes"] <= 5 and margin >= 20 - ) - medium = ( - not blocked and effective_answer_count >= 3 and dimension_count >= 2 - and segment is not None and segment["width_minutes"] <= 15 and margin >= 10 - ) - confidence: Confidence = "high" if high else "medium" if medium else "low" - reasons = [] - if len(segments) != 1: - reasons.append("tied_leader" if segments else "no_candidate_rows") - if missing_layers: - reasons.append("missing_mandatory_layers") - if confidence == "low" and effective_answer_count < 3: - reasons.append("insufficient_effective_evidence") - fingerprint = request_fingerprint or _canonical_hash(ranked) - return { - "result_id": str(uuid5(NAMESPACE_URL, f"{ALGORITHM_VERSION}:{fingerprint}")), - "confidence": confidence, - "can_apply": confidence == "high", - "winning_segment": segment, - "event_count": effective_answer_count, - "domain_count": dimension_count, - "top_score": top_score, - "second_score": second_score, - "margin_percent": margin, - "reasons": reasons, - "evidence": [], - "algorithm_version": ALGORITHM_VERSION, - "evidence_mode": "dynamic_choice", - "effective_answer_count": effective_answer_count, - "dimension_count": dimension_count, - } - - -def _validated_choice_evidence( - evidence_rows: list | None, candidates: Sequence[str], -) -> tuple[list[dict], set[str]]: - if not isinstance(evidence_rows, list): - raise ValueError("choice evidence must contain partition evidence") - if len(evidence_rows) > 10: - raise ValueError("choice evidence may contain at most 10 rows") - question_ids: set[str] = set() - dimensions: set[str] = set() - required = { - "question_id", "opportunity_id", "partition_id", "dimension_code", - "candidate_scores", "information_gain", - } - for evidence in evidence_rows: - if not isinstance(evidence, dict) or set(evidence) != required: - field = ( - "option_id" - if isinstance(evidence, dict) and "option_id" in evidence - else "partition evidence" - ) - raise ValueError(f"choice evidence contains invalid {field}") - question_id = evidence["question_id"].strip() if isinstance(evidence["question_id"], str) else "" - if not question_id: - raise ValueError("partition evidence question identifier must be non-empty") - if question_id in question_ids: - raise ValueError("duplicate question evidence is not allowed") - if any( - not isinstance(evidence[key], str) or not evidence[key].strip() - for key in ("opportunity_id", "partition_id") - ): - raise ValueError("partition evidence identifier must be a non-empty string") - _validate_scores(evidence, candidates) - if evidence["dimension_code"] not in SUPPORTED_DIMENSIONS: - raise ValueError("choice evidence dimension is unsupported") - question_ids.add(question_id) - dimensions.add(evidence["dimension_code"]) - return evidence_rows, dimensions - - -def _validate_scores(evidence: dict, candidates: Sequence[str]) -> None: - import math - - scores = evidence["candidate_scores"] - gain = evidence["information_gain"] - valid_scores = isinstance(scores, dict) and set(scores) == set(candidates) and all( - not isinstance(score, bool) - and isinstance(score, int | float) - and math.isfinite(score) - and score >= 0 - for score in scores.values() - ) - if not valid_scores: - raise ValueError("candidate scores must exactly match the submitted range") - if ( - isinstance(gain, bool) or not isinstance(gain, int | float) - or not math.isfinite(gain) or gain < 0 - ): - raise ValueError("choice evidence information gain must be finite") - - -def score_choice_evidence(request: dict) -> dict: - """Sum only strict server-resolved primary evidence, then adjudicate it.""" - candidates = _candidate_times( - request["birth_date"], request["start_time"], request["end_time"] - ) - evidence_rows, dimensions = _validated_choice_evidence( - request.get("choice_evidence"), candidates - ) - totals = {candidate: 0.0 for candidate in candidates} - for evidence in evidence_rows: - for candidate in candidates: - totals[candidate] += ( - float(evidence["candidate_scores"][candidate]) - * float(evidence["information_gain"]) - ) - rows: list[ChoiceRow] = [ - {"time": candidate, "score": round(score, 6)} for candidate, score in totals.items() - ] - return adjudicate_choice_rows( - rows, - effective_answer_count=len(evidence_rows), - dimension_count=len(dimensions), - missing_layers=[], - request_fingerprint=_canonical_hash(request), - ) diff --git a/scripts/dynamic_rectification_copy.py b/scripts/dynamic_rectification_copy.py deleted file mode 100644 index c41cdeeec..000000000 --- a/scripts/dynamic_rectification_copy.py +++ /dev/null @@ -1,59 +0,0 @@ -"""Localized public copy for dynamic birth-time rectification choices.""" - -from __future__ import annotations - -from collections.abc import Sequence -from datetime import date -from typing import Final, Literal, TypedDict, assert_never - -DIMENSION_CONTEXT: Final = { - "education": "一次明显的升学、转学或学习方向变化", - "relocation": "一次明显的搬家、离乡或长期居住地变化", - "relationship": "一次明显的关系进入、结束或重要转变", - "career": "一次明显的工作、职业方向或身份变化", - "health_pressure": "一次持续的健康压力或生活压力变化", -} -SUPPORTED_DIMENSIONS: Final = frozenset(DIMENSION_CONTEXT) - - -class DateRange(TypedDict): - window_start: str - window_end: str - - -RangePrecision = Literal["year", "month", "day"] - - -def _range_label(item: DateRange, precision: RangePrecision) -> str: - start = date.fromisoformat(item["window_start"]) - end = date.fromisoformat(item["window_end"]) - match precision: - case "year": - return f"{start.year} 年" if start.year == end.year else f"{start.year}—{end.year} 年" - case "month": - if start.year == end.year: - return f"{start.year} 年 {start.month} 月—{end.month} 月" - return f"{start.year} 年 {start.month} 月—{end.year} 年 {end.month} 月" - case "day": - if start.year == end.year and start.month == end.month: - return f"{start.year} 年 {start.month} 月 {start.day} 日—{end.day} 日" - return ( - f"{start.year} 年 {start.month} 月 {start.day} 日—" - f"{end.year} 年 {end.month} 月 {end.day} 日" - ) - case unreachable: - assert_never(unreachable) - - -def visible_range_labels(items: Sequence[DateRange]) -> list[str]: - """Use the least date precision that keeps every visible range distinct.""" - labels = [_range_label(item, "year") for item in items] - for precision in ("month", "day"): - duplicates = {label for label in labels if labels.count(label) > 1} - if not duplicates: - break - labels = [ - _range_label(item, precision) if label in duplicates else label - for item, label in zip(items, labels, strict=True) - ] - return labels diff --git a/scripts/dynamic_rectification_fact_priority.py b/scripts/dynamic_rectification_fact_priority.py deleted file mode 100644 index 02363b3a7..000000000 --- a/scripts/dynamic_rectification_fact_priority.py +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env python3 -"""Shadow-only categorical birth-minute differences for question selection.""" -from __future__ import annotations - -import hashlib -import json -import math -from collections import defaultdict -from typing import Any, Final - -from scripts import active_rectification_event_engine as engine -from scripts.dynamic_rectification_copy import SUPPORTED_DIMENSIONS -from scripts.minute_rectification_feature_facts_v4 import ( - build_fact_difference_opportunities, - build_feature_fact_rows, -) - -FACT_PRIORITY_VERSION: Final = "birth-time-question-fact-priority-v1" -EVENT_FACT_PRIORITY_VERSION: Final = "birth-time-question-event-fact-priority-v1" - - -def _fingerprint(value: Any) -> str: - canonical = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")) - return hashlib.sha256(canonical.encode("utf-8")).hexdigest() - - -def _arudha_keys(domain: str) -> tuple[str, ...]: - if domain == "relationship": - return ("A7", "UL") - if domain == "career": - return ("A10",) - return () - - -def build_domain_fact_priorities(request: dict) -> dict[str, dict[str, Any]]: - """Measure categorical D-varga/Arudha/AV differences without scoring them.""" - candidates = engine._candidate_datetimes(request) - signatures: dict[str, list[tuple[str, str]]] = { - domain: [] for domain in SUPPORTED_DIMENSIONS - } - for candidate_at in candidates: - chart = engine.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": engine.AYANAMSA, - "node_mode": engine.NODE_MODE, - }) - planet_longitudes = { - name: float(value["lon"]) - for name, value in chart.get("planets", {}).items() - if isinstance(value, dict) and isinstance(value.get("lon"), int | float) - } - ascendant_longitude = float(chart["ascendant"]["lon"]) - ascendant_index = int(ascendant_longitude // 30) - vargas = engine.varga.calc_all_vargas( - planet_longitudes, ascendant_longitude, divisions=[2, 4, 9, 10, 24, 30], - ) - d11 = engine._d11_chart(planet_longitudes, ascendant_longitude) - arudha_result = engine.jaimini.calc_arudha_padas(ascendant_index, planet_longitudes) - arudha = { - **(arudha_result.get("padas") or {}), - "UL": arudha_result.get("upapada") or {}, - } - av = engine.ashtakavarga.calc_ashtakavarga(chart.get("planets", {}), ascendant_index) - av_scores = av.get("house_scores_full") or {} - for domain in SUPPORTED_DIMENSIONS: - prefixes, target_houses = engine.DOMAIN_CONFIG[domain] - domain_vargas = [ - d11 if prefix == "D11" else engine._varga_chart(vargas, prefix) - for prefix in prefixes - ] - facts = { - "varga_ascendant_signs": { - prefix: (item.get("Ascendant") or {}).get("sign_idx") if item else None - for prefix, item in zip(prefixes, domain_vargas, strict=True) - }, - "arudha_signs": { - key: (arudha.get(key) or {}).get("sign_idx") - for key in _arudha_keys(domain) - }, - "ashtakavarga_target_house_scores": { - str(house): (av_scores.get(f"house_{house}") or {}).get("sav_score") - for house in target_houses - }, - } - signatures[domain].append((candidate_at.strftime("%H:%M"), _fingerprint(facts))) - - result = {} - for domain, rows in signatures.items(): - groups: dict[str, list[str]] = defaultdict(list) - for candidate_time, fingerprint in rows: - groups[fingerprint].append(candidate_time) - probabilities = [len(times) / len(rows) for times in groups.values()] if rows else [] - entropy = ( - -sum(value * math.log(value) for value in probabilities) / math.log(len(groups)) - if len(groups) > 1 else 0.0 - ) - adjacent_changes = sum( - previous[1] != current[1] for previous, current in zip(rows, rows[1:]) - ) - result[domain] = { - "fact_priority_version": FACT_PRIORITY_VERSION, - "selection_priority": round(entropy, 6), - "unique_signature_count": len(groups), - "adjacent_change_count": adjacent_changes, - "shadow_only": True, - "may_affect_candidate_score": False, - } - return result - - -def build_historical_event_priorities(request: dict) -> dict[str, dict[str, Any]]: - """Rank domains by real event-specific Dasha and placement differences.""" - events = list(request.get("historical_events") or []) - empty = { - domain: { - "event_fact_priority_version": EVENT_FACT_PRIORITY_VERSION, - "selection_priority": 0.0, - "discriminating_event_ids": [], - "shadow_only": True, - "may_affect_candidate_score": False, - } - for domain in SUPPORTED_DIMENSIONS - } - if not events: - return empty - event_request = { - key: request[key] - for key in ("birth_date", "start_time", "end_time", "lat", "lon", "tz") - } | {"events": events} - candidates = engine._candidate_datetimes(event_request) - opportunities = build_fact_difference_opportunities(build_feature_fact_rows( - event_request, - candidates=candidates, - )) - by_domain: dict[str, list[dict[str, Any]]] = defaultdict(list) - for opportunity in opportunities: - if opportunity["domain"] in SUPPORTED_DIMENSIONS: - by_domain[opportunity["domain"]].append(opportunity) - return { - domain: { - "event_fact_priority_version": EVENT_FACT_PRIORITY_VERSION, - "selection_priority": round(max( - (item["estimated_information_gain"] for item in by_domain[domain]), - default=0.0, - ), 6), - "discriminating_event_ids": sorted({ - item["event_id"] for item in by_domain[domain] - }), - "shadow_only": True, - "may_affect_candidate_score": False, - } - for domain in SUPPORTED_DIMENSIONS - } diff --git a/scripts/dynamic_rectification_opportunities.py b/scripts/dynamic_rectification_opportunities.py deleted file mode 100644 index 2c29f5776..000000000 --- a/scripts/dynamic_rectification_opportunities.py +++ /dev/null @@ -1,380 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [] -# /// -# ─── How to run ─── -# .venv/bin/python -m pytest -q tests/test_dynamic_rectification.py -"""Candidate-model construction and opportunity partitioning for rectification.""" - -from __future__ import annotations - -import hashlib -import json -import math -from collections import defaultdict -from collections.abc import Callable, Mapping, Sequence -from datetime import date, datetime, time, timedelta -from typing import Final -from uuid import NAMESPACE_URL, uuid5 - -from scripts.dynamic_rectification_copy import ( - DIMENSION_CONTEXT, - SUPPORTED_DIMENSIONS, - visible_range_labels, -) -from scripts.dynamic_rectification_fact_priority import ( - EVENT_FACT_PRIORITY_VERSION, - FACT_PRIORITY_VERSION, - build_domain_fact_priorities, - build_historical_event_priorities, -) - -ALGORITHM_VERSION: Final = "birth-time-choice-scoring-v2" -OPPORTUNITY_MODEL_VERSION: Final = "birth-time-opportunity-model-v4" -MIN_INFORMATION_GAIN: Final = 0.15 - - -def canonical_hash(value: Mapping | Sequence) -> str: - encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")) - return hashlib.sha256(encoded.encode("utf-8")).hexdigest() - - -def candidate_times(birth_date: str, start_time: str, end_time: str) -> list[str]: - day = date.fromisoformat(birth_date) - start = datetime.combine(day, time.fromisoformat(start_time)) - end = datetime.combine(day, time.fromisoformat(end_time)) - if end < start: - end += timedelta(days=1) - count = int((end - start).total_seconds() // 60) + 1 - if not 1 <= count <= 1_440: - raise ValueError("candidate range must contain between 1 and 1440 minutes") - return [(start + timedelta(minutes=offset)).strftime("%H:%M") for offset in range(count)] - - -def experience_window_sets( - birth_date: str, as_of_date: str, -) -> list[tuple[str, list[tuple[date, date]]]]: - born = date.fromisoformat(birth_date) - as_of = date.fromisoformat(as_of_date) - try: - first = born.replace(year=born.year + 12) - except ValueError: - first = born.replace(year=born.year + 12, day=28) - if as_of < first: - return [] - day_count = (as_of - first).days + 1 - counts = [1] if day_count == 1 else list(range(2, min(4, day_count) + 1)) - return [ - ( - f"periods-{count}", - [ - ( - first + timedelta(days=day_count * index // count), - as_of if index == count - 1 else ( - first + timedelta(days=day_count * (index + 1) // count - 1) - ), - ) - for index in range(count) - ], - ) - for count in counts - ] - - -def experience_windows(birth_date: str, as_of_date: str) -> list[tuple[date, date]]: - sets = experience_window_sets(birth_date, as_of_date) - return sets[-1][1] if sets else [] - - -def candidate_window_rows(request: dict) -> list[dict]: - """Compute each candidate chart once and reuse it across every window.""" - from scripts.active_rectification_event_engine import ( - DOMAIN_CONFIG, - _candidate_datetimes, - _candidate_row, - ) - - window_sets = experience_window_sets(request["birth_date"], request["as_of_date"]) - if not window_sets: - return [] - events = [] - event_windows: dict[str, tuple[str, str, date, date]] = {} - for dimension in sorted(SUPPORTED_DIMENSIONS): - for window_group, windows in window_sets: - for window_start, window_end in windows: - event_id = str(uuid5( - NAMESPACE_URL, - f"{ALGORITHM_VERSION}:{window_group}:{dimension}:{window_start}:{window_end}", - )) - midpoint = window_start + (window_end - window_start) / 2 - events.append({ - "id": event_id, - "domain": dimension, - "date": midpoint.isoformat(), - "precision": "day", - }) - event_windows[event_id] = ( - window_group, dimension, window_start, window_end, - ) - calculation_request = { - "birth_date": request["birth_date"], - "start_time": request["start_time"], - "end_time": request["end_time"], - "lat": request["lat"], - "lon": request["lon"], - "tz": request["tz"], - "events": events, - } - candidates = _candidate_datetimes(calculation_request) - rows = [_candidate_row(calculation_request, candidate) for candidate in candidates] - fact_priorities = build_domain_fact_priorities(calculation_request) - event_priorities = build_historical_event_priorities({ - **calculation_request, - "historical_events": request.get("events") or [], - }) - activations = { - event_id: {row["time"]: 0.0 for row in rows} for event_id in event_windows - } - missing = {layer for row in rows for layer in row["missing_layers"]} - for row in rows: - for evidence in row["evidence"]: - activations[evidence["event_id"]][row["time"]] = float(evidence["points"]) - return [ - { - "window_group": window_group, - "dimension_code": dimension, - "window_start": window_start.isoformat(), - "window_end": window_end.isoformat(), - "activations": activations[event_id], - "missing_layers": sorted(set(DOMAIN_CONFIG[dimension][0]) & missing), - "fact_selection_priority": fact_priorities[dimension]["selection_priority"], - "fact_priority_version": FACT_PRIORITY_VERSION, - "event_fact_selection_priority": event_priorities[dimension]["selection_priority"], - "event_fact_priority_version": EVENT_FACT_PRIORITY_VERSION, - } - for event_id, (window_group, dimension, window_start, window_end) in event_windows.items() - ] - - -def compute_candidate_model(request: dict, row_builder: Callable[[dict], list[dict]]) -> dict: - return { - "version": ALGORITHM_VERSION, - "opportunity_model_version": OPPORTUNITY_MODEL_VERSION, - "historical_event_fingerprint": historical_event_fingerprint(request), - "birth_date": request["birth_date"], - "as_of_date": request["as_of_date"], - "range": {"start_time": request["start_time"], "end_time": request["end_time"]}, - "location": { - "lat": request["lat"], - "lon": request["lon"], - "tz": request["tz"], - }, - "candidate_times": candidate_times( - request["birth_date"], request["start_time"], request["end_time"] - ), - "windows": row_builder(request), - } - - -def validate_candidate_model(model: dict, request: dict) -> dict: - expected = { - "version", "opportunity_model_version", "birth_date", "as_of_date", "range", "location", - "candidate_times", "windows", "historical_event_fingerprint", - } - candidates = candidate_times(request["birth_date"], request["start_time"], request["end_time"]) - try: - valid_header = ( - set(model) == expected - and model["version"] == ALGORITHM_VERSION - and model["opportunity_model_version"] == OPPORTUNITY_MODEL_VERSION - and model["historical_event_fingerprint"] == historical_event_fingerprint(request) - and model["birth_date"] == request["birth_date"] - and model["as_of_date"] == request["as_of_date"] - and model["range"] == { - "start_time": request["start_time"], "end_time": request["end_time"] - } - and model["location"] == { - "lat": request["lat"], "lon": request["lon"], "tz": request["tz"] - } - and model["candidate_times"] == candidates - and isinstance(model["windows"], list) - ) - valid_windows = _validate_windows(model["windows"], request, candidates) - except (KeyError, TypeError, ValueError): - valid_header = valid_windows = False - if not valid_header or not valid_windows: - raise ValueError("candidate model does not match the submitted request") - return model - - -def _validate_windows(windows: list, request: dict, candidates: list[str]) -> bool: - generated = experience_window_sets(request["birth_date"], request["as_of_date"]) - minimum = generated[0][1][0][0] if generated else date.max - maximum = date.fromisoformat(request["as_of_date"]) - groups = {name for name, _windows in generated} - keys = [ - (row.get("window_group"), row.get("dimension_code"), row.get("window_start"), row.get("window_end")) - for row in windows if isinstance(row, dict) - ] - return len(keys) == len(set(keys)) and all( - isinstance(row, dict) - and set(row) == { - "window_group", "dimension_code", "window_start", "window_end", "activations", "missing_layers", - "fact_selection_priority", "fact_priority_version", - "event_fact_selection_priority", "event_fact_priority_version", - } - and row["window_group"] in groups - and row["dimension_code"] in SUPPORTED_DIMENSIONS - and minimum <= date.fromisoformat(row["window_start"]) - <= date.fromisoformat(row["window_end"]) <= maximum - and isinstance(row["activations"], dict) - and set(row["activations"]) == set(candidates) - and all( - not isinstance(score, bool) - and isinstance(score, int | float) - and math.isfinite(score) - and score >= 0 - for score in row["activations"].values() - ) - and isinstance(row["missing_layers"], list) - and all(isinstance(layer, str) and layer for layer in row["missing_layers"]) - and not isinstance(row["fact_selection_priority"], bool) - and isinstance(row["fact_selection_priority"], int | float) - and math.isfinite(row["fact_selection_priority"]) - and 0 <= row["fact_selection_priority"] <= 1 - and row["fact_priority_version"] == FACT_PRIORITY_VERSION - and not isinstance(row["event_fact_selection_priority"], bool) - and isinstance(row["event_fact_selection_priority"], int | float) - and math.isfinite(row["event_fact_selection_priority"]) - and 0 <= row["event_fact_selection_priority"] <= 1 - and row["event_fact_priority_version"] == EVENT_FACT_PRIORITY_VERSION - for row in windows - ) - - -def opportunities(model: dict) -> list[dict]: - grouped: dict[tuple[str, str], list[dict]] = defaultdict(list) - for row in model["windows"]: - if not row["missing_layers"]: - grouped[(row["dimension_code"], row["window_group"])].append(row) - variants: dict[str, list[dict]] = defaultdict(list) - for (dimension, window_group), windows in sorted(grouped.items()): - opportunity = _dimension_opportunity( - dimension, window_group, windows, model["candidate_times"], - ) - if opportunity is not None: - variants[dimension].append(opportunity) - selected = [ - sorted(items, key=lambda item: (-item["estimated_information_gain"], item["opportunity_id"]))[0] - for items in variants.values() - ] - result = sorted(selected, key=lambda item: ( - -item["_event_fact_selection_priority"], - -item["_fact_selection_priority"], - -item["estimated_information_gain"], - item["opportunity_id"], - )) - return [ - { - key: value for key, value in item.items() - if key not in {"_fact_selection_priority", "_event_fact_selection_priority"} - } - for item in result - ] - - -def _dimension_opportunity( - dimension: str, - window_group: str | list[dict], - windows: list[dict] | list[str], - candidates: list[str] | None = None, -) -> dict | None: - # Preserve the original three-argument helper contract for frozen fixtures; - # production calls always supply an explicit period-window group. - legacy_contract = candidates is None - if legacy_contract: - candidates = list(windows) - windows = list(window_group) - resolved_window_group: str | None = None - else: - resolved_window_group = str(window_group) - neutral_context = DIMENSION_CONTEXT[dimension] - memberships: dict[int, list[str]] = defaultdict(list) - for candidate in candidates: - winner = max( - range(len(windows)), - key=lambda index: (windows[index]["activations"][candidate], -index), - ) - memberships[winner].append(candidate) - populated = [(windows[index], members) for index, members in sorted(memberships.items())] - if not 2 <= len(populated) <= 4: - return None - probabilities = [len(members) / len(candidates) for _, members in populated] - gain = -sum(value * math.log(value) for value in probabilities) / math.log(len(populated)) - if gain < MIN_INFORMATION_GAIN: - return None - basis = [ - { - "version": ALGORITHM_VERSION, - "dimension": dimension, - "window_start": window["window_start"], - "window_end": window["window_end"], - "members": sorted(members), - } - for window, members in populated - ] - if resolved_window_group is not None: - basis = [{**item, "window_group": resolved_window_group} for item in basis] - labels = visible_range_labels([ - {"window_start": item["window_start"], "window_end": item["window_end"]} - for item in basis - ]) - partitions = [ - { - "partition_id": canonical_hash(item), - "descriptor": f"{item['window_start']}--{item['window_end']}", - "fallback_label": label, - "candidate_scores": { - candidate: 1.0 if candidate in item["members"] else 0.0 - for candidate in candidates - }, - } - for item, label in zip(basis, labels, strict=True) - ] - fingerprint = canonical_hash({"version": ALGORITHM_VERSION, "partitions": basis}) - return { - "opportunity_id": canonical_hash({ - "version": ALGORITHM_VERSION, "dimension": dimension, "partitions": basis - }), - "dimension_code": dimension, - "neutral_context": neutral_context, - "estimated_information_gain": round(gain, 6), - "candidate_partition_fingerprint": fingerprint, - "fallback_prompt": f"哪一个时间段更接近{neutral_context}?", - "partitions": partitions, - "_fact_selection_priority": max( - (float(window.get("fact_selection_priority", 0.0)) for window in windows), - default=0.0, - ), - "_event_fact_selection_priority": max( - (float(window.get("event_fact_selection_priority", 0.0)) for window in windows), - default=0.0, - ), - } - - -def historical_event_fingerprint(request: dict) -> str: - """Bind reusable private models to the exact normalized historical events.""" - events = sorted( - ( - { - "id": item["id"], - "domain": item["domain"], - "date": item["date"], - "precision": item["precision"], - } - for item in (request.get("events") or []) - ), - key=lambda item: (item["id"], item["domain"], item["date"], item["precision"]), - ) - return canonical_hash(events) diff --git a/scripts/jyotish_api_server.py b/scripts/jyotish_api_server.py index 0dc2d98e6..4b55d5ebb 100644 --- a/scripts/jyotish_api_server.py +++ b/scripts/jyotish_api_server.py @@ -399,26 +399,6 @@ def _compare_vedastro_minute_snapshots(candidate_snapshots): } -def _vedastro_minute_sensitive_candidate_times(result) -> list[str]: - decisions = result.get('candidate_decisions') if isinstance(result, dict) else None - times = [] - if not isinstance(decisions, list): - return times - for item in decisions: - if not isinstance(item, dict): - continue - time_value = item.get('time') - if ( - isinstance(time_value, str) - and re.fullmatch(r'(?:[01]\d|2[0-3]):[0-5]\d', time_value) - and time_value not in times - ): - times.append(time_value) - if len(times) == 2: - break - return times - - def _unevaluated_vedastro_minute_sensitive(reason: str) -> dict: return { 'status': 'not_evaluated', @@ -429,140 +409,6 @@ def _unevaluated_vedastro_minute_sensitive(reason: str) -> dict: } -def _evaluate_vedastro_minute_sensitive_pair(request, times: list[str]) -> dict: - if not isinstance(request, dict) or len(times) != 2: - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_pair_unavailable') - try: - birth_day = datetime.strptime(str(request.get('birth_date') or ''), '%Y-%m-%d') - lat = float(request['lat']) - lon = float(request['lon']) - tz = float(request['tz']) - except (KeyError, TypeError, ValueError): - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_request_incomplete') - try: - adapter = _load_local_module('vedastro_service_adapter') - except Exception: - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_adapter_unavailable') - - def snapshot_for(candidate_time: str): - hour, minute = candidate_time.split(':', 1) - case = { - 'year': birth_day.year, - 'month': birth_day.month, - 'day': birth_day.day, - 'hour': int(hour), - 'minute': int(minute), - 'second': 0, - 'lat': lat, - 'lon': lon, - 'tz': tz, - } - return _safe_vedastro_adapter_call( - adapter.run_rectification_minute_snapshot_for_case, - case, - case_id=f'rectification_v5_minute_{candidate_time.replace(":", "")}', - ) - - timeout = _foreground_vedastro_budget_seconds() - futures = [_FOREGROUND_VEDASTRO_EXECUTOR.submit(snapshot_for, candidate_time) for candidate_time in times] - reports = [] - deadline = time.monotonic() + timeout - for future in futures: - remaining = max(0.0, deadline - time.monotonic()) - try: - reports.append(future.result(timeout=remaining)) - except FuturesTimeoutError: - for pending in futures: - pending.cancel() - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_snapshot_timeout') - except Exception: - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_snapshot_error') - summaries = [ - _safe_vedastro_minute_snapshot_summary(candidate_time, report) - for candidate_time, report in zip(times, reports) - ] - if any( - report.get('status') == 'timeout' or report.get('_failure_kind') == 'timeout' - for report in reports - ): - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_snapshot_timeout') - complete = all( - _vedastro_minute_snapshot_is_complete(report, summary) - for report, summary in zip(reports, summaries) - ) - if not complete: - return _unevaluated_vedastro_minute_sensitive('vedastro_minute_snapshot_incomplete') - comparison = _compare_vedastro_minute_snapshots(summaries) - discriminated_layers = [ - str(name) for name in (comparison.get('discriminated_layers') or [])[:6] if name - ] - if comparison.get('discriminated'): - return { - 'status': 'passed', - 'summary': { - 'reason': 'minute_sensitive_layers_discriminated', - 'discriminated': True, - 'discriminated_layers': discriminated_layers, - }, - } - return { - 'status': 'failed', - 'summary': { - 'reason': 'vedastro_minute_sensitive_layers_not_discriminated', - 'discriminated': False, - }, - } - - -def _attach_vedastro_minute_sensitive_to_score(result, request): - if not isinstance(result, dict): - return result - receipt = result.get('decision_receipt') - if not isinstance(receipt, dict): - receipt = result.get('candidate_decision_receipt') - if not isinstance(receipt, dict): - return result - times = _vedastro_minute_sensitive_candidate_times(result) - from scripts.rectification.decision_policy import apply_vedastro_minute_sensitive_to_receipt - if len(times) < 2 or receipt.get('acceptance_allowed') is not True: - apply_vedastro_minute_sensitive_to_receipt( - receipt, - 'not_evaluated', - summary={ - 'reason': 'local_candidate_not_ready_for_minute_sensitive_check', - 'discriminated': False, - }, - ) - result['decision_receipt'] = receipt - if isinstance(result.get('candidate_decision_receipt'), dict): - result['candidate_decision_receipt'] = receipt - result['confirmation_allowed'] = receipt.get('confirmation_allowed') is True - return result - evaluation = _evaluate_vedastro_minute_sensitive_pair(request, times) - apply_vedastro_minute_sensitive_to_receipt( - receipt, - evaluation['status'], - summary=evaluation['summary'], - ) - result['decision_receipt'] = receipt - if 'candidate_decision_receipt' in result: - result['candidate_decision_receipt'] = receipt - result['confirmation_allowed'] = receipt.get('confirmation_allowed') is True - return result - - -def _safe_vedastro_adapter_call(call, *args, **kwargs): - try: - result = call(*args, **kwargs) - except TimeoutError: - return {'available': False, 'status': 'timeout', '_failure_kind': 'timeout'} - except Exception: - return {'available': False, 'status': 'exception', '_failure_kind': 'exception'} - if not isinstance(result, dict): - return {'available': False, 'status': 'invalid_response', '_failure_kind': 'exception'} - return result - - def _rectification_candidate_ready_for_external_validation(result): """Allow external validation once local scoring has a narrow, auditable lead.""" segment = result.get('winning_segment') @@ -3129,12 +2975,6 @@ API_COMMAND_MAP = { 'active-rectification-questions': '/api/active_rectification_questions', 'active-rectification-score': '/api/active_rectification_score', 'active-rectification-events': '/api/active_rectification_events', - 'active-rectification-events-v4': '/api/active_rectification_events_v4', - 'rectification-v5-candidate-features': '/api/rectification/v5/candidate-features', - 'rectification-v5-score': '/api/rectification/v5/score', - 'rectification-v5-diagnostics': '/api/rectification/v5/diagnostics', - 'rectification-v5-vedastro-validate': '/api/rectification/v5/vedastro-validate', - 'rectification-v5-versions': '/api/rectification/v5/versions', 'case-validation': '/api/case_validation', 'divisional-yoga': '/api/divisional_yoga', 'deep-varga-avastha': '/api/deep_varga_avastha', @@ -3169,14 +3009,7 @@ TECHNIQUE_EXAMPLE_ENDPOINTS = { '/api/active_rectification_questions', '/api/active_rectification_score', '/api/active_rectification_events', - '/api/active_rectification_events_v4', - '/api/rectification/v5/candidate-features', - '/api/rectification/v5/score', - '/api/rectification/v5/diagnostics', - '/api/rectification/v5/vedastro-validate', '/api/rectification/v5/range_reading', - '/api/rectification/v5/block_scan', - '/api/rectification/v5/versions', '/api/relationship', '/api/remedies', '/api/sade_sati', @@ -8408,239 +8241,8 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): **result, } - def _dynamic_rectification_base(self, body, allowed_fields, field_label): - unsupported_fields = sorted(set(body) - allowed_fields) - if unsupported_fields: - raise BadRequest(f'unsupported dynamic rectification {field_label} field: {unsupported_fields[0]}') - birth_date = body.get('birth_date') - start_time = body.get('start_time') - end_time = body.get('end_time') - if not isinstance(birth_date, str): - raise BadRequest('birth_date must be YYYY-MM-DD') - if not isinstance(start_time, str) or not isinstance(end_time, str): - raise BadRequest('candidate times must be HH:MM') - for key in ('lat', 'lon', 'tz'): - if key not in body or body[key] in (None, ''): - raise BadRequest(f'{key} is required') - try: - datetime.strptime(birth_date, '%Y-%m-%d') - datetime.strptime(start_time, '%H:%M') - datetime.strptime(end_time, '%H:%M') - except ValueError as exc: - raise BadRequest('birth date or candidate time has invalid format') from exc - return { - **body, - 'birth_date': birth_date, - 'start_time': start_time, - 'end_time': end_time, - 'lat': self._get_float(body, 'lat', 0, -90, 90), - 'lon': self._get_float(body, 'lon', 0, -180, 180), - 'tz': self._get_float(body, 'tz', 0, -14, 14), - } - - def _rectification_v5_request(self, body): - from scripts.rectification.contracts import normalize_rectification_request - try: - return normalize_rectification_request(body) - except ValueError as exc: - raise BadRequest(str(exc)) from exc - - def _compute_rectification_v5_versions(self, body=None): - from scripts.rectification.api_service import engine_scoring_versions - return { - 'success': True, - 'endpoint': 'rectification_v5_versions', - **engine_scoring_versions(), - } - - def _compute_rectification_v5_candidate_features(self, body): - from scripts.rectification.api_service import candidate_features - return { - 'success': True, - 'endpoint': 'rectification_v5_candidate_features', - **candidate_features(self._rectification_v5_request(body)), - } - - def _compute_rectification_v5_score(self, body): - from scripts.rectification.api_service import score_candidates - request = self._rectification_v5_request(body) - return { - 'success': True, - 'endpoint': 'rectification_v5_score', - **_attach_vedastro_minute_sensitive_to_score(score_candidates(request), request), - } - - def _compute_rectification_v5_diagnostics(self, body): - from scripts.rectification.api_service import diagnostics - request = self._rectification_v5_request(body) - return { - 'success': True, - 'endpoint': 'rectification_v5_diagnostics', - **_attach_vedastro_minute_sensitive_to_score(diagnostics(request), request), - } - - def _compute_rectification_v5_vedastro_validate(self, body): - if not isinstance(body, dict): - raise BadRequest('request body must be an object') - candidate_times = body.get('candidate_times') - if ( - not isinstance(candidate_times, list) - or len(candidate_times) != 2 - or any(not isinstance(value, str) or not re.fullmatch(r'(?:[01]\d|2[0-3]):[0-5]\d', value) for value in candidate_times) - or candidate_times[0] == candidate_times[1] - ): - raise BadRequest('candidate_times must contain exactly two distinct HH:MM values: primary then runner-up') - - request_body = dict(body) - request_body.pop('candidate_times', None) - request = self._rectification_v5_request(request_body) - from scripts.active_rectification_event_engine import _candidate_datetimes - allowed_candidate_times = {value.strftime('%H:%M'): value for value in _candidate_datetimes(request)} - if any(value not in allowed_candidate_times for value in candidate_times): - raise BadRequest('candidate_times must fall within the V5 candidate range') - - # issue #130: a VedAstro failure for this evidence and pair is kept for a day, - # and the whole check stays inside the frontend's wait. - from scripts.rectification.vedastro_validate_cache import ValidateBudget, remember_if_service_failure, remembered_failure, validation_key - remembered_key = validation_key(request_body, candidate_times) - remembered = remembered_failure(remembered_key) - if remembered is not None: - return remembered - selected_events, eligible_event_count, unsupported_events = _select_vedastro_rectification_events( - request['events'] - ) - adapter = _load_local_module('vedastro_service_adapter') - budget = ValidateBudget(getattr(adapter, '_timeout_seconds', None)) - minute_cache = {} - range_scan_cache = {} - minute_reports = [] - minute_raw_reports = [] - candidate_validations = [] - raw_reports = [] - - for role, candidate_time in zip(('primary', 'runner_up'), candidate_times): - birth_day = allowed_candidate_times[candidate_time] - hour, minute = candidate_time.split(':', 1) - candidate_case = { - 'year': birth_day.year, - 'month': birth_day.month, - 'day': birth_day.day, - 'hour': int(hour), - 'minute': int(minute), - 'second': 0, - 'lat': request['lat'], - 'lon': request['lon'], - 'tz': request['tz'], - } - if candidate_time not in minute_cache: - minute_cache[candidate_time] = budget.call( - _safe_vedastro_adapter_call, - adapter.run_rectification_minute_snapshot_for_case, - candidate_case, - case_id=f'rectification_v5_{role}_{candidate_time.replace(":", "")}', - ) - minute_report = minute_cache[candidate_time] - minute_raw_reports.append(minute_report) - raw_reports.append(minute_report) - minute_reports.append(_safe_vedastro_minute_snapshot_summary(candidate_time, minute_report)) - - event_scans = [] - for event, adapter_domain, mapping_mode, start_date, end_date in selected_events: - cache_key = (candidate_time, adapter_domain, start_date, end_date) - if cache_key not in range_scan_cache: - range_scan_cache[cache_key] = budget.call( - _safe_vedastro_adapter_call, - adapter.run_range_scan_for_case, - candidate_case, - adapter_domain, - start_date, - end_date, - case_id=f'rectification_v5_{role}_{candidate_time.replace(":", "")}', - ) - report = range_scan_cache[cache_key] - raw_reports.append(report) - event_scans.append(_safe_vedastro_range_scan_summary( - event, - adapter_domain, - mapping_mode, - start_date, - end_date, - report, - )) - candidate_validations.append({ - 'role': role, - 'candidate_time': candidate_time, - 'metric': _vedastro_candidate_metric(event_scans), - 'events': event_scans, - }) - - minute_comparison = _compare_vedastro_minute_snapshots(minute_reports) - minute_snapshots_verified = bool( - minute_comparison['comparison_ready'] - and all( - _vedastro_minute_snapshot_is_complete(report, summary) - for report, summary in zip(minute_raw_reports, minute_reports) - ) - ) - scans_succeeded = bool(selected_events) and all( - item['metric']['successful_event_count'] == item['metric']['requested_event_count'] - for item in candidate_validations - ) - search_events_primary_supports_local_winner = bool( - scans_succeeded - and _vedastro_metric_key(candidate_validations[0]['metric']) - > _vedastro_metric_key(candidate_validations[1]['metric']) - ) - - blockers = [] - failure_kinds = {report.get('_failure_kind') for report in raw_reports} - if 'timeout' in failure_kinds or any(report.get('status') == 'timeout' for report in raw_reports): - blockers.append('vedastro_timeout') - if 'exception' in failure_kinds: - blockers.append('vedastro_exception') - if not minute_snapshots_verified or not scans_succeeded: - blockers.append('vedastro_official_response_missing') - if minute_snapshots_verified and not minute_comparison['discriminated']: - blockers.append('vedastro_minute_sensitive_layers_not_discriminated') - if not selected_events: - blockers.append('vedastro_supported_events_missing') - blockers = list(dict.fromkeys(blockers)) - passed = not blockers - - result = { - 'success': True, - 'endpoint': 'rectification_v5_vedastro_validate', - 'status': 'pass' if passed else 'fail', - 'passed': passed, - 'can_confirm_exact_minute': False, - 'candidate_times': { - 'primary': candidate_times[0], - 'runner_up': candidate_times[1], - }, - 'blockers': blockers, - 'minute_sensitive_validation': { - 'status': 'pass' if minute_snapshots_verified and minute_comparison['discriminated'] else 'fail', - 'candidates': minute_reports, - **minute_comparison, - }, - 'event_validation': { - 'status': 'pass' if scans_succeeded else 'fail', - 'eligible_event_count': eligible_event_count, - 'supported_event_count': len(selected_events), - 'selection_policy': ( - 'one_strongest_event_per_native_adapter_domain; ' - 'direct_mapping_before_proxy; higher_precision_before_lower_precision; newest_on_equal_precision' - ), - 'unsupported_events': unsupported_events, - 'search_events_primary_supports_local_winner': search_events_primary_supports_local_winner, - 'candidates': candidate_validations, - }, - } - remember_if_service_failure(remembered_key, result) - return result - def _compute_rectification_v5_range_reading(self, body): - from scripts.rectification.api_service import range_reading + from scripts.birth_window_range_reading import range_reading if not isinstance(body, dict): raise BadRequest('request body must be an object') try: @@ -8653,25 +8255,6 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): **payload, } - def _compute_rectification_v5_block_scan(self, body): - from scripts.rectification.api_service import block_scan - return { - 'success': True, - 'endpoint': 'rectification_v5_block_scan', - **block_scan(self._rectification_v5_request(body)), - } - - def _compute_active_rectification_events_v4(self, body): - """Compatibility projection; validation and calculations are owned by V5 services.""" - from scripts.rectification.api_service import score_candidates - return { - 'success': True, - 'endpoint': 'active_rectification_events_v4', - **score_candidates(self._rectification_v5_request(body)), - } - - - def _compute_case_validation(self, body): planets, _, _ = self._normalized_planets_from_body(body) current_md = body.get('current_md', body.get('dasha_lord', '')) @@ -9435,14 +9018,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): '/api/active_rectification_questions': self._compute_active_rectification_questions, '/api/active_rectification_score': self._compute_active_rectification_score, '/api/active_rectification_events': self._compute_active_rectification_events, - '/api/active_rectification_events_v4': self._compute_active_rectification_events_v4, - '/api/rectification/v5/candidate-features': self._compute_rectification_v5_candidate_features, - '/api/rectification/v5/score': self._compute_rectification_v5_score, - '/api/rectification/v5/diagnostics': self._compute_rectification_v5_diagnostics, - '/api/rectification/v5/vedastro-validate': self._compute_rectification_v5_vedastro_validate, '/api/rectification/v5/range_reading': self._compute_rectification_v5_range_reading, - '/api/rectification/v5/block_scan': self._compute_rectification_v5_block_scan, - '/api/rectification/v5/versions': self._compute_rectification_v5_versions, '/api/relationship': self._compute_relationship, '/api/remedies': self._compute_remedies, '/api/sade_sati': self._compute_sade_sati, @@ -9568,14 +9144,7 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): '/api/prashna': 'Compute Prashna chart and answer evidence', '/api/rectification_gate': 'Evaluate birth-time precision gate', '/api/active_rectification_events': 'Score dated life events against actual birth-time candidates', - '/api/active_rectification_events_v4': 'Score immutable dated event ranges for asynchronous V4 rectification', - '/api/rectification/v5/candidate-features': 'Scan immutable candidate static features once per calculation specification', - '/api/rectification/v5/score': 'Build the V5 event-by-candidate contribution matrix and score candidate ranges', - '/api/rectification/v5/diagnostics': 'Run V5 stability diagnostics over the server-owned contribution matrix', - '/api/rectification/v5/vedastro-validate': 'Validate one V5 primary/runner-up pair with safe official VedAstro summaries', '/api/rectification/v5/range_reading': 'Compare stable versus minute-sensitive themes across a trusted unresolved window', - '/api/rectification/v5/block_scan': 'Score a 24-hour unknown-time case in declared period blocks', - '/api/rectification/v5/versions': 'Return live V5 algorithm and decision-policy identity without scoring', '/api/relationship': 'Compute relationship and spouse-status evidence', '/api/remedies': 'Generate low-risk remedies from doshas/strength/dasha', '/api/sade_sati': 'Compute Sade Sati status and phase', @@ -9638,27 +9207,6 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): '/api/pancha_mahapurusha': {'planets': SAMPLE_PLANETS, 'sun_degree': SAMPLE_PLANETS['Sun']['lon']}, '/api/prashna': {'planets': SAMPLE_PLANETS, 'question': 'general'}, '/api/rectification_gate': {**base, 'declared_accuracy': 'minute', 'time_source': 'family_clear'}, - '/api/rectification/v5/candidate-features': { - 'birth_date': '1997-08-08', 'start_time': '05:00', 'end_time': '05:03', - 'lat': 36.419, 'lon': 114.213, 'tz': 8, - 'events': [{'id': '00000000-0000-4000-8000-000000000001', 'domain': 'education', 'event_kind': 'education_milestone', 'date_start': '2016-09-01', 'date_end': '2016-09-30', 'precision': 'month', 'summary': '大学入学'}], - }, - '/api/rectification/v5/score': { - 'birth_date': '1997-08-08', 'start_time': '05:00', 'end_time': '05:03', - 'lat': 36.419, 'lon': 114.213, 'tz': 8, - 'events': [{'id': '00000000-0000-4000-8000-000000000001', 'domain': 'education', 'event_kind': 'education_milestone', 'date_start': '2016-09-01', 'date_end': '2016-09-30', 'precision': 'month', 'summary': '大学入学'}], - }, - '/api/rectification/v5/diagnostics': { - 'birth_date': '1997-08-08', 'start_time': '05:00', 'end_time': '05:03', - 'lat': 36.419, 'lon': 114.213, 'tz': 8, - 'events': [{'id': '00000000-0000-4000-8000-000000000001', 'domain': 'education', 'event_kind': 'education_milestone', 'date_start': '2016-09-01', 'date_end': '2016-09-30', 'precision': 'month', 'summary': '大学入学'}], - }, - '/api/rectification/v5/vedastro-validate': { - 'birth_date': '1997-08-08', 'start_time': '05:00', 'end_time': '05:03', - 'lat': 36.419, 'lon': 114.213, 'tz': 8, - 'candidate_times': ['05:01', '05:02'], - 'events': [{'id': '00000000-0000-4000-8000-000000000001', 'domain': 'education', 'event_kind': 'education_milestone', 'date_start': '2016-09-01', 'date_end': '2016-09-30', 'precision': 'month', 'summary': '大学入学'}], - }, '/api/rectification/v5/range_reading': { 'birth_date': '1997-08-08', 'lat': 36.419, 'lon': 114.213, 'tz': 8, @@ -9666,12 +9214,6 @@ class JyotishComputeService(VedastroEvidenceMixin, SynastryMixin): 'representative_time': '05:01', 'candidate_range': {'start_time': '05:00', 'end_time': '05:26', 'representative_time': '05:01'}, }, - '/api/rectification/v5/block_scan': { - 'birth_date': '1997-08-08', 'start_time': '00:00', 'end_time': '23:59', - 'lat': 36.419, 'lon': 114.213, 'tz': 8, 'minute_step': 10, - 'events': [{'id': '00000000-0000-4000-8000-000000000001', 'domain': 'education', 'event_kind': 'education_milestone', 'date_start': '2016-09-01', 'date_end': '2016-09-30', 'precision': 'month', 'summary': '大学入学'}], - }, - '/api/rectification/v5/versions': {}, '/api/relationship': {'planets': SAMPLE_PLANETS, 'asc_sign': 'Aries', 'dasha_info': {'maha_dasha': 'Venus', 'antar_dasha': 'Jupiter'}}, '/api/remedies': {'shadbala': {'Sun': {'rupas': 4.1}, 'Moon': {'rupas': 3.8}}, 'doshas': ['manglik'], 'dasha_lord': 'Venus'}, '/api/sade_sati': {'moon_degree': SAMPLE_PLANETS['Moon']['lon'], 'asc_degree': SAMPLE_ASCENDANT['lon'], 'saturn_degree': SAMPLE_PLANETS['Saturn']['lon']}, @@ -10369,19 +9911,6 @@ class JyotishAPIHandler(BaseHTTPRequestHandler, JyotishComputeService): scheme, _, token = authorization.partition(' ') return token.strip() if scheme.lower() == 'bearer' else '' - def _require_dynamic_rectification_token(self): - configured = os.environ.get('JYOTISH_DYNAMIC_RECTIFICATION_TOKEN', '').strip() - if not configured: - service_role = os.environ.get('SUPABASE_SERVICE_ROLE_KEY', '').strip() - if service_role: - configured = hashlib.sha256( - f'jyotisha-dynamic-rectification-v1:{service_role}'.encode('utf-8') - ).hexdigest() - supplied = self._job_access_token() - matches = secrets.compare_digest(supplied, configured) - if not configured or not matches: - raise Forbidden('Dynamic rectification server token is missing or invalid') - def do_OPTIONS(self): try: self._enforce_request_security() @@ -10434,8 +9963,6 @@ class JyotishAPIHandler(BaseHTTPRequestHandler, JyotishComputeService): 'async_job_runtime': async_job_runtime_status(), 'vedastro': self._vedastro_status(), }) - elif path == '/api/rectification/v5/versions': - self._json(self._compute_rectification_v5_versions()) elif path == '/api/cities': self._json(list(CITY_DB.keys())) elif path == '/api/capability_audit': @@ -10719,9 +10246,6 @@ class JyotishAPIHandler(BaseHTTPRequestHandler, JyotishComputeService): elif path == '/api/active_rectification_events': result = self._compute_active_rectification_events(body) self._json(result) - elif path == '/api/active_rectification_events_v4': - result = self._compute_active_rectification_events_v4(body) - self._json(result) elif path in ('/api/chart_choice/packet', '/api/chart_choice/decide'): from scripts.chart_choice.boundaries import ChartChoiceInputError from scripts.chart_choice.service import build_packet, decide_packet @@ -10732,26 +10256,8 @@ class JyotishAPIHandler(BaseHTTPRequestHandler, JyotishComputeService): raise BadRequest(str(exc)) from exc elif path == '/api/rectification/v5/varga-segments': _load_local_module('rectification_varga_segments_api').handle_varga_segments(self, body) - elif path == '/api/rectification/v5/candidate-features': - self._json(self._compute_rectification_v5_candidate_features(body)) - elif path == '/api/rectification/v5/score': - self._json(_pooled(self, '_compute_rectification_v5_score', body)) - elif path == '/api/rectification/v5/diagnostics': - self._json(self._compute_rectification_v5_diagnostics(body)) - elif path == '/api/rectification/v5/vedastro-validate': - self._json(self._compute_rectification_v5_vedastro_validate(body)) elif path == '/api/rectification/v5/range_reading': self._json(self._compute_rectification_v5_range_reading(body)) - elif path == '/api/rectification/v5/block_scan': - self._json(_pooled(self, '_compute_rectification_v5_block_scan', body)) - elif path == '/api/rectification/v5/versions': - self._json(self._compute_rectification_v5_versions()) - elif path == '/api/dynamic_rectification_opportunities': - result = self._compute_dynamic_rectification_opportunities(body) - self._json(result) - elif path == '/api/dynamic_rectification_score': - result = self._compute_dynamic_rectification_score(body) - self._json(result) elif path == '/api/case_validation': result = self._compute_case_validation(body) self._json(result) @@ -10838,106 +10344,6 @@ class JyotishAPIHandler(BaseHTTPRequestHandler, JyotishComputeService): access_token=self._job_access_token(), ) - def _compute_dynamic_rectification_opportunities(self, body): - self._require_dynamic_rectification_token() - allowed_fields = { - 'case_id', 'birth_date', 'as_of_date', 'start_time', 'end_time', - 'lat', 'lon', 'tz', 'candidate_model', 'evidence', - 'events', - 'dismissed_opportunity_ids', 'question_fingerprints', - 'partition_fingerprints', 'recent_ranges', - } - normalized = self._dynamic_rectification_base(body, allowed_fields, 'opportunity') - case_id = normalized.get('case_id') - as_of_date = normalized.get('as_of_date') - if not isinstance(case_id, str) or not case_id.strip(): - raise BadRequest('case_id must be a non-empty string') - if not isinstance(as_of_date, str): - raise BadRequest('as_of_date must be YYYY-MM-DD') - try: - datetime.strptime(as_of_date, '%Y-%m-%d') - except ValueError as exc: - raise BadRequest('as_of_date must be YYYY-MM-DD') from exc - for key in ('evidence', 'dismissed_opportunity_ids', 'question_fingerprints', 'partition_fingerprints', 'recent_ranges'): - if not isinstance(normalized.get(key), list): - raise BadRequest(f'{key} must be an array') - if any(not isinstance(item, str) or not item for key in ('dismissed_opportunity_ids', 'question_fingerprints', 'partition_fingerprints') for item in normalized[key]): - raise BadRequest('dynamic rectification fingerprints and IDs must be non-empty strings') - for item in normalized['recent_ranges']: - if not isinstance(item, dict) or set(item) != {'start_time', 'end_time'}: - raise BadRequest('recent_ranges must contain only start_time and end_time') - try: - datetime.strptime(item['start_time'], '%H:%M') - datetime.strptime(item['end_time'], '%H:%M') - except (KeyError, TypeError, ValueError) as exc: - raise BadRequest('recent_ranges must contain valid HH:MM times') from exc - if normalized.get('candidate_model') is not None and not isinstance(normalized['candidate_model'], dict): - raise BadRequest('candidate_model must be an object') - # Older stored clients did not send historical events. Treat omission as - # an empty evidence set so resuming an unfinished case never fails just - # because its cached request predates event-aware question selection. - events = normalized.get('events', []) - if not isinstance(events, list) or len(events) > 6: - raise BadRequest('events must be an array with at most 6 items') - parsed_birth_date = datetime.strptime(normalized['birth_date'], '%Y-%m-%d') - allowed_domains = {'education', 'relocation', 'relationship', 'career', 'finance', 'health_pressure'} - formats = {'year': '%Y', 'month': '%Y-%m', 'day': '%Y-%m-%d'} - normalized_events = [] - for raw_event in events: - if not isinstance(raw_event, dict) or set(raw_event) != {'id', 'domain', 'date', 'precision'}: - raise BadRequest('each event must contain only id, domain, date, and precision') - try: - event_id = str(uuid.UUID(str(raw_event['id']))) - except (ValueError, TypeError, AttributeError) as exc: - raise BadRequest('event id must be a UUID') from exc - domain = raw_event['domain'] - precision = raw_event['precision'] - event_date = raw_event['date'] - if domain not in allowed_domains: - raise BadRequest('event domain is unsupported') - if precision not in formats or not isinstance(event_date, str): - raise BadRequest('event precision is unsupported') - try: - parsed_event_date = datetime.strptime(event_date, formats[precision]) - except ValueError as exc: - raise BadRequest('event date does not match its precision') from exc - if parsed_event_date.year < parsed_birth_date.year or parsed_event_date > datetime.now(): - raise BadRequest('event date must be between birth and today') - normalized_events.append({ - 'id': event_id, - 'domain': domain, - 'date': event_date, - 'precision': precision, - }) - normalized['events'] = normalized_events - module = _load_local_module('dynamic_rectification') - try: - result = module.build_difference_packet(normalized) - except (KeyError, TypeError, ValueError) as exc: - raise BadRequest(str(exc)) from exc - return {'success': True, 'endpoint': 'dynamic_rectification_opportunities', **result} - - def _compute_dynamic_rectification_score(self, body): - self._require_dynamic_rectification_token() - allowed_fields = { - 'birth_date', 'start_time', 'end_time', 'lat', 'lon', 'tz', 'choice_evidence', - } - normalized = self._dynamic_rectification_base(body, allowed_fields, 'score') - evidence = normalized.get('choice_evidence') - if not isinstance(evidence, list): - raise BadRequest('choice_evidence must be an array') - if any(isinstance(item, dict) and 'option_id' in item for item in evidence): - raise BadRequest('option_id is client-owned and cannot be scored') - module = _load_local_module('dynamic_rectification') - try: - result = module.score_choice_evidence(normalized) - except (KeyError, TypeError, ValueError) as exc: - raise BadRequest(str(exc)) from exc - result['can_apply'] = False - result.setdefault('reasons', []).append('vedastro_validation_required') - return {'success': True, 'endpoint': 'dynamic_rectification_score', **result} - - def _parse_allowed_origins(value): if not value: return DEFAULT_ALLOWED_ORIGINS diff --git a/scripts/minute_candidate_discriminability.py b/scripts/minute_candidate_discriminability.py deleted file mode 100644 index 9cb459117..000000000 --- a/scripts/minute_candidate_discriminability.py +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env python3 -"""Audit whether event evidence actually distinguishes adjacent birth minutes.""" -from __future__ import annotations - -import hashlib -import json -from collections import defaultdict -from collections.abc import Sequence -from typing import Any - -from scripts.active_rectification_events import CandidateScoreRow - - -def _evidence_features(item: dict[str, Any]) -> dict[str, Any]: - return { - "event_id": item["event_id"], - "domain": item["domain"], - "points": float(item["points"]), - "rule_ids": sorted(item["rule_ids"]), - } - - -def feature_fingerprint(row: CandidateScoreRow) -> str: - """Hash only computed evidence features, never the candidate time or truth label.""" - payload = { - "evidence": sorted( - ( - _evidence_features(item) - for item in row["evidence"] - ), - key=lambda item: (item["event_id"], item["domain"]), - ), - "missing_layers": sorted(row["missing_layers"]), - } - canonical = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")) - return hashlib.sha256(canonical.encode("utf-8")).hexdigest() - - -def analyze_candidate_rows( - rows: Sequence[CandidateScoreRow], - *, - ranking_rows: Sequence[CandidateScoreRow] | None = None, -) -> dict[str, Any]: - """Return feature-equivalence classes and real adjacent-minute transitions.""" - candidates = list(rows) - if not candidates: - return { - "scope": "minute_candidate_discriminability", - "candidate_count": 0, - "unique_feature_fingerprint_count": 0, - "distinguishable_candidate_ratio": 0.0, - "equivalence_classes": [], - "adjacent_transitions": [], - "indistinguishable_adjacent_pair_count": 0, - "top_candidate_feature_unique": False, - "status": "blocked_no_candidates", - } - - fingerprints = {row["time"]: feature_fingerprint(row) for row in candidates} - classes: dict[str, list[str]] = defaultdict(list) - for row in candidates: - classes[fingerprints[row["time"]]].append(row["time"]) - equivalence_classes = [ - {"feature_fingerprint": fingerprint, "candidate_times": times, "size": len(times)} - for fingerprint, times in sorted(classes.items(), key=lambda item: item[1][0]) - ] - - adjacent_transitions = [] - indistinguishable = 0 - for previous, current in zip(candidates, candidates[1:]): - previous_by_event = { - item["event_id"]: _evidence_features(item) for item in previous["evidence"] - } - current_by_event = { - item["event_id"]: _evidence_features(item) for item in current["evidence"] - } - changed_event_ids = sorted( - event_id - for event_id in set(previous_by_event) | set(current_by_event) - if previous_by_event.get(event_id) != current_by_event.get(event_id) - ) - feature_changed = fingerprints[previous["time"]] != fingerprints[current["time"]] - indistinguishable += int(not feature_changed) - adjacent_transitions.append({ - "between": [previous["time"], current["time"]], - "feature_changed": feature_changed, - "changed_event_ids": changed_event_ids, - "score_delta": round(float(current["score"]) - float(previous["score"]), 4), - }) - - ranked = list(ranking_rows) if ranking_rows is not None else candidates - top_score = max(float(row["score"]) for row in ranked) - top_times = [row["time"] for row in ranked if float(row["score"]) == top_score] - top_unique = len(top_times) == 1 and len(classes[fingerprints[top_times[0]]]) == 1 - unique_count = len(classes) - status = ( - "minute_feature_unique" - if top_unique - else "range_has_differences_but_top_not_unique" - if unique_count > 1 - else "blocked_feature_equivalent_range" - ) - return { - "scope": "minute_candidate_discriminability", - "candidate_count": len(candidates), - "unique_feature_fingerprint_count": unique_count, - "distinguishable_candidate_ratio": round(unique_count / len(candidates), 4), - "equivalence_classes": equivalence_classes, - "adjacent_transitions": adjacent_transitions, - "indistinguishable_adjacent_pair_count": indistinguishable, - "top_candidate_times": top_times, - "top_candidate_feature_unique": top_unique, - "status": status, - "boundary": "Feature uniqueness describes this scorer's computed evidence only; it is not proof that a birth minute is true.", - } diff --git a/scripts/minute_rectification_blind_eval.py b/scripts/minute_rectification_blind_eval.py deleted file mode 100644 index b96c01ae2..000000000 --- a/scripts/minute_rectification_blind_eval.py +++ /dev/null @@ -1,202 +0,0 @@ -#!/usr/bin/env python3 -"""Replay the sealed AA birth-minute holdout without exposing truth to ranking.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import sys -from datetime import datetime, timedelta -from pathlib import Path -from typing import Any - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -if str(PROJECT_ROOT) not in sys.path: - sys.path.insert(0, str(PROJECT_ROOT)) - -from scripts.active_rectification_event_engine import ( - adjudicate_event_candidate_rows, - compute_event_candidate_rows, -) -from scripts.active_rectification_events import ALGORITHM_VERSION, CandidateResult, CandidateScoreRow -from scripts.minute_rectification_holdout_validator import DEFAULT_MANIFEST, ROOT, validate - - -def implementation_sha256(files: list[str]) -> str: - """Hash the ordered path/content pairs that define the frozen ranker.""" - digest = hashlib.sha256() - for relative in sorted(files): - path = ROOT / relative - digest.update(relative.encode("utf-8")) - digest.update(b"\0") - digest.update(path.read_bytes()) - digest.update(b"\0") - return digest.hexdigest() - - -def _minute_at_offset(value: str, offset: int) -> str: - moment = datetime.strptime(value, "%H:%M") + timedelta(minutes=offset) - return moment.strftime("%H:%M") - - -def _clock_distance(left: str, right: str) -> int: - left_value = int(left[:2]) * 60 + int(left[3:]) - right_value = int(right[:2]) * 60 + int(right[3:]) - distance = abs(left_value - right_value) - return min(distance, 1440 - distance) - - -def _request(case: dict[str, Any], events: list[dict[str, Any]]) -> dict[str, Any]: - birth = case["birth"] - radius = int(case["candidate_radius_minutes"]) - return { - "birth_date": birth["date"], - "start_time": _minute_at_offset(birth["time"], -radius), - "end_time": _minute_at_offset(birth["time"], radius), - "lat": float(birth["latitude"]), - "lon": float(birth["longitude"]), - "tz": float(birth["timezone_offset"]), - "events": [ - {"id": event["id"], "domain": event["domain"], "date": event["date"], "precision": event["precision"]} - for event in events - ], - } - - -def _candidate_moments(case: dict[str, Any]) -> list[datetime]: - birth = case["birth"] - center = datetime.fromisoformat(f"{birth['date']}T{birth['time']}:00") - radius = int(case["candidate_radius_minutes"]) - return [center + timedelta(minutes=offset) for offset in range(-radius, radius + 1)] - - -def _opaque_winner(benchmark_id: str, case_id: str, rows: list[CandidateScoreRow]) -> str: - top_score = max(row["score"] for row in rows) - leaders = [row["time"] for row in rows if row["score"] == top_score] - return min( - leaders, - key=lambda value: hashlib.sha256(f"{benchmark_id}:{case_id}:{value}".encode()).hexdigest(), - ) - - -def _would_confirm(result: CandidateResult) -> bool: - release_independent_reasons = [ - reason for reason in result["reasons"] if reason != "minute_holdout_not_ready" - ] - segment = result["winning_segment"] - return ( - result["confidence"] == "high" - and segment is not None - and segment["width_minutes"] == 1 - and not release_independent_reasons - and not result["missing_layers"] - ) - - -def summarize_trials(trials: list[dict[str, Any]], release_metrics: dict[str, Any]) -> dict[str, Any]: - """Compute frozen aggregate metrics from truth-revealed trial outputs.""" - count = len(trials) - if not count: - metrics = { - "top_1_rate": None, - "top_3_rate": None, - "mean_absolute_minute_error": None, - "false_confirmation_rate": None, - "correct_insufficient_evidence_rejection_rate": None, - "confirmation_coverage_rate": None, - } - return {"metrics": metrics, "metric_gates_passed": False} - metrics = { - "top_1_rate": round(sum(item["true_rank"] <= 1 for item in trials) / count, 4), - "top_3_rate": round(sum(item["true_rank"] <= 3 for item in trials) / count, 4), - "mean_absolute_minute_error": round(sum(item["minute_error"] for item in trials) / count, 4), - "false_confirmation_rate": round(sum(item["false_confirmation"] for item in trials) / count, 4), - "correct_insufficient_evidence_rejection_rate": round( - sum(item["insufficient_evidence_rejected"] for item in trials) / count, 4, - ), - "confirmation_coverage_rate": round(sum(item["would_confirm"] for item in trials) / count, 4), - } - passed = ( - metrics["top_1_rate"] >= float(release_metrics["top_1_rate_minimum"]) - and metrics["top_3_rate"] >= float(release_metrics["top_3_rate_minimum"]) - and metrics["mean_absolute_minute_error"] <= float(release_metrics["mean_absolute_minute_error_maximum"]) - and metrics["false_confirmation_rate"] <= float(release_metrics["false_confirmation_rate_maximum"]) - and metrics["correct_insufficient_evidence_rejection_rate"] - >= float(release_metrics["correct_insufficient_evidence_rejection_rate_minimum"]) - ) - return {"metrics": metrics, "metric_gates_passed": passed} - - -def run(manifest_path: Path = DEFAULT_MANIFEST) -> dict[str, Any]: - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - validation = validate(manifest_path) - frozen = manifest.get("frozen_scoring") or {} - files = frozen.get("files") if isinstance(frozen.get("files"), list) else [] - actual_hash = implementation_sha256(files) if files else None - hash_matches = actual_hash == frozen.get("implementation_sha256") - algorithm_matches = frozen.get("algorithm_version") == ALGORITHM_VERSION - invalid_ids = set(validation["invalid_cases"]) - trials: list[dict[str, Any]] = [] - if hash_matches and algorithm_matches: - for case in manifest.get("cases", []): - if case.get("case_id") in invalid_ids: - continue - request = _request(case, case["events"]) - rows = compute_event_candidate_rows(request, candidates=_candidate_moments(case)) - result = adjudicate_event_candidate_rows(request, rows) - true_time = case["birth"]["time"] - true_row = next(row for row in rows if row["time"] == true_time) - true_rank = 1 + sum(row["score"] > true_row["score"] for row in rows) - predicted = _opaque_winner(manifest["benchmark_id"], case["case_id"], rows) - would_confirm = _would_confirm(result) - - sparse_request = _request(case, case["events"][:1]) - sparse_rows = compute_event_candidate_rows(sparse_request, candidates=_candidate_moments(case)) - sparse_result = adjudicate_event_candidate_rows(sparse_request, sparse_rows) - trials.append({ - "case_id": case["case_id"], - "candidate_count": len(rows), - "published_truth_revealed_after_ranking": true_time, - "predicted_time": predicted, - "true_rank": true_rank, - "minute_error": _clock_distance(predicted, true_time), - "would_confirm": would_confirm, - "false_confirmation": would_confirm and predicted != true_time, - "insufficient_evidence_rejected": not _would_confirm(sparse_result), - "full_trial_reasons": result["reasons"], - "sparse_trial_reasons": sparse_result["reasons"], - }) - - aggregate = summarize_trials(trials, manifest.get("release_metrics") or {}) - minimum_cases_met = validation["valid_public_aa_cases"] >= validation["minimum_public_aa_cases"] - release_ready = ( - validation["status"] == "ready_for_blind_replay" - and hash_matches - and algorithm_matches - and minimum_cases_met - and aggregate["metric_gates_passed"] - ) - return { - "scope": "minute_rectification_blind_holdout", - "benchmark_id": manifest.get("benchmark_id"), - "status": "release_gate_passed" if release_ready else "blocked", - "validation": validation, - "frozen_scoring": { - "algorithm_matches": algorithm_matches, - "implementation_hash_matches": hash_matches, - "expected_sha256": frozen.get("implementation_sha256"), - "actual_sha256": actual_hash, - }, - "trial_count": len(trials), - "trials": trials, - **aggregate, - "verified_minute_claim_allowed": release_ready, - "boundary": "Holdout outcomes must never be used to tune scoring. Any scoring change requires a new benchmark version and a newly sealed evaluation set.", - } - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) - args = parser.parse_args() - print(json.dumps(run(args.manifest), ensure_ascii=False, indent=2, sort_keys=True)) diff --git a/scripts/minute_rectification_development_eval.py b/scripts/minute_rectification_development_eval.py deleted file mode 100644 index 2fc0f57af..000000000 --- a/scripts/minute_rectification_development_eval.py +++ /dev/null @@ -1,178 +0,0 @@ -#!/usr/bin/env python3 -"""Run non-holdout development cases and expose minute discriminability failures.""" -from __future__ import annotations - -import argparse -import json -import sys -from pathlib import Path -from typing import Any - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -if str(PROJECT_ROOT) not in sys.path: - sys.path.insert(0, str(PROJECT_ROOT)) - -from scripts.active_rectification_event_engine import ( - adjudicate_event_candidate_rows, - compute_event_candidate_rows, -) -from scripts.minute_candidate_discriminability import analyze_candidate_rows -from scripts.minute_rectification_blind_eval import ( - _candidate_moments, - _clock_distance, - _opaque_winner, - _request, -) -from scripts.minute_rectification_development_validator import DEFAULT_MANIFEST, validate -from scripts.minute_rectification_feature_facts_v4 import ( - analyze_feature_fact_rows, - build_fact_difference_opportunities, - build_feature_fact_rows, -) -from scripts.minute_rectification_fact_ranker_v4 import ( - rank_fact_rows, - score_fact_ranker_v4, -) -from scripts.minute_rectification_pairwise_v3 import rank_candidate_rows, score_pairwise_v3 - - -def run(manifest_path: Path = DEFAULT_MANIFEST) -> dict[str, Any]: - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - validation = validate(manifest_path) - invalid = {item["case_id"] for item in validation["invalid_cases"]} - cases = [] - for case in manifest.get("cases", []): - if case.get("case_id") in invalid: - continue - request = _request(case, case["events"]) - candidate_moments = _candidate_moments(case) - rows = compute_event_candidate_rows(request, candidates=candidate_moments) - fact_rows = build_feature_fact_rows(request, candidates=candidate_moments) - fact_diagnostics = analyze_feature_fact_rows(fact_rows) - fact_opportunities = build_fact_difference_opportunities(fact_rows) - v2_result = adjudicate_event_candidate_rows(request, rows) - v2_diagnostics = analyze_candidate_rows(rows) - v3_rows, _ = rank_candidate_rows(rows, request["events"]) - v3_result = score_pairwise_v3(rows, request["events"]) - v3_diagnostics = analyze_candidate_rows(rows, ranking_rows=v3_rows) - v4_rows, _ = rank_fact_rows(fact_rows, request["events"]) - v4_result = score_fact_ranker_v4(fact_rows, request["events"]) - v4_diagnostics = analyze_candidate_rows(v4_rows, ranking_rows=v4_rows) - truth = case["birth"]["time"] - truth_row = next(row for row in rows if row["time"] == truth) - v3_truth_row = next(row for row in v3_rows if row["time"] == truth) - v4_truth_row = next(row for row in v4_rows if row["time"] == truth) - v2_predicted = _opaque_winner(manifest["benchmark_id"], case["case_id"], rows) - v3_predicted = _opaque_winner(f"{manifest['benchmark_id']}:v3", case["case_id"], v3_rows) - v4_predicted = _opaque_winner(f"{manifest['benchmark_id']}:v4", case["case_id"], v4_rows) - cases.append({ - "case_id": case["case_id"], - "published_time": truth, - "production_confirmation_allowed": False, - "p6_feature_facts": fact_diagnostics, - "p6_fact_difference_opportunities": fact_opportunities, - "v2": { - "predicted_time": v2_predicted, - "true_rank": 1 + sum(row["score"] > truth_row["score"] for row in rows), - "minute_error": _clock_distance(v2_predicted, truth), - "result_reasons": v2_result["reasons"], - "discriminability": v2_diagnostics, - }, - "v3": { - "predicted_time": v3_predicted, - "true_rank": 1 + sum(row["score"] > v3_truth_row["score"] for row in v3_rows), - "minute_error": _clock_distance(v3_predicted, truth), - "result_reasons": v3_result["reasons"], - "winning_segment": v3_result["winning_segment"], - "discriminability": v3_diagnostics, - }, - "v4": { - "predicted_time": v4_predicted, - "true_rank": 1 + sum(row["score"] > v4_truth_row["score"] for row in v4_rows), - "minute_error": _clock_distance(v4_predicted, truth), - "result_reasons": v4_result["reasons"], - "winning_segment": v4_result["winning_segment"], - "stability_diagnostics": v4_result["stability_diagnostics"], - "discriminability": v4_diagnostics, - }, - }) - v2_errors = [case["v2"]["minute_error"] for case in cases] - v3_errors = [case["v3"]["minute_error"] for case in cases] - v4_errors = [case["v4"]["minute_error"] for case in cases] - adjacent_pair_count = sum( - max(case["v3"]["discriminability"]["candidate_count"] - 1, 0) - for case in cases - ) - indistinguishable_pair_count = sum( - case["v3"]["discriminability"]["indistinguishable_adjacent_pair_count"] - for case in cases - ) - p6_indistinguishable_pair_count = sum( - case["p6_feature_facts"]["indistinguishable_adjacent_pair_count"] - for case in cases - ) - p6_opportunities = [ - opportunity - for case in cases - for opportunity in case["p6_fact_difference_opportunities"] - ] - summary = { - "v2_mean_minute_error": round(sum(v2_errors) / len(v2_errors), 4) if v2_errors else None, - "v3_mean_minute_error": round(sum(v3_errors) / len(v3_errors), 4) if v3_errors else None, - "v3_improved_case_count": sum(v3 < v2 for v2, v3 in zip(v2_errors, v3_errors)), - "v3_worsened_case_count": sum(v3 > v2 for v2, v3 in zip(v2_errors, v3_errors)), - "v3_unchanged_case_count": sum(v3 == v2 for v2, v3 in zip(v2_errors, v3_errors)), - "v4_mean_minute_error": round(sum(v4_errors) / len(v4_errors), 4) if v4_errors else None, - "v4_improved_vs_v2_case_count": sum(v4 < v2 for v2, v4 in zip(v2_errors, v4_errors)), - "v4_worsened_vs_v2_case_count": sum(v4 > v2 for v2, v4 in zip(v2_errors, v4_errors)), - "v4_unique_minute_count": sum( - (case["v4"]["winning_segment"] or {}).get("width_minutes") == 1 for case in cases - ), - "v4_neighbor_stability_pass_count": sum( - case["v4"]["stability_diagnostics"]["neighbor_stability"]["all_required_passed"] - for case in cases - ), - "v4_leave_one_event_out_pass_count": sum( - case["v4"]["stability_diagnostics"]["leave_one_event_out"]["status"] == "pass" - for case in cases - ), - "indistinguishable_adjacent_pair_count": indistinguishable_pair_count, - "adjacent_pair_count": adjacent_pair_count, - "indistinguishable_adjacent_pair_ratio": round( - indistinguishable_pair_count / adjacent_pair_count, 4 - ) if adjacent_pair_count else None, - "p6_fact_indistinguishable_adjacent_pair_count": p6_indistinguishable_pair_count, - "p6_fact_indistinguishable_adjacent_pair_ratio": round( - p6_indistinguishable_pair_count / adjacent_pair_count, 4 - ) if adjacent_pair_count else None, - "p6_fact_atoms_may_affect_score": False, - "p6_fact_difference_opportunity_count": len(p6_opportunities), - "p6_question_ready_opportunity_count": sum( - opportunity["question_ready"] for opportunity in p6_opportunities - ), - "v3_shadow_only": True, - "v3_may_replace_production": False, - "v4_shadow_only": True, - "v4_may_replace_production": False, - "decision": "reject_v3_production_promotion", - "v4_decision": "requires_independent_frozen_holdout", - } - return { - "scope": "minute_rectification_development_evaluation", - "benchmark_id": manifest.get("benchmark_id"), - "status": "diagnostics_available" if cases else "blocked", - "validation": validation, - "case_count": len(cases), - "cases": cases, - "summary": summary, - "excluded_from_holdout": True, - "may_open_release_gate": False, - "boundary": "Development outcomes may guide a future scorer version but are never added to sealed holdout metrics.", - } - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) - args = parser.parse_args() - print(json.dumps(run(args.manifest), ensure_ascii=False, indent=2, sort_keys=True)) diff --git a/scripts/minute_rectification_development_validator.py b/scripts/minute_rectification_development_validator.py deleted file mode 100644 index 5128ce2fb..000000000 --- a/scripts/minute_rectification_development_validator.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python3 -"""Validate public cases that may be used for development but never for holdout claims.""" -from __future__ import annotations - -import json -import sys -from copy import deepcopy -from pathlib import Path -from typing import Any - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -if str(PROJECT_ROOT) not in sys.path: - sys.path.insert(0, str(PROJECT_ROOT)) - -from scripts.minute_rectification_holdout_validator import ROOT, _case_errors - -DEFAULT_MANIFEST = ROOT / "references" / "real_case_calibration" / "minute_rectification_development_v1.json" - - -def validate(manifest_path: Path = DEFAULT_MANIFEST) -> dict[str, Any]: - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - gate = manifest.get("minimum_case_contract") or {} - invalid: list[dict[str, Any]] = [] - valid = 0 - seen: set[str] = set() - for raw_case in manifest.get("cases", []): - case = deepcopy(raw_case) if isinstance(raw_case, dict) else raw_case - errors: list[str] = [] - if isinstance(case, dict): - if case.get("development_partition") != "tuning_and_diagnostics": - errors.append("case_not_in_development_partition") - if case.get("allowed_for_tuning") is not True: - errors.append("case_not_allowed_for_tuning") - if case.get("excluded_from_holdout") is not True: - errors.append("case_not_excluded_from_holdout") - case["holdout_partition"] = "sealed_evaluation" - case["excluded_from_tuning"] = True - errors.extend(_case_errors(case, gate)) - errors = [ - error for error in errors - if error not in {"case_not_in_sealed_evaluation_partition", "case_not_excluded_from_tuning"} - ] - case_id = raw_case.get("case_id") if isinstance(raw_case, dict) else "non_object_case" - if case_id in seen: - errors.append("duplicate_case_id") - if isinstance(case_id, str): - seen.add(case_id) - if errors: - invalid.append({"case_id": case_id, "errors": sorted(set(errors))}) - else: - valid += 1 - schema_valid = manifest.get("schema_version") == "minute-rectification-development-v1" - return { - "scope": "minute_rectification_development_validation", - "status": "ready_for_development" if schema_valid and not invalid and valid else "blocked", - "valid_development_cases": valid, - "invalid_cases": invalid, - "excluded_from_holdout": True, - "may_open_release_gate": False, - } - - -if __name__ == "__main__": - print(json.dumps(validate(), ensure_ascii=False, indent=2, sort_keys=True)) diff --git a/scripts/minute_rectification_fact_blind_eval_v4.py b/scripts/minute_rectification_fact_blind_eval_v4.py deleted file mode 100644 index c4a91faa1..000000000 --- a/scripts/minute_rectification_fact_blind_eval_v4.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python3 -"""Replay a sealed public-AA holdout with the shadow fact ranker v4.""" -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - -from scripts.minute_rectification_blind_eval import ( - _candidate_moments, - _clock_distance, - _opaque_winner, - _request, - implementation_sha256, - summarize_trials, -) -from scripts.minute_rectification_fact_ranker_v4 import ( - ALGORITHM_VERSION, - rank_fact_rows, - score_fact_ranker_v4, -) -from scripts.minute_rectification_feature_facts_v4 import build_feature_fact_rows -from scripts.minute_rectification_holdout_validator import validate - -DEFAULT_MANIFEST = Path(__file__).resolve().parents[1] / "references" / "real_case_calibration" / "minute_rectification_holdout_v3.json" - - -def _would_confirm(result: dict[str, Any]) -> bool: - independent_reasons = [ - reason for reason in result["reasons"] - if reason != "fact_ranker_v4_holdout_not_ready" - ] - segment = result["winning_segment"] - return ( - result["confidence"] == "high" - and segment is not None - and segment["width_minutes"] == 1 - and not independent_reasons - and not result["missing_layers"] - ) - - -def run(manifest_path: Path = DEFAULT_MANIFEST) -> dict[str, Any]: - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - validation = validate(manifest_path) - frozen = manifest.get("frozen_scoring") or {} - files = frozen.get("files") if isinstance(frozen.get("files"), list) else [] - actual_hash = implementation_sha256(files) if files else None - hash_matches = actual_hash == frozen.get("implementation_sha256") - algorithm_matches = frozen.get("algorithm_version") == ALGORITHM_VERSION - invalid_ids = set(validation["invalid_cases"]) - trials = [] - if hash_matches and algorithm_matches: - for case in manifest.get("cases", []): - if case.get("case_id") in invalid_ids: - continue - request = _request(case, case["events"]) - candidates = _candidate_moments(case) - fact_rows = build_feature_fact_rows(request, candidates=candidates) - ranked_rows, _ = rank_fact_rows(fact_rows, request["events"]) - result = score_fact_ranker_v4(fact_rows, request["events"]) - true_time = case["birth"]["time"] - true_row = next(row for row in ranked_rows if row["time"] == true_time) - true_rank = 1 + sum(row["score"] > true_row["score"] for row in ranked_rows) - predicted = _opaque_winner( - manifest["benchmark_id"], case["case_id"], ranked_rows, - ) - would_confirm = _would_confirm(result) - - sparse_request = _request(case, case["events"][:1]) - sparse_facts = build_feature_fact_rows(sparse_request, candidates=candidates) - sparse_result = score_fact_ranker_v4(sparse_facts, sparse_request["events"]) - trials.append({ - "case_id": case["case_id"], - "candidate_count": len(ranked_rows), - "published_truth_revealed_after_ranking": true_time, - "predicted_time": predicted, - "true_rank": true_rank, - "minute_error": _clock_distance(predicted, true_time), - "would_confirm": would_confirm, - "false_confirmation": would_confirm and predicted != true_time, - "insufficient_evidence_rejected": not _would_confirm(sparse_result), - "full_trial_reasons": result["reasons"], - "sparse_trial_reasons": sparse_result["reasons"], - "neighbor_stability": result["stability_diagnostics"]["neighbor_stability"], - "leave_one_event_out": result["stability_diagnostics"]["leave_one_event_out"], - "ablation": result["stability_diagnostics"]["ablation"], - }) - - aggregate = summarize_trials(trials, manifest.get("release_metrics") or {}) - minimum_cases_met = validation["valid_public_aa_cases"] >= validation["minimum_public_aa_cases"] - release_ready = ( - validation["status"] == "ready_for_blind_replay" - and hash_matches - and algorithm_matches - and minimum_cases_met - and aggregate["metric_gates_passed"] - ) - return { - "scope": "minute_rectification_fact_ranker_v4_blind_holdout", - "benchmark_id": manifest.get("benchmark_id"), - "status": "release_gate_passed" if release_ready else "blocked", - "validation": validation, - "frozen_scoring": { - "algorithm_matches": algorithm_matches, - "implementation_hash_matches": hash_matches, - "expected_sha256": frozen.get("implementation_sha256"), - "actual_sha256": actual_hash, - }, - "trial_count": len(trials), - "trials": trials, - **aggregate, - "verified_minute_claim_allowed": release_ready, - "boundary": "Frozen holdout outcomes may not tune v4. A scoring change requires a new algorithm version and a new sealed evaluation set.", - } - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST) - args = parser.parse_args() - print(json.dumps(run(args.manifest), ensure_ascii=False, indent=2, sort_keys=True)) diff --git a/scripts/minute_rectification_fact_ranker_v4.py b/scripts/minute_rectification_fact_ranker_v4.py deleted file mode 100644 index c9d658b71..000000000 --- a/scripts/minute_rectification_fact_ranker_v4.py +++ /dev/null @@ -1,366 +0,0 @@ -#!/usr/bin/env python3 -"""Event-specific fact ranker for minute rectification development. - -The ranker consumes the lossless v4 fact contract. It is deliberately shadow -only: it can be evaluated and frozen, but it cannot apply a birth minute until -an independent public-AA holdout passes the release gates. -""" -from __future__ import annotations - -import hashlib -import json -from collections import defaultdict -from collections.abc import Iterable, Mapping, Sequence -from typing import Any, Final -from uuid import NAMESPACE_URL, uuid5 - -from scripts.active_rectification_event_engine import DOMAIN_CONFIG -from scripts.active_rectification_events import ( - CandidateScoreRow, - LifeEvent, - build_stability_diagnostics, - precision_weight, -) -from scripts.minute_candidate_discriminability import analyze_candidate_rows - -ALGORITHM_VERSION: Final = "birth-time-event-fact-ranker-v4-shadow" -LAYER_FAMILIES: Final = ( - "vimshottari_d1", - "varga", - "narayana", - "arudha", - "ashtakavarga", - "shadbala", -) -VIM_WEIGHTS: Final = {"md": 2.0, "ad": 1.5, "pd": 0.75} -LAYER_WEIGHTS: Final = { - "vimshottari_d1": 0.20, - "varga": 0.30, - "narayana": 0.25, - "arudha": 0.10, - "ashtakavarga": 0.075, - "shadbala": 0.075, -} - - -def _relative_house(sign_index: int, ascendant_index: int) -> int: - return (sign_index - ascendant_index) % 12 + 1 - - -def _event_layer_points(fact: Mapping[str, Any]) -> dict[str, float]: - domain = str(fact["domain"]) - target_houses = set(DOMAIN_CONFIG[domain][1]) - d1 = fact["d1"] - active_lords = fact["vimshottari"] - target_lords = set(d1["target_house_lords"]) - - vimshottari_d1 = 0.0 - for level, weight in VIM_WEIGHTS.items(): - lord = active_lords[level] - if d1["active_lord_houses"].get(level) in target_houses: - vimshottari_d1 += weight - if lord in target_lords: - vimshottari_d1 += weight - - vargas = list(fact["vargas"]) - varga_points = 0.0 - if vargas: - for level, weight in VIM_WEIGHTS.items(): - matches = sum( - chart["active_lord_houses"].get(level) in target_houses - for chart in vargas - ) - varga_points += weight * matches / len(vargas) - - ascendant = int(d1["ascendant_sign"]) - narayana = fact["narayana"] - narayana_points = 0.0 - for key, weight in (("md_sign", 2.0), ("ad_sign", 1.0)): - sign = narayana.get(key) - if isinstance(sign, int) and _relative_house(sign, ascendant) in target_houses: - narayana_points += weight - - arudha_signs = { - value for value in fact["arudha_signs"].values() if isinstance(value, int) - } - arudha_points = 0.0 - if arudha_signs: - if narayana.get("md_sign") in arudha_signs: - arudha_points += 1.5 - if narayana.get("ad_sign") in arudha_signs: - arudha_points += 0.75 - - av_values = [ - float(value) - for value in fact["ashtakavarga_target_house_scores"].values() - if isinstance(value, int | float) - ] - av_points = sum(av_values) / len(av_values) / 40 if av_values else 0.0 - - shadbala_points = 0.0 - shadbala_states = set(fact["verified_shadbala_state"]) - if "shadbala_sthana_drik_naisargika_support_auxiliary" in shadbala_states: - shadbala_points = 0.25 - elif "shadbala_sthana_drik_naisargika_pressure_auxiliary" in shadbala_states: - shadbala_points = -0.125 - - return { - "vimshottari_d1": vimshottari_d1, - "varga": varga_points, - "narayana": narayana_points, - "arudha": arudha_points, - "ashtakavarga": av_points, - "shadbala": shadbala_points, - } - - -def _percentile_ranks(values: Mapping[str, float]) -> dict[str, float]: - if not values or len(set(values.values())) == 1: - return {candidate: 0.0 for candidate in values} - count = len(values) - return { - candidate: round(( - sum(other < value for other in values.values()) - + 0.5 * (sum(other == value for other in values.values()) - 1) - ) / (count - 1), 6) - for candidate, value in values.items() - } - - -def rank_fact_rows( - fact_rows: Sequence[dict[str, Any]], - events: Sequence[LifeEvent], - *, - excluded_layers: Iterable[str] = (), -) -> tuple[list[CandidateScoreRow], dict[str, Any]]: - rows = list(fact_rows) - event_list = list(events) - excluded = set(excluded_layers) - unknown = excluded - set(LAYER_FAMILIES) - if unknown: - raise ValueError(f"unsupported fact layer: {sorted(unknown)[0]}") - times = [row["time"] for row in rows] - by_time = { - row["time"]: {fact["event_id"]: fact for fact in row["event_facts"]} - for row in rows - } - raw_event_scores: dict[str, dict[str, float]] = {} - event_layer_ranks: dict[str, dict[str, dict[str, float]]] = {} - event_layer_points: dict[str, dict[str, dict[str, float]]] = {} - for event in event_list: - event_id = event["id"] - event_layer_points[event_id] = {} - for candidate_time in times: - fact = by_time[candidate_time].get(event_id) - layers = _event_layer_points(fact) if fact else {key: 0.0 for key in LAYER_FAMILIES} - event_layer_points[event_id][candidate_time] = layers - event_layer_ranks[event_id] = { - layer: _percentile_ranks({ - candidate_time: event_layer_points[event_id][candidate_time][layer] - for candidate_time in times - }) - for layer in LAYER_FAMILIES if layer not in excluded - } - active_weight = sum( - weight for layer, weight in LAYER_WEIGHTS.items() - if layer not in excluded - and any(event_layer_ranks[event_id][layer].values()) - ) - raw_event_scores[event_id] = { - candidate_time: round( - sum( - LAYER_WEIGHTS[layer] * ranks[candidate_time] - for layer, ranks in event_layer_ranks[event_id].items() - ) / active_weight if active_weight else 0.0, - 6, - ) - for candidate_time in times - } - event_ranks = raw_event_scores - event_ids_by_domain: dict[str, list[str]] = defaultdict(list) - for event in event_list: - event_ids_by_domain[event["domain"]].append(event["id"]) - - ranked: list[CandidateScoreRow] = [] - domain_scores_by_time: dict[str, dict[str, float]] = {} - for candidate_time in times: - domain_scores = { - domain: round( - sum( - event_ranks[event_id][candidate_time] - * precision_weight(next( - event["precision"] for event in event_list if event["id"] == event_id - )) - for event_id in event_ids - ) / sum( - precision_weight(next( - event["precision"] for event in event_list if event["id"] == event_id - )) - for event_id in event_ids - ), - 6, - ) - for domain, event_ids in event_ids_by_domain.items() - } - domain_scores_by_time[candidate_time] = domain_scores - overall = sum(domain_scores.values()) / len(domain_scores) if domain_scores else 0.0 - evidence = [{ - "event_id": event["id"], - "domain": event["domain"], - "candidate_time": candidate_time, - "rule_ids": [ - f"fact_v4_{layer}" - for layer, points in event_layer_points[event["id"]][candidate_time].items() - if layer not in excluded and points != 0 - ] or ["fact_v4_no_candidate_relative_support"], - "points": event_ranks[event["id"]][candidate_time], - } for event in event_list] - ranked.append({ - "time": candidate_time, - "score": round(overall * 100, 6), - "evidence": evidence, - "missing_layers": list(next( - (row["missing_layers"] for row in rows if row["time"] == candidate_time), - [], - )), - }) - return ranked, { - "schema_version": "minute-event-fact-ranker-v4", - "algorithm_version": ALGORITHM_VERSION, - "excluded_layers": sorted(excluded), - "event_raw_scores": raw_event_scores, - "event_layer_ranks": event_layer_ranks, - "layer_weights": LAYER_WEIGHTS, - "event_percentile_ranks": event_ranks, - "candidate_domain_scores": domain_scores_by_time, - "aggregation": "fixed_fact_rules_then_tie_aware_event_percentile_then_equal_domain_mean", - "shadow_only": True, - } - - -def _winning_segment(rows: Sequence[CandidateScoreRow]) -> dict[str, Any] | None: - if not rows: - return None - top = max(row["score"] for row in rows) - leaders = [row for row in rows if row["score"] == top] - segments: list[list[CandidateScoreRow]] = [] - for row in leaders: - if segments: - previous = segments[-1][-1]["time"] - previous_minute = int(previous[:2]) * 60 + int(previous[3:]) - current_minute = int(row["time"][:2]) * 60 + int(row["time"][3:]) - if (current_minute - previous_minute) % 1_440 == 1: - segments[-1].append(row) - continue - segments.append([row]) - if len(segments) != 1: - return None - winner = segments[0] - return { - "start_time": winner[0]["time"], - "end_time": winner[-1]["time"], - "representative_time": winner[(len(winner) - 1) // 2]["time"], - "width_minutes": len(winner), - } - - -def _leave_one_event_out( - fact_rows: Sequence[dict[str, Any]], events: Sequence[LifeEvent], full_leader: str | None, -) -> dict[str, Any]: - runs = [] - passed = full_leader is not None and len(events) >= 2 - for removed in events: - remaining = [event for event in events if event["id"] != removed["id"]] - rescored, _ = rank_fact_rows(fact_rows, remaining) - segment = _winning_segment(rescored) - retained = bool( - full_leader and segment and segment["width_minutes"] == 1 - and segment["representative_time"] == full_leader - ) - passed = passed and retained - runs.append({ - "removed_event_id": removed["id"], - "winning_segment": segment, - "original_unique_leader_retained": retained, - }) - return {"status": "pass" if passed else "fail", "runs": runs} - - -def _ablation_report( - fact_rows: Sequence[dict[str, Any]], events: Sequence[LifeEvent], full_leader: str | None, -) -> dict[str, Any]: - runs = [] - for layer in LAYER_FAMILIES: - rescored, _ = rank_fact_rows(fact_rows, events, excluded_layers={layer}) - segment = _winning_segment(rescored) - runs.append({ - "removed_layer": layer, - "winning_segment": segment, - "full_unique_leader_retained": bool( - full_leader and segment and segment["width_minutes"] == 1 - and segment["representative_time"] == full_leader - ), - }) - return {"scope": "fact_layer_ablation", "runs": runs} - - -def score_fact_ranker_v4( - fact_rows: Sequence[dict[str, Any]], events: Sequence[LifeEvent], -) -> dict[str, Any]: - rows, contract = rank_fact_rows(fact_rows, events) - segment = _winning_segment(rows) - full_leader = ( - segment["representative_time"] - if segment and segment["width_minutes"] == 1 else None - ) - neighbor = build_stability_diagnostics(rows, winning_segment=segment) - leave_one_out = _leave_one_event_out(fact_rows, events, full_leader) - ablation = _ablation_report(fact_rows, events, full_leader) - discriminability = analyze_candidate_rows(rows, ranking_rows=rows) - scores = sorted({row["score"] for row in rows}, reverse=True) - top = scores[0] if scores else 0.0 - second = scores[1] if len(scores) > 1 else top - domains = {event["domain"] for event in events} - missing = sorted({layer for row in rows for layer in row["missing_layers"]}) - reasons = [] - if not full_leader: - reasons.append("unique_minute_not_found") - if len(events) < 4: - reasons.append("insufficient_events") - if len(domains) < 3: - reasons.append("insufficient_domains") - if missing: - reasons.append("missing_mandatory_layers") - if not neighbor["all_required_passed"]: - reasons.append("neighbor_stability_not_passed") - if leave_one_out["status"] != "pass": - reasons.append("leave_one_event_out_not_passed") - if not discriminability["top_candidate_feature_unique"]: - reasons.append("top_candidate_feature_not_unique") - reasons.append("fact_ranker_v4_holdout_not_ready") - fingerprint = hashlib.sha256(json.dumps( - {"rows": rows, "events": list(events), "version": ALGORITHM_VERSION}, - ensure_ascii=True, sort_keys=True, separators=(",", ":"), - ).encode()).hexdigest() - return { - "result_id": str(uuid5(NAMESPACE_URL, f"{ALGORITHM_VERSION}:{fingerprint}")), - "confidence": "high" if len(reasons) == 1 else "low", - "can_apply": False, - "winning_segment": segment, - "event_count": len(events), - "domain_count": len(domains), - "top_score": top, - "second_score": second, - "margin_percent": round((top - second) / max(abs(top), 1.0) * 100, 2), - "reasons": reasons, - "algorithm_version": ALGORITHM_VERSION, - "missing_layers": missing, - "fact_ranking_contract": contract, - "stability_diagnostics": { - "neighbor_stability": neighbor, - "leave_one_event_out": leave_one_out, - "candidate_discriminability": discriminability, - "ablation": ablation, - }, - "shadow_only": True, - } diff --git a/scripts/minute_rectification_feature_facts_v4.py b/scripts/minute_rectification_feature_facts_v4.py deleted file mode 100644 index 44fd8a1e4..000000000 --- a/scripts/minute_rectification_feature_facts_v4.py +++ /dev/null @@ -1,286 +0,0 @@ -#!/usr/bin/env python3 -"""Lossless categorical fact atoms for adjacent-minute rectification diagnostics. - -This is a shadow-only feature contract. It preserves the identities and -placements behind generic scoring rule names, but never changes candidate -scores or opens minute confirmation. -""" -from __future__ import annotations - -import hashlib -import json -import math -from collections import defaultdict -from collections.abc import Sequence -from datetime import datetime -from typing import Any, Final - -from scripts import active_rectification_event_engine as engine -from scripts.active_rectification_events import LifeEvent, RectificationEventRequest - -FEATURE_CONTRACT_VERSION: Final = "minute-rectification-feature-facts-v4-shadow" - - -def _canonical_hash(value: Any) -> str: - payload = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")) - return hashlib.sha256(payload.encode("utf-8")).hexdigest() - - -def _arudha_keys(domain: str) -> tuple[str, ...]: - if domain == "relationship": - return ("A7", "UL") - if domain == "career": - return ("A10",) - return () - - -def _candidate_facts( - request: RectificationEventRequest, - candidate_at: datetime, -) -> dict[str, Any]: - chart = engine.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": engine.AYANAMSA, - "node_mode": engine.NODE_MODE, - }) - planet_longitudes = { - name: float(value["lon"]) - for name, value in chart.get("planets", {}).items() - if isinstance(value, dict) and isinstance(value.get("lon"), int | float) - } - ascendant_longitude = float(chart["ascendant"]["lon"]) - ascendant_index = int(ascendant_longitude // 30) - vargas = engine.varga.calc_all_vargas( - planet_longitudes, - ascendant_longitude, - divisions=[2, 4, 9, 10, 24, 30], - ) - d11 = engine._d11_chart(planet_longitudes, ascendant_longitude) - arudha_result = engine.jaimini.calc_arudha_padas(ascendant_index, planet_longitudes) - arudha = { - **(arudha_result.get("padas") or {}), - "UL": arudha_result.get("upapada") or {}, - } - av = engine.ashtakavarga.calc_ashtakavarga(chart.get("planets", {}), ascendant_index) - av_scores = av.get("house_scores_full") or {} - event_facts: list[dict[str, Any]] = [] - missing_layers: set[str] = set() - - for event in request["events"]: - prefixes, target_houses = engine.DOMAIN_CONFIG[event["domain"]] - domain_vargas = [ - d11 if prefix == "D11" else engine._varga_chart(vargas, prefix) - for prefix in prefixes - ] - if any(item is None for item in domain_vargas): - missing_layers.update(prefixes) - continue - event_at = engine._event_datetime(event) - try: - vim = engine._active_vimshottari( - candidate_at.date().isoformat(), planet_longitudes["Moon"], event_at, - ) - except (KeyError, TypeError, ValueError): - missing_layers.add("Vimshottari_MD_AD_PD") - continue - try: - narayana = engine._active_narayana( - ascendant_index, planet_longitudes, candidate_at, event_at, - ) - except (KeyError, TypeError, ValueError): - missing_layers.add("Narayana_MD_AD") - continue - if narayana[0] is None or narayana[1] is None: - missing_layers.add("Narayana_MD_AD") - continue - - active_lords = {"md": vim[0], "ad": vim[1], "pd": vim[2]} - varga_facts = [] - for prefix, varga_chart in zip(prefixes, domain_vargas, strict=True): - assert varga_chart is not None - varga_facts.append({ - "chart": prefix, - "ascendant_sign": (varga_chart.get("Ascendant") or {}).get("sign_idx"), - "active_lord_houses": { - level: engine._varga_house(varga_chart, lord) - for level, lord in active_lords.items() - }, - }) - relevant_arudha = { - key: (arudha.get(key) or {}).get("sign_idx") - for key in _arudha_keys(event["domain"]) - } - shadbala_rules, _ = engine._shadbala_verified_components_auxiliary( - chart, - candidate_at.hour + candidate_at.minute / 60, - vim, - ) - event_facts.append({ - "event_id": event["id"], - "domain": event["domain"], - "vimshottari": active_lords, - "narayana": {"md_sign": narayana[0], "ad_sign": narayana[1]}, - "d1": { - "ascendant_sign": ascendant_index, - "target_house_lords": sorted(engine._house_lords(ascendant_index, target_houses)), - "active_lord_houses": { - level: engine._planet_house(chart, lord) - for level, lord in active_lords.items() - }, - }, - "vargas": varga_facts, - "arudha_signs": relevant_arudha, - "ashtakavarga_target_house_scores": { - str(house): (av_scores.get(f"house_{house}") or {}).get("sav_score") - for house in target_houses - }, - "verified_shadbala_state": sorted(shadbala_rules), - }) - - return { - "time": candidate_at.strftime("%H:%M"), - "feature_contract_version": FEATURE_CONTRACT_VERSION, - "event_facts": event_facts, - "missing_layers": sorted(missing_layers), - } - - -def build_feature_fact_rows( - request: RectificationEventRequest, - *, - candidates: Sequence[datetime] | None = None, -) -> list[dict[str, Any]]: - candidate_datetimes = list(candidates) if candidates is not None else engine._candidate_datetimes(request) - return [_candidate_facts(request, candidate) for candidate in candidate_datetimes] - - -def feature_fact_fingerprint(row: dict[str, Any]) -> str: - """Hash facts only; candidate time and scorer output are deliberately excluded.""" - return _canonical_hash({ - "feature_contract_version": row["feature_contract_version"], - "event_facts": row["event_facts"], - "missing_layers": row["missing_layers"], - }) - - -def analyze_feature_fact_rows(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: - candidates = list(rows) - if not candidates: - return { - "scope": "minute_feature_fact_discriminability", - "feature_contract_version": FEATURE_CONTRACT_VERSION, - "candidate_count": 0, - "unique_feature_fingerprint_count": 0, - "indistinguishable_adjacent_pair_count": 0, - "status": "blocked_no_candidates", - "shadow_only": True, - } - fingerprints = {row["time"]: feature_fact_fingerprint(row) for row in candidates} - classes: dict[str, list[str]] = defaultdict(list) - for row in candidates: - classes[fingerprints[row["time"]]].append(row["time"]) - transitions = [] - for previous, current in zip(candidates, candidates[1:]): - previous_events = {item["event_id"]: item for item in previous["event_facts"]} - current_events = {item["event_id"]: item for item in current["event_facts"]} - changed = sorted( - event_id - for event_id in set(previous_events) | set(current_events) - if previous_events.get(event_id) != current_events.get(event_id) - ) - transitions.append({ - "between": [previous["time"], current["time"]], - "feature_changed": fingerprints[previous["time"]] != fingerprints[current["time"]], - "changed_event_ids": changed, - }) - unique_count = len(classes) - return { - "scope": "minute_feature_fact_discriminability", - "feature_contract_version": FEATURE_CONTRACT_VERSION, - "candidate_count": len(candidates), - "unique_feature_fingerprint_count": unique_count, - "distinguishable_candidate_ratio": round(unique_count / len(candidates), 4), - "equivalence_classes": [ - {"feature_fingerprint": fingerprint, "candidate_times": times, "size": len(times)} - for fingerprint, times in sorted(classes.items(), key=lambda item: item[1][0]) - ], - "adjacent_transitions": transitions, - "indistinguishable_adjacent_pair_count": sum( - not item["feature_changed"] for item in transitions - ), - "status": "facts_have_candidate_differences" if unique_count > 1 else "blocked_fact_equivalent_range", - "shadow_only": True, - "may_affect_candidate_score": False, - "boundary": "Fact atoms may select a discriminating question, but cannot rank or confirm a minute without a separately frozen evidence rule.", - } - - -def build_fact_difference_opportunities(rows: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: - """Partition candidates only where one event's actual fact atoms differ. - - The output deliberately contains no user-facing claim and no candidate - scores. It is an auditable input for a later question-planning layer. - """ - candidates = list(rows) - if not candidates: - return [] - facts_by_event: dict[str, dict[str, tuple[str, dict[str, Any]]]] = defaultdict(dict) - domains: dict[str, str] = {} - for row in candidates: - for fact in row["event_facts"]: - event_id = fact["event_id"] - domains[event_id] = fact["domain"] - material = { - key: value for key, value in fact.items() - if key not in {"event_id", "domain"} - } - facts_by_event[event_id][row["time"]] = (_canonical_hash(material), material) - opportunities = [] - for event_id, by_time in sorted(facts_by_event.items()): - groups: dict[str, list[str]] = defaultdict(list) - material_by_hash: dict[str, dict[str, Any]] = {} - for candidate_time, (fingerprint, material) in by_time.items(): - groups[fingerprint].append(candidate_time) - material_by_hash[fingerprint] = material - if len(groups) < 2: - continue - probabilities = [len(times) / len(by_time) for times in groups.values()] - information_gain = ( - -sum(value * math.log(value) for value in probabilities) / math.log(len(groups)) - if len(groups) > 1 else 0.0 - ) - ordered = sorted(groups.items(), key=lambda item: item[1][0]) - question_ready = 2 <= len(ordered) <= 4 - opportunities.append({ - "opportunity_id": _canonical_hash({ - "version": FEATURE_CONTRACT_VERSION, - "event_id": event_id, - "partitions": ordered, - }), - "event_id": event_id, - "domain": domains[event_id], - "estimated_information_gain": round(information_gain, 6), - "partitions": [ - { - "fact_fingerprint": fingerprint, - "candidate_times": times, - "fact_atoms": material_by_hash[fingerprint], - } - for fingerprint, times in ordered - ], - "question_ready": question_ready, - "requires_partition_coalescing": not question_ready, - "shadow_only": True, - "may_score_candidates": False, - }) - return sorted( - opportunities, - key=lambda item: (-item["estimated_information_gain"], item["opportunity_id"]), - ) diff --git a/scripts/minute_rectification_holdout_intake.py b/scripts/minute_rectification_holdout_intake.py deleted file mode 100644 index 5cf3ee836..000000000 --- a/scripts/minute_rectification_holdout_intake.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python3 -"""Append one independently reviewed case to a non-production v4 intake queue.""" - -from __future__ import annotations - -import argparse -import json -from datetime import UTC, datetime -from pathlib import Path -from typing import Any - -try: - from scripts.minute_rectification_holdout_validator import ( - FRESH_HUMAN_REVIEW_KIND, - case_errors, - ) -except ModuleNotFoundError: # pragma: no cover - direct script execution - from minute_rectification_holdout_validator import ( - FRESH_HUMAN_REVIEW_KIND, - case_errors, - ) - -INTAKE_SCHEMA_VERSION = "minute-rectification-holdout-v4-intake" -DEFAULT_INTAKE = ( - Path(__file__).resolve().parents[1] - / "references" - / "real_case_calibration" - / "minute_rectification_holdout_v4_intake.json" -) - - -def append_case(path: Path, case: dict[str, Any]) -> dict[str, Any]: - data = json.loads(path.read_text(encoding="utf-8")) - if data.get("schema_version") != INTAKE_SCHEMA_VERSION: - return {"appended": False, "errors": ["intake_schema_required"]} - gate = data.get("minimum_gate") if isinstance(data.get("minimum_gate"), dict) else {} - cases = data.get("cases") if isinstance(data.get("cases"), list) else [] - case_id = str(case.get("case_id") or "").strip() - if not case_id: - return {"appended": False, "errors": ["missing_case_id"]} - if any(isinstance(existing, dict) and existing.get("case_id") == case_id for existing in cases): - return {"appended": False, "errors": ["duplicate_case_id"]} - # Never auto-attest independent review. A true flag is accepted only when - # the caller already supplied a fresh biography-level human-review kind. - if ( - case.get("independent_human_reviewed") is True - and case.get("human_review_kind") != FRESH_HUMAN_REVIEW_KIND - ): - return {"appended": False, "errors": ["independent_review_requires_fresh_biography_audit"]} - errors = case_errors(case, gate, require_review_safeguards=True) - if errors: - return {"appended": False, "errors": errors} - - cases.append({**case, "ingested_at": datetime.now(UTC).isoformat().replace("+00:00", "Z")}) - data["cases"] = cases - data["status"] = "collecting_independently_reviewed_cases" - data["production_tuning_allowed"] = False - data["verified_minute_claim_allowed"] = False - path.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") - return { - "appended": True, - "errors": [], - "case_count": len(cases), - "verified_minute_claim_allowed": False, - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("manifest", nargs="?", type=Path, default=DEFAULT_INTAKE) - parser.add_argument("--case-json", required=True) - args = parser.parse_args() - result = append_case(args.manifest, json.loads(args.case_json)) - print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True)) - return 0 if result["appended"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/minute_rectification_holdout_validator.py b/scripts/minute_rectification_holdout_validator.py deleted file mode 100644 index 071d55ae5..000000000 --- a/scripts/minute_rectification_holdout_validator.py +++ /dev/null @@ -1,283 +0,0 @@ -#!/usr/bin/env python3 -"""Validate the frozen public AA minute-rectification holdout contract.""" -from __future__ import annotations - -import json -from datetime import date, datetime -from pathlib import Path -from typing import Any -from urllib.parse import urlparse - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_MANIFEST = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v2.json" -SUPPORTED_SCHEMA_VERSIONS = { - "minute-rectification-holdout-v2", - "minute-rectification-holdout-v3", - "minute-rectification-holdout-v4", -} -ALLOWED_DOMAINS = { - "education", "relocation", "relationship", "career", "finance", "health_pressure", -} -ALLOWED_PRECISIONS = {"year", "month", "day"} -FRESH_HUMAN_REVIEW_KIND = "fresh_biography_audit" -MIGRATED_HUMAN_REVIEW_KIND = "migrated_v3_record" - - -def _is_public_url(value: Any) -> bool: - if not isinstance(value, str): - return False - parsed = urlparse(value) - return parsed.scheme == "https" and bool(parsed.netloc) - - -def _parse_event_date(value: Any, precision: Any) -> date | None: - if not isinstance(value, str) or precision not in ALLOWED_PRECISIONS: - return None - try: - if precision == "day": - return datetime.strptime(value, "%Y-%m-%d").date() - if precision == "month": - return datetime.strptime(value, "%Y-%m").date() - return datetime.strptime(value, "%Y").date() - except ValueError: - return None - - -def _case_errors(case: Any, gate: dict[str, Any]) -> list[str]: - if not isinstance(case, dict): - return ["case_must_be_object"] - errors: list[str] = [] - case_id = case.get("case_id") - if not isinstance(case_id, str) or not case_id.strip(): - errors.append("missing_case_id") - if case.get("holdout_partition") != "sealed_evaluation": - errors.append("case_not_in_sealed_evaluation_partition") - if case.get("excluded_from_tuning") is not True: - errors.append("case_not_excluded_from_tuning") - - birth = case.get("birth") if isinstance(case.get("birth"), dict) else {} - source = birth.get("source") if isinstance(birth.get("source"), dict) else {} - try: - birth_date = date.fromisoformat(str(birth.get("date"))) - except ValueError: - birth_date = None - errors.append("invalid_birth_date") - try: - datetime.strptime(str(birth.get("time")), "%H:%M") - except ValueError: - errors.append("invalid_birth_time") - for field, lower, upper in (("latitude", -90, 90), ("longitude", -180, 180), ("timezone_offset", -14, 14)): - value = birth.get(field) - if not isinstance(value, int | float) or not lower <= float(value) <= upper: - errors.append(f"invalid_birth_{field}") - if source.get("rodden_rating") != "AA": - errors.append("birth_source_not_rodden_aa") - if source.get("record_type") != "birth_record": - errors.append("birth_source_not_record_based") - if not _is_public_url(source.get("url")): - errors.append("invalid_birth_source_url") - if not isinstance(source.get("publisher"), str) or not source.get("publisher", "").strip(): - errors.append("missing_birth_source_publisher") - - events = case.get("events") if isinstance(case.get("events"), list) else [] - minimum_events = int(gate.get("events_per_case", 3)) - if len(events) < minimum_events: - errors.append("insufficient_events") - event_ids: list[str] = [] - domains: set[str] = set() - source_urls: set[str] = set() - for index, event in enumerate(events): - prefix = f"event_{index + 1}" - if not isinstance(event, dict): - errors.append(f"{prefix}_must_be_object") - continue - event_id = event.get("id") - if not isinstance(event_id, str) or not event_id.strip(): - errors.append(f"{prefix}_missing_id") - else: - event_ids.append(event_id) - domain = event.get("domain") - if domain not in ALLOWED_DOMAINS: - errors.append(f"{prefix}_invalid_domain") - else: - domains.add(domain) - event_date = _parse_event_date(event.get("date"), event.get("precision")) - if event_date is None: - errors.append(f"{prefix}_invalid_date") - elif birth_date is not None and event_date <= birth_date: - errors.append(f"{prefix}_not_after_birth") - event_source = event.get("source") if isinstance(event.get("source"), dict) else {} - source_url = event_source.get("url") - if not _is_public_url(source_url): - errors.append(f"{prefix}_invalid_source_url") - else: - source_urls.add(source_url) - if source_url == source.get("url"): - errors.append(f"{prefix}_source_not_independent_of_birth") - if event_source.get("independent_of_birth_source") is not True: - errors.append(f"{prefix}_independence_not_attested") - if not isinstance(event_source.get("publisher"), str) or not event_source.get("publisher", "").strip(): - errors.append(f"{prefix}_missing_source_publisher") - if len(event_ids) != len(set(event_ids)): - errors.append("duplicate_event_ids") - if len(domains) < int(gate.get("domains_per_case", 2)): - errors.append("insufficient_event_domains") - if len(source_urls) < int(gate.get("independent_event_sources_per_case", 2)): - errors.append("insufficient_independent_event_sources") - - radius = case.get("candidate_radius_minutes") - offsets = case.get("false_minute_offsets") if isinstance(case.get("false_minute_offsets"), list) else [] - if not isinstance(radius, int) or not 5 <= radius <= 60: - errors.append("invalid_candidate_radius") - valid_offsets = all(isinstance(offset, int) and offset != 0 for offset in offsets) - if not valid_offsets or len(offsets) != len(set(offsets)): - errors.append("invalid_false_minute_offsets") - else: - needed = int(gate.get("negative_minutes_per_case", 4)) - if len(offsets) < needed: - errors.append("insufficient_false_minutes") - if not any(offset < 0 for offset in offsets) or not any(offset > 0 for offset in offsets): - errors.append("false_minutes_do_not_cover_both_sides") - if not {-2, -1, 1, 2}.issubset(set(offsets)): - errors.append("false_minutes_missing_adjacent_controls") - if isinstance(radius, int) and any(abs(offset) > radius for offset in offsets): - errors.append("false_minute_outside_candidate_radius") - return errors - - -def _prior_score_exposures(case: Any) -> list[Any]: - raw = case.get("prior_score_exposures") if isinstance(case, dict) else None - if not isinstance(raw, list): - return [] - return [item for item in raw if item] - - -def _review_safeguard_errors(case: Any, gate: dict[str, Any]) -> list[str]: - """Validate safeguards required for newly admitted v4 holdout cases.""" - if not isinstance(case, dict): - return ["case_must_be_object"] - errors: list[str] = [] - if not isinstance(case.get("adjudicator"), str) or not case.get("adjudicator", "").strip(): - errors.append("missing_independent_adjudicator") - if _prior_score_exposures(case): - errors.append("results_already_seen_cannot_be_blind_holdout") - review_kind = case.get("human_review_kind") - if review_kind == MIGRATED_HUMAN_REVIEW_KIND: - errors.append("migrated_review_does_not_satisfy_safeguard") - if review_kind != FRESH_HUMAN_REVIEW_KIND: - errors.append("fresh_biography_audit_not_attested") - if case.get("independent_human_reviewed") is not True: - errors.append("independent_review_not_attested") - if case.get("frozen_before_scoring") is not True: - errors.append("case_not_frozen_before_scoring") - - events = case.get("events") if isinstance(case.get("events"), list) else [] - day_precision_count = sum( - isinstance(event, dict) - and event.get("precision") == "day" - and _parse_event_date(event.get("date"), event.get("precision")) is not None - for event in events - ) - if day_precision_count < int(gate.get("day_precision_events_per_case", 3)): - errors.append("insufficient_day_precision_events") - - offsets = case.get("false_minute_offsets") if isinstance(case.get("false_minute_offsets"), list) else [] - commitments = ( - case.get("false_minute_commitments") - if isinstance(case.get("false_minute_commitments"), list) - else [] - ) - committed_offsets: list[int] = [] - hashes: list[str] = [] - for item in commitments: - if not isinstance(item, dict): - errors.append("invalid_false_minute_commitment") - continue - offset = item.get("offset_minutes") - commitment_hash = item.get("commitment_hash") - if not isinstance(offset, int) or offset == 0: - errors.append("invalid_false_minute_commitment_offset") - else: - committed_offsets.append(offset) - if ( - not isinstance(commitment_hash, str) - or len(commitment_hash) != 64 - or any(character not in "0123456789abcdef" for character in commitment_hash.lower()) - ): - errors.append("invalid_false_minute_commitment_hash") - else: - hashes.append(commitment_hash.lower()) - if any(key in item for key in ("candidate_minute", "published_minute", "birth_time")): - errors.append("false_minute_commitment_leaks_time") - if sorted(committed_offsets) != sorted(offsets): - errors.append("false_minute_commitments_do_not_match_offsets") - if len(hashes) != len(set(hashes)): - errors.append("duplicate_false_minute_commitment_hash") - return errors - - -def case_errors(case: Any, gate: dict[str, Any], *, require_review_safeguards: bool = False) -> list[str]: - """Public case-level validator shared by frozen manifests and intake tooling.""" - errors = _case_errors(case, gate) - if require_review_safeguards: - errors.extend(_review_safeguard_errors(case, gate)) - return sorted(set(errors)) - - -def validate(manifest_path: Path = DEFAULT_MANIFEST) -> dict[str, Any]: - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - gate = manifest.get("minimum_gate") if isinstance(manifest.get("minimum_gate"), dict) else {} - cases = manifest.get("cases") if isinstance(manifest.get("cases"), list) else [] - manifest_errors: list[str] = [] - if manifest.get("schema_version") not in SUPPORTED_SCHEMA_VERSIONS: - manifest_errors.append("unsupported_schema_version") - if manifest.get("truth_hidden_from_ranker") is not True: - manifest_errors.append("truth_not_hidden_from_ranker") - if manifest.get("frozen_before_replay") is not True: - manifest_errors.append("benchmark_not_frozen_before_replay") - if ( - manifest.get("schema_version") in { - "minute-rectification-holdout-v3", - "minute-rectification-holdout-v4", - } - and manifest.get("source_audit_status") != "passed_before_freeze" - ): - manifest_errors.append("source_content_audit_not_passed_before_freeze") - scoring = manifest.get("frozen_scoring") if isinstance(manifest.get("frozen_scoring"), dict) else {} - if not scoring.get("algorithm_version") or not scoring.get("implementation_sha256"): - manifest_errors.append("missing_frozen_scoring_identity") - - seen_ids: set[str] = set() - invalid_details: list[dict[str, Any]] = [] - valid_cases = 0 - require_review_safeguards = manifest.get("schema_version") == "minute-rectification-holdout-v4" - for case in cases: - errors = case_errors(case, gate, require_review_safeguards=require_review_safeguards) - case_id = case.get("case_id") if isinstance(case, dict) else "non_object_case" - if isinstance(case_id, str) and case_id in seen_ids: - errors.append("duplicate_case_id") - if isinstance(case_id, str): - seen_ids.add(case_id) - if errors: - invalid_details.append({"case_id": case_id or "unnamed_case", "errors": sorted(set(errors))}) - else: - valid_cases += 1 - - needed = int(gate.get("public_aa_cases", 20)) - ready = not manifest_errors and not invalid_details and valid_cases >= needed - return { - "scope": "minute_rectification_holdout_validation", - "benchmark_id": manifest.get("benchmark_id"), - "status": "ready_for_blind_replay" if ready else "blocked_awaiting_public_aa_cases", - "valid_public_aa_cases": valid_cases, - "minimum_public_aa_cases": needed, - "manifest_errors": manifest_errors, - "invalid_cases": [item["case_id"] for item in invalid_details], - "invalid_case_details": invalid_details, - "verified_minute_claim_allowed": False, - "boundary": manifest.get("boundary"), - } - - -if __name__ == "__main__": - print(json.dumps(validate(), ensure_ascii=False, indent=2, sort_keys=True)) diff --git a/scripts/minute_rectification_pairwise_v3.py b/scripts/minute_rectification_pairwise_v3.py deleted file mode 100644 index 5edecf33b..000000000 --- a/scripts/minute_rectification_pairwise_v3.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python3 -"""Domain-balanced, difference-only candidate ranking for rectification v3.""" -from __future__ import annotations - -import hashlib -import json -from collections import defaultdict -from collections.abc import Sequence -from typing import Any, Final -from uuid import NAMESPACE_URL, uuid5 - -from scripts.active_rectification_events import ( - CandidateScoreRow, - LifeEvent, - build_stability_diagnostics, -) -from scripts.minute_candidate_discriminability import analyze_candidate_rows - -ALGORITHM_VERSION: Final = "birth-time-event-pairwise-v3" - - -def _percentile_ranks(values: dict[str, float]) -> dict[str, float]: - """Map one event's candidate points to tie-aware [0, 1] ranks.""" - if not values: - return {} - unique = set(values.values()) - if len(unique) == 1: - return {candidate: 0.0 for candidate in values} - count = len(values) - return { - candidate: round( - ( - sum(other < value for other in values.values()) - + 0.5 * (sum(other == value for other in values.values()) - 1) - ) / (count - 1), - 6, - ) - for candidate, value in values.items() - } - - -def rank_candidate_rows( - raw_rows: Sequence[CandidateScoreRow], - events: Sequence[LifeEvent], -) -> tuple[list[CandidateScoreRow], dict[str, Any]]: - """Rank within each event, average within domains, then weight domains equally.""" - rows = list(raw_rows) - times = [row["time"] for row in rows] - evidence_by_time = { - row["time"]: {item["event_id"]: item for item in row["evidence"]} - for row in rows - } - event_ranks: dict[str, dict[str, float]] = {} - constant_events: list[str] = [] - for event in events: - points = { - candidate_time: float((evidence_by_time[candidate_time].get(event["id"]) or {}).get("points", 0.0)) - for candidate_time in times - } - ranks = _percentile_ranks(points) - event_ranks[event["id"]] = ranks - if len(set(points.values())) <= 1: - constant_events.append(event["id"]) - - event_ids_by_domain: dict[str, list[str]] = defaultdict(list) - for event in events: - event_ids_by_domain[event["domain"]].append(event["id"]) - candidate_domain_scores: dict[str, dict[str, float]] = {} - ranked_rows: list[CandidateScoreRow] = [] - for row in rows: - domain_scores = { - domain: round( - sum(event_ranks[event_id][row["time"]] for event_id in event_ids) / len(event_ids), - 6, - ) - for domain, event_ids in event_ids_by_domain.items() - } - candidate_domain_scores[row["time"]] = domain_scores - overall = sum(domain_scores.values()) / len(domain_scores) if domain_scores else 0.0 - ranked_rows.append({ - **row, - "score": round(overall * 100, 6), - }) - return ranked_rows, { - "schema_version": "minute-pairwise-domain-balanced-v1", - "algorithm_version": ALGORITHM_VERSION, - "event_count": len(events), - "domain_count": len(event_ids_by_domain), - "constant_event_ids": sorted(constant_events), - "discriminating_event_ids": sorted(set(event_ranks) - set(constant_events)), - "event_percentile_ranks": event_ranks, - "candidate_domain_scores": candidate_domain_scores, - "aggregation": "tie_aware_event_percentile_then_domain_mean_then_equal_domain_mean", - "boundary": "Common support shared by every candidate contributes zero and repeated events cannot increase a domain's weight.", - } - - -def _winning_segment(rows: Sequence[CandidateScoreRow]) -> dict[str, Any] | None: - if not rows: - return None - top = max(row["score"] for row in rows) - leaders = [row for row in rows if row["score"] == top] - if not leaders: - return None - segments: list[list[CandidateScoreRow]] = [] - for row in leaders: - if segments: - previous = segments[-1][-1]["time"] - previous_minute = int(previous[:2]) * 60 + int(previous[3:]) - current_minute = int(row["time"][:2]) * 60 + int(row["time"][3:]) - if (current_minute - previous_minute) % 1440 == 1: - segments[-1].append(row) - continue - segments.append([row]) - if len(segments) != 1: - return None - winner = segments[0] - return { - "start_time": winner[0]["time"], - "end_time": winner[-1]["time"], - "representative_time": winner[(len(winner) - 1) // 2]["time"], - "width_minutes": len(winner), - } - - -def _leave_one_event_out(raw_rows: list[CandidateScoreRow], events: list[LifeEvent]) -> dict[str, Any]: - full_rows, _ = rank_candidate_rows(raw_rows, events) - full_segment = _winning_segment(full_rows) - full_leader = full_segment["representative_time"] if full_segment and full_segment["width_minutes"] == 1 else None - runs = [] - stable = full_leader is not None - for event in events: - remaining = [item for item in events if item["id"] != event["id"]] - rescored, _ = rank_candidate_rows(raw_rows, remaining) - segment = _winning_segment(rescored) - retained = bool( - full_leader - and segment - and segment["width_minutes"] == 1 - and segment["representative_time"] == full_leader - ) - stable = stable and retained - runs.append({ - "removed_event_id": event["id"], - "winning_segment": segment, - "original_unique_leader_retained": retained, - }) - return { - "status": "pass" if stable else "fail", - "runs": runs, - "boundary": "Every event deletion must retain the same unique leading minute after ranks and domain means are recomputed.", - } - - -def score_pairwise_v3(raw_rows: Sequence[CandidateScoreRow], events: Sequence[LifeEvent]) -> dict[str, Any]: - """Produce a guarded v3 candidate result without opening minute confirmation.""" - raw = list(raw_rows) - event_list = list(events) - rows, contract = rank_candidate_rows(raw, event_list) - segment = _winning_segment(rows) - unique_scores = sorted({row["score"] for row in rows}, reverse=True) - top_score = unique_scores[0] if unique_scores else 0.0 - second_score = unique_scores[1] if len(unique_scores) > 1 else top_score - margin = round((top_score - second_score) / max(abs(top_score), 1.0) * 100, 2) - missing = sorted({layer for row in raw for layer in row["missing_layers"]}) - neighbor = build_stability_diagnostics(rows, winning_segment=segment) - leave_one_out = _leave_one_event_out(raw, event_list) - discriminability = analyze_candidate_rows(raw, ranking_rows=rows) - domains = {event["domain"] for event in event_list} - reasons: list[str] = [] - if segment is None: - reasons.append("tied_or_disconnected_leader") - elif segment["width_minutes"] != 1: - reasons.append("leading_range_not_unique_minute") - if len(event_list) < 3: - reasons.append("insufficient_events") - if len(domains) < 2: - reasons.append("insufficient_domains") - if missing: - reasons.append("missing_mandatory_layers") - if not neighbor["all_required_passed"]: - reasons.append("neighbor_stability_not_passed") - if leave_one_out["status"] != "pass": - reasons.append("leave_one_event_out_not_passed") - if not discriminability["top_candidate_feature_unique"]: - reasons.append("top_candidate_feature_not_unique") - high = ( - len(event_list) >= 4 - and len(domains) >= 3 - and not reasons - ) - medium = ( - len(event_list) >= 3 - and len(domains) >= 2 - and segment is not None - and segment["width_minutes"] <= 15 - and not missing - ) - confidence = "high" if high else "medium" if medium else "low" - reasons.append("pairwise_v3_holdout_not_ready") - fingerprint = hashlib.sha256(json.dumps( - {"rows": rows, "events": event_list, "version": ALGORITHM_VERSION}, - ensure_ascii=True, - sort_keys=True, - separators=(",", ":"), - ).encode()).hexdigest() - return { - "result_id": str(uuid5(NAMESPACE_URL, f"{ALGORITHM_VERSION}:{fingerprint}")), - "confidence": confidence, - "can_apply": False, - "winning_segment": segment, - "event_count": len(event_list), - "domain_count": len(domains), - "top_score": top_score, - "second_score": second_score, - "margin_percent": margin, - "reasons": reasons, - "algorithm_version": ALGORITHM_VERSION, - "missing_layers": missing, - "pairwise_contract": contract, - "stability_diagnostics": { - "neighbor_stability": neighbor, - "leave_one_event_out": leave_one_out, - "candidate_discriminability": discriminability, - }, - } diff --git a/scripts/minute_rectification_source_audit.py b/scripts/minute_rectification_source_audit.py deleted file mode 100644 index e2c8f0e56..000000000 --- a/scripts/minute_rectification_source_audit.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python3 -"""Audit reusable public AA cases before admitting them to a minute holdout.""" - -from __future__ import annotations - -import argparse -import json -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[1] -DEFAULT_SOURCES = ( - ROOT / "references" / "real_case_calibration" / "replay_manifest.json", - ROOT / "references" / "real_case_calibration" / "replay_manifest_holdout_v2.json", - ROOT / "references" / "real_case_calibration" / "replay_manifest_probe3_v2.json", - ROOT / "references" / "real_case_calibration" / "public_context_manifest.json", -) - - -def _events(case: dict[str, Any]) -> list[dict[str, Any]]: - raw = case.get("events") if isinstance(case.get("events"), list) else case.get("event_outcomes") - return [event for event in raw or [] if isinstance(event, dict)] - - -def _birth_source(subject: dict[str, Any]) -> dict[str, Any]: - if isinstance(subject.get("birth_source"), dict): - return subject["birth_source"] - birth = subject.get("birth") if isinstance(subject.get("birth"), dict) else {} - return birth.get("source") if isinstance(birth.get("source"), dict) else {} - - -def _is_aa(source: dict[str, Any]) -> bool: - return source.get("time_accuracy_rating") == "AA" or source.get("rodden_rating") == "AA" - - -def build_source_audit(paths: list[Path] | tuple[Path, ...] = DEFAULT_SOURCES) -> dict[str, Any]: - entries: dict[str, dict[str, Any]] = {} - for path in paths: - data = json.loads(path.read_text(encoding="utf-8")) - for case in data.get("cases", []): - if not isinstance(case, dict): - continue - subject = case.get("subject") if isinstance(case.get("subject"), dict) else case - source = _birth_source(subject) - source_url = str(source.get("url") or "") - if not _is_aa(source) or not source_url: - continue - label = str(subject.get("name") or subject.get("subject_label") or case.get("case_id") or "unnamed") - entry = entries.setdefault(source_url, { - "subject": label, - "birth_source_url": source_url, - "case_ids": [], - "day_precision_event_dates": set(), - }) - entry["case_ids"].append(str(case.get("case_id") or label)) - for event in _events(case): - event_date = str(event.get("event_date") or event.get("date") or "") - if len(event_date) == 10: - entry["day_precision_event_dates"].add(event_date) - - cases = [] - for entry in entries.values(): - event_count = len(entry["day_precision_event_dates"]) - cases.append({ - "subject": entry["subject"], - "birth_source_url": entry["birth_source_url"], - "case_ids": sorted(set(entry["case_ids"])), - "existing_day_precision_event_count": event_count, - "additional_day_precision_events_required": max(0, 3 - event_count), - "review_and_commitment_controls_required": True, - }) - cases.sort(key=lambda case: (case["additional_day_precision_events_required"], case["subject"])) - return { - "scope": "minute_rectification_public_aa_source_audit", - "public_aa_case_count": len(cases), - "minimum_public_aa_cases": 20, - "additional_public_aa_cases_required": max(0, 20 - len(cases)), - "cases": cases, - "production_tuning_allowed": False, - "boundary": ( - "Source discovery is not holdout validation. Every promoted case still requires " - "independent review, day-precision events and committed false-minute controls." - ), - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("sources", nargs="*", type=Path, default=list(DEFAULT_SOURCES)) - parser.add_argument("--output", type=Path) - args = parser.parse_args() - result = build_source_audit(args.sources) - text = json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True) - if args.output: - args.output.write_text(text + "\n", encoding="utf-8") - print(text) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/pyjhora_rectification_d1_reference.py b/scripts/pyjhora_rectification_d1_reference.py deleted file mode 100644 index 7bbda700b..000000000 --- a/scripts/pyjhora_rectification_d1_reference.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Optional PyJHora D1 signs for the rectification parity packet. - -The product packet calls this only for the PyJHora column. A missing install -raises, and the packet records that column as blocked. -""" - -from __future__ import annotations - -import importlib -from typing import Any - -SIGNS = ( - "Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", - "Libra", "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces", -) - - -def pyjhora_d1(case: dict[str, Any]) -> dict[str, str]: - utils = importlib.import_module("jhora.utils") - charts = importlib.import_module("jhora.horoscope.chart.charts") - drik = importlib.import_module("jhora.panchanga.drik") - jd = utils.julian_day_number( - (case["year"], case["month"], case["day"]), - (case["hour"], case["minute"], case.get("second", 0)), - ) - drik.set_ayanamsa_mode("LAHIRI", jd=jd) - place = drik.Place("request-level", case["lat"], case["lon"], case["tz"]) - index_to_planet = { - 0: "Sun", 1: "Moon", 2: "Mars", 3: "Mercury", 4: "Jupiter", 5: "Venus", 6: "Saturn", - } - return { - index_to_planet[body]: SIGNS[int(position[0])] - for body, position in charts.rasi_chart(jd, place) - if body in index_to_planet - } diff --git a/scripts/rectification/api_service.py b/scripts/rectification/api_service.py deleted file mode 100644 index 304747a37..000000000 --- a/scripts/rectification/api_service.py +++ /dev/null @@ -1,599 +0,0 @@ -from __future__ import annotations - -from typing import Any, Mapping, Sequence -from uuid import NAMESPACE_URL, uuid5 - -from scripts.active_rectification_events import build_candidate_result_summary -from scripts.offline_compute_mixins import BadRequest -from scripts.rectification.candidate_feature_service import build_candidate_feature_snapshot -from scripts.rectification.candidate_window import enumerate_candidate_window -from scripts.rectification.contracts import ( - EVENT_CONTRACT_VERSION, - RectificationRequest, - is_primary_scoreable_event, -) -from scripts.rectification.decision_policy import ( - EXECUTION_LEDGER_VERSION, - POLICY_VERSION, - build_candidate_decisions, - build_decision_receipt, - build_execution_ledger, -) -from scripts.rectification.diagnostics_service import run_diagnostics -from scripts.rectification.scoring_service import ( - ALGORITHM_VERSION, - build_event_contribution_matrix, - calculation_spec, - score_from_matrix, - scoreable_request, - sha256, -) - - -def _clock_minutes(value: str) -> int: - hour, minute = value[:5].split(":", 1) - return int(hour) * 60 + int(minute) - - -def _window_width(start_time: str, end_time: str) -> int: - return (_clock_minutes(end_time) - _clock_minutes(start_time)) % 1_440 + 1 - - -def _report_candidate_range( - request: RectificationRequest, - candidate_scores: Sequence[dict[str, Any]], - representative_time: str | None, -) -> dict[str, Any]: - top_score = max((float(row.get("score") or 0) for row in candidate_scores), default=None) - top_times = [ - str(row.get("time"))[:5] - for row in candidate_scores - if top_score is not None and float(row.get("score") or 0) == top_score - ] - if "candidate_intervals" in request: - from scripts.rectification.candidate_window import candidate_positions, enumerate_candidate_window, intervals_from_positions, interval_union_width - positions = candidate_positions(request, enumerate_candidate_window(request)) - selected = [row for row in positions if not top_times or row["time"] in top_times] - parts = intervals_from_positions(selected) - return { - "start_time": selected[0]["time"], "end_time": selected[-1]["time"], - "candidate_intervals": [{"start_at": part["start_at"], "end_at": part["end_at"]} for part in parts], - "representative_time": representative_time or selected[len(selected) // 2]["time"], - "width_minutes": interval_union_width(parts), "representative_is_unique": False, - } - if not top_times: - return { - "start_time": request["start_time"], - "end_time": request["end_time"], - "representative_time": representative_time, - "width_minutes": _window_width(request["start_time"], request["end_time"]), - "representative_is_unique": False, - } - return { - "start_time": top_times[0], - "end_time": top_times[-1], - "representative_time": representative_time or top_times[len(top_times) // 2], - "width_minutes": len(top_times), - "representative_is_unique": False, - } - - -def _window_span_minutes(start_time: str, end_time: str) -> int: - start = _clock_minutes(start_time) - end = _clock_minutes(end_time) - return end - start if end >= start else 1440 - start + end - - -def _adaptive_minute_step(start_time: str, end_time: str) -> int: - width = _window_span_minutes(start_time, end_time) - if width > 360: - return 10 - if width > 180: - return 5 - return 2 - - -def _block_scan_periods(request: RectificationRequest) -> list[tuple[str, str, str]]: - custom = request.get("blocks") - if isinstance(custom, list) and custom: - periods: list[tuple[str, str, str]] = [] - for item in custom: - if not isinstance(item, dict): - continue - label = str(item.get("period") or item.get("label") or "") - start_time = str(item.get("start_time") or "")[:5] - end_time = str(item.get("end_time") or "")[:5] - if label and start_time and end_time: - periods.append((label, start_time, end_time)) - if periods: - return periods - return list(BLOCK_SCAN_PERIODS) - - -def _report_evidence( - request: RectificationRequest, - built: dict[str, Any], - representative_time: str | None, -) -> list[dict[str, Any]]: - matrix = built.get("matrix") or {} - rows: list[dict[str, Any]] = [] - for event in request.get("events") or []: - if not is_primary_scoreable_event(event): - continue - contribution = (matrix.get(event["id"]) or {}).get(representative_time or "") - contribution = contribution if isinstance(contribution, dict) else {} - points = float(contribution.get("points") or 0) - status = "supporting" if points > 0 else "contradictory" if points < 0 else "unconfirmed" - rows.append({ - "event_id": event["id"], - "summary": str(event.get("summary") or "").strip(), - "domain": event["domain"], - "date": { - "start": event["date_start"], - "end": event["date_end"], - "precision": event["precision"], - }, - "status": status, - "supports_candidate_time": representative_time if status == "supporting" else None, - "methods": sorted({str(layer) for layer in contribution.get("technique_layers") or []}), - }) - return rows - - -def _report_excluded_candidates( - candidate_decisions: Sequence[dict[str, Any]], - representative_time: str | None, -) -> list[dict[str, Any]]: - return [ - { - "time": str(candidate.get("time") or "")[:5], - "reason": "not_the_leading_candidate", - "representative_time": representative_time, - } - for candidate in candidate_decisions - if str(candidate.get("time") or "")[:5] != (representative_time or "") - ] - - -def _confirmation_blockers(receipt: dict[str, Any]) -> list[dict[str, str]]: - allowed = {"VedAstro 分钟级校验", "唯一分钟确认"} - return [ - { - "technique": str(row.get("technique")), - "status": str(row.get("status")), - "user_meaning": str(row.get("note") or ""), - } - for row in receipt.get("technique_audit_table") or [] - if isinstance(row, dict) - and str(row.get("technique")) in allowed - and str(row.get("status")) != "executed" - ] - - -def _rectification_report( - request: RectificationRequest, - built: dict[str, Any], - candidate_scores: Sequence[dict[str, Any]], - candidate_decisions: Sequence[dict[str, Any]], - receipt: dict[str, Any], -) -> dict[str, Any]: - representative_time = str(receipt.get("representative_time") or "")[:5] or None - blockers = _confirmation_blockers(receipt) - candidate_range = _report_candidate_range(request, candidate_scores, representative_time) - limitations = [item["user_meaning"] for item in blockers if item["user_meaning"]] - if not limitations: - limitations.append("本会话以代表性时间收口,不确认唯一分钟。") - return { - "candidate_range": candidate_range, - "representative_time": representative_time, - "representative_label": "代表性候选,不是唯一解", - "confidence": receipt.get("overall_confidence", "low"), - "evidence": _report_evidence(request, built, representative_time), - "excluded_candidates": _report_excluded_candidates(candidate_decisions, representative_time), - "next_step_codes": [], - "confirmation_gate_blockers": blockers, - "limitations": limitations, - "claim_status": "candidate_range_not_birth_time_truth", - } - - -MAX_CANDIDATES_PER_REQUEST = 241 - - -class TooManyCandidates(BadRequest): - """Rejected before any chart is computed. - - The API server maps every BadRequest to HTTP 400 with error_code - ERR_BAD_REQUEST and this task must not edit that server. The token - too_many_candidates lives in the message, with the cap and the count. - """ - - code = "too_many_candidates" - - def __init__(self, count: int) -> None: - self.count = int(count) - self.limit = MAX_CANDIDATES_PER_REQUEST - super().__init__(f"too_many_candidates: limit={self.limit} count={self.count}") - - -def _candidate_count(request: RectificationRequest) -> int: - return len(enumerate_candidate_window(request)) - - -def _reject_if_too_many_candidates(request: RectificationRequest) -> None: - count = _candidate_count(request) - if count > MAX_CANDIDATES_PER_REQUEST: - raise TooManyCandidates(count) - - -def engine_scoring_versions() -> dict[str, str]: - """Identity fields also returned by `/api/rectification/v5/score`, without scoring.""" - return { - "algorithm_version": ALGORITHM_VERSION, - "event_contract_version": EVENT_CONTRACT_VERSION, - "decision_policy_version": POLICY_VERSION, - } - - -def candidate_features(request: RectificationRequest) -> dict[str, Any]: - spec = calculation_spec(request) - spec_hash = sha256(spec) - scoring_request = scoreable_request(request) - return { - "algorithm_version": ALGORITHM_VERSION, - "event_contract_version": EVENT_CONTRACT_VERSION, - "decision_policy_version": POLICY_VERSION, - "calculation_spec": spec, - "calculation_spec_hash": spec_hash, - "candidate_feature_snapshot": build_candidate_feature_snapshot(scoring_request, spec_hash), - "can_confirm_exact_minute": False, - } - - -def score_candidates( - request: RectificationRequest, - *, - include_internal: bool = False, - enforce_candidate_cap: bool = True, -) -> dict[str, Any]: - if enforce_candidate_cap: - _reject_if_too_many_candidates(request) - scoring_request = scoreable_request(request) - built = build_event_contribution_matrix(scoring_request) - rows = score_from_matrix(scoring_request, built) - spec = calculation_spec(request) - spec_hash = sha256(spec) - diagnostic_values = run_diagnostics(scoring_request, rows, built) - fingerprint = sha256({ - key: value - for key, value in request.items() - if key not in {"asked_probe_keys", "dropped_asked_probe_keys", "declined_domains", "column_times", "refresh_probes"} - }) - result_id = str(uuid5(NAMESPACE_URL, f"{ALGORITHM_VERSION}:{fingerprint}")) - candidate_decisions = build_candidate_decisions( - rows, - result_id=result_id, - static_contexts=built.get("static_contexts") if isinstance(built.get("static_contexts"), list) else None, - ) - decision_receipt = build_decision_receipt(request, candidate_decisions, built, diagnostic_values) - from scripts.rectification.candidate_window import candidate_intervals - decision_receipt.update({"candidate_window_contract": "dated-v1", "candidate_intervals": candidate_intervals(request), - "candidate_timezone_offset": request["tz"], "candidate_timezone_id": request.get("timezone_id", "")}) - execution_ledger = build_execution_ledger(request, built, diagnostic_values, candidate_decisions) - representative = candidate_decisions[0] if candidate_decisions else None - representative_time = str(representative.get("time") or "")[:5] if representative else None - report_range = _report_candidate_range(request, rows, representative_time) - report_evidence = _report_evidence(request, built, representative_time) - summary_evidence = [ - { - "event_id": item["event_id"], - "domain": item["domain"], - "candidate_time": representative_time or "", - "rule_ids": item["methods"], - "points": 1 if item["status"] == "supporting" else -1 if item["status"] == "contradictory" else 0, - } - for item in report_evidence - ] - candidate_summary = build_candidate_result_summary({ - "winning_segment": report_range, - "event_count": len(scoring_request.get("events", [])), - "margin_percent": decision_receipt.get("margin_percent", 0), - "reasons": decision_receipt.get("reasons", []), - "evidence": summary_evidence, - }) - candidate_summary["stability"] = {"label": decision_receipt.get("overall_confidence", "low")} - rectification_report = _rectification_report( - request, built, [{ - "time": row["time"], - "score": row["score"], - } for row in rows], candidate_decisions, decision_receipt, - ) - rectification_report["next_step_codes"] = candidate_summary["next_step_codes"] - candidate_summary["report"] = rectification_report - payload = { - "result_id": result_id, - "algorithm_version": ALGORITHM_VERSION, - "event_contract_version": EVENT_CONTRACT_VERSION, - "decision_policy_version": POLICY_VERSION, - "calculation_spec": spec, - "calculation_spec_hash": spec_hash, - "candidate_scores": [{ - "time": row["time"], - "score": row["score"], - "supporting_event_ids": [item["event_id"] for item in row["evidence"] if item["points"] > 0], - "conflicting_event_ids": [item["event_id"] for item in row["evidence"] if item["points"] < 0], - } for row in rows], - "candidate_decisions": candidate_decisions, - "decision_receipt": decision_receipt, - "execution_ledger_version": EXECUTION_LEDGER_VERSION, - "execution_ledger": execution_ledger, - "candidate_feature_snapshot": build_candidate_feature_snapshot( - scoring_request, spec_hash, built.get("static_contexts") - ), - "diagnostics": diagnostic_values, - "candidate_summary": candidate_summary, - "next_step_codes": candidate_summary["next_step_codes"], - "stability": candidate_summary["stability"], - "rectification_report": rectification_report, - "robustness": { - "neighbor_support_minutes": diagnostic_values.get("neighbor_support_minutes", 0), - "leave_one_out_retention_rate": diagnostic_values.get("leave_one_event_out_retention_rate", 0), - "leave_one_domain_out_retention_rate": diagnostic_values.get("leave_one_domain_out_retention_rate", 0), - "date_sensitivity_retention_rate": diagnostic_values.get("date_sensitivity_retention_rate", 0), - }, - "missing_layers": built["missing_layers"], - "display_allowed": decision_receipt["display_allowed"], - "selection_allowed": decision_receipt["selection_allowed"], - "acceptance_allowed": decision_receipt["acceptance_allowed"], - "propose_allowed": decision_receipt["propose_allowed"], - "confirmation_allowed": decision_receipt["confirmation_allowed"], - "representative_candidate_id": representative["candidate_id"] if representative else None, - "representative_time": representative["time"] if representative else None, - "overall_confidence": decision_receipt["overall_confidence"], - "margin_percent": decision_receipt["margin_percent"], - "can_confirm_exact_minute": decision_receipt["confirmation_allowed"], - } - if include_internal: - payload["candidate_decision_receipt"] = decision_receipt - payload["event_contribution_matrix"] = built["matrix"] - return payload - - -def diagnostics( - request: RectificationRequest, - *, - enforce_candidate_cap: bool = True, -) -> dict[str, Any]: - if enforce_candidate_cap: - _reject_if_too_many_candidates(request) - scored = score_candidates(request, enforce_candidate_cap=enforce_candidate_cap) - return { - "result_id": scored["result_id"], - "algorithm_version": scored["algorithm_version"], - "event_contract_version": scored["event_contract_version"], - "decision_policy_version": scored["decision_policy_version"], - "calculation_spec_hash": scored["calculation_spec_hash"], - "candidate_decisions": scored["candidate_decisions"], - "decision_receipt": scored["decision_receipt"], - "execution_ledger_version": scored["execution_ledger_version"], - "execution_ledger": scored["execution_ledger"], - "diagnostics": scored["diagnostics"], - "candidate_summary": scored.get("candidate_summary", {"next_step_codes": ["do_not_apply_as_birth_time_truth"]}), - "next_step_codes": scored.get("next_step_codes", ["do_not_apply_as_birth_time_truth"]), - "stability": scored.get("stability", {"label": scored.get("overall_confidence", "low")}), - "rectification_report": scored.get("rectification_report", {}), - "missing_layers": scored["missing_layers"], - "display_allowed": scored["display_allowed"], - "selection_allowed": scored["selection_allowed"], - "acceptance_allowed": scored["acceptance_allowed"], - "propose_allowed": scored["propose_allowed"], - "confirmation_allowed": scored["confirmation_allowed"], - "representative_candidate_id": scored["representative_candidate_id"], - "representative_time": scored["representative_time"], - "overall_confidence": scored["overall_confidence"], - "margin_percent": scored["margin_percent"], - "can_confirm_exact_minute": scored["confirmation_allowed"], - } - - -def range_reading(request: Mapping[str, Any]) -> dict[str, Any]: - """Stable vs minute-sensitive themes for one unresolved clock window.""" - from types import SimpleNamespace - - from scripts.jyotish_engine import _build_birth_time_sensitivity - - body = dict(request or {}) - birth_date = str(body.get("birth_date") or "").strip() - if birth_date: - year_text, month_text, day_text = birth_date.split("-", 2) - year, month, day = int(year_text), int(month_text), int(day_text) - else: - year, month, day = int(body["year"]), int(body["month"]), int(body["day"]) - representative = str(body.get("representative_time") or "")[:5] - if len(representative) == 5 and representative[2] == ":": - hour, minute = int(representative[:2]), int(representative[3:]) - else: - hour = int(body.get("hour") or 12) - minute = int(body.get("minute") or 0) - representative = f"{hour:02d}:{minute:02d}" - raw_range = body.get("candidate_range") - if isinstance(raw_range, Mapping): - start_time = str(raw_range.get("start_time") or "")[:5] - end_time = str(raw_range.get("end_time") or "")[:5] - representative = str(raw_range.get("representative_time") or representative)[:5] - else: - start_time = str(body.get("start_time") or "")[:5] - end_time = str(body.get("end_time") or "")[:5] - hour, minute = int(representative[:2]), int(representative[3:]) - accuracy = str(body.get("birth_time_accuracy") or "provisional") - args = SimpleNamespace( - year=year, - month=month, - day=day, - hour=hour, - minute=minute, - second=0, - lat=float(body["lat"]), - lon=float(body["lon"]), - tz=float(body["tz"]), - ayanamsa=body.get("ayanamsa") or "raman", - node_mode=body.get("node_mode") or "mean", - birth_time_accuracy=accuracy, - candidate_range={ - "start_time": start_time, - "end_time": end_time, - "representative_time": representative, - }, - representative_time=representative, - declared_window_start=None, - declared_window_end=None, - uncertainty_before_minutes=None, - uncertainty_after_minutes=None, - ) - sensitivity = _build_birth_time_sensitivity(args) - themes = sensitivity.get("theme_sensitivity") - themes = themes if isinstance(themes, dict) else {} - stable = [ - key for key, row in themes.items() - if isinstance(row, dict) and row.get("status") == "stable" - ] - sensitive = [ - key for key, row in themes.items() - if isinstance(row, dict) and row.get("status") == "sensitive" - ] - return { - "window": sensitivity.get("window"), - "stable_themes": stable, - "sensitive_themes": sensitive, - "claim_boundary": sensitivity.get("claim_boundary"), - "theme_sensitivity": themes, - "accuracy": sensitivity.get("accuracy"), - "status": sensitivity.get("status"), - } - - -BLOCK_SCAN_PERIODS: tuple[tuple[str, str, str], ...] = ( - ("early_morning", "04:00", "07:59"), - ("morning", "08:00", "11:59"), - ("afternoon", "12:00", "17:59"), - ("evening", "18:00", "22:59"), - ("late_night", "23:00", "03:59"), -) - - -def _clock_in_declared_period(clock: str, start_time: str, end_time: str) -> bool: - current = _clock_minutes(clock[:5]) - start = _clock_minutes(start_time) - end = _clock_minutes(end_time) - if start <= end: - return start <= current <= end - return current >= start or current <= end - - -def _normalize_relative_support(raw: Sequence[float]) -> list[float]: - floored = [max(0.0, float(value)) for value in raw] - total = sum(floored) - if not floored: - return [] - if total <= 0: - shares = [round(100.0 / len(floored), 1) for _ in floored] - else: - shares = [round(100.0 * value / total, 1) for value in floored] - delta = round(100.0 - sum(shares), 1) - if shares: - shares[shares.index(max(shares))] = round(shares[shares.index(max(shares))] + delta, 1) - return shares - - -def block_scan( - request: RectificationRequest, - *, - enforce_candidate_cap: bool = True, -) -> dict[str, Any]: - """Aggregate event scores into declared periods or caller-supplied sub-blocks.""" - requested_step = request.get("minute_step") - if isinstance(requested_step, int) and requested_step > 1: - step = requested_step - else: - step = _adaptive_minute_step(request["start_time"], request["end_time"]) - if not request.get("blocks"): - step = int(request.get("minute_step") or 10) - if step <= 1: - step = 10 - scoring_request = {**request, "minute_step": step} - if enforce_candidate_cap: - _reject_if_too_many_candidates(scoring_request) - scored = score_candidates(scoring_request, enforce_candidate_cap=enforce_candidate_cap) - events_by_id = { - str(event.get("id") or ""): event - for event in request.get("events") or [] - if isinstance(event, dict) - } - rows = [ - row for row in scored.get("candidate_scores") or [] - if isinstance(row, dict) and str(row.get("time") or "")[:5] - ] - day_scores = [float(row.get("score") or 0) for row in rows] - min_day = min(day_scores) if day_scores else 0.0 - periods = _block_scan_periods(request) - raw_support: list[float] = [] - blocks: list[dict[str, Any]] = [] - for period, start_time, end_time in periods: - members = [ - row for row in rows - if _clock_in_declared_period(str(row.get("time") or "")[:5], start_time, end_time) - ] - counts: dict[str, int] = {} - for row in members: - for event_id in row.get("supporting_event_ids") or []: - key = str(event_id) - if key: - counts[key] = counts.get(key, 0) + 1 - top_events = [] - for event_id, _count in sorted(counts.items(), key=lambda item: (-item[1], item[0]))[:3]: - event = events_by_id.get(event_id) or {} - top_events.append({ - "event_id": event_id, - "domain": event.get("domain"), - "summary": event.get("summary"), - }) - member_scores = [float(row.get("score") or 0) for row in members] - mean = (sum(member_scores) / len(member_scores)) if member_scores else 0.0 - raw_support.append(max(mean - min_day, 0.0)) - from scripts.rectification.candidate_window import narrow_candidate_intervals - blocks.append({ - "candidate_intervals": narrow_candidate_intervals(request, start_time, end_time), - "period": period, - "start_time": start_time, - "end_time": end_time, - "relative_support": 0, - "top_events": top_events, - "candidate_count": len(members), - }) - shares = _normalize_relative_support(raw_support) - for block, share in zip(blocks, shares): - block["relative_support"] = share - receipt = scored.get("decision_receipt") if isinstance(scored.get("decision_receipt"), dict) else {} - return { - "result_id": scored.get("result_id"), - "algorithm_version": scored.get("algorithm_version"), - "calculation_spec": scored.get("calculation_spec"), - "calculation_spec_hash": scored.get("calculation_spec_hash"), - "minute_step": step, - "candidate_count": len(rows), - "precision_stage": {"current": "block_scan"}, - "blocks": blocks, - "discriminating_event_probes": [], - "guided_collect_windows": [], - "acceptance_allowed": False, - "selection_allowed": False, - "display_allowed": False, - "decision_receipt": { - **receipt, - "precision_stage": {"current": "block_scan"}, - "discriminating_event_probes": [], - "guided_collect_windows": [], - "acceptance_allowed": False, - "selection_allowed": False, - }, - } diff --git a/scripts/rectification/candidate_feature_service.py b/scripts/rectification/candidate_feature_service.py deleted file mode 100644 index d74001004..000000000 --- a/scripts/rectification/candidate_feature_service.py +++ /dev/null @@ -1,23 +0,0 @@ -from __future__ import annotations - -from typing import Any, Sequence - -from scripts.active_rectification_event_engine import compute_candidate_static_contexts -from scripts.rectification.contracts import RectificationRequest -from scripts.rectification.scoring_service import ALGORITHM_VERSION, sha256 - - -def build_candidate_feature_snapshot( - request: RectificationRequest, - calculation_spec_hash: str, - static_contexts: Sequence[dict[str, Any]] | None = None, -) -> dict[str, Any]: - contexts = list(static_contexts) if static_contexts is not None else compute_candidate_static_contexts(request) - features = [context["feature"] for context in contexts] - return { - "calculation_spec_hash": calculation_spec_hash, - "algorithm_version": ALGORITHM_VERSION, - "candidate_count": len(features), - "feature_hash": sha256(features), - "features": features, - } diff --git a/scripts/rectification/dasha_transition_proximity.py b/scripts/rectification/dasha_transition_proximity.py deleted file mode 100644 index 4ddd22835..000000000 --- a/scripts/rectification/dasha_transition_proximity.py +++ /dev/null @@ -1,206 +0,0 @@ -"""Deterministic dasha-transition proximity scoring for day/month events. - -Birth-time drift of about 1 minute moves Vimshottari/Narayana transition -dates by a few days. A dated event near a candidate's AD/PD change is a -bounded auxiliary signal, never larger than one day-level event body. -""" - -from __future__ import annotations - -from collections.abc import Callable, Sequence -from datetime import date, datetime -from typing import Any - -from scripts.rectification.event_probes import _narayana_start_dates, _vim_start_dates - -PROXIMITY_WINDOW_DAYS = 45 -DAY_KERNEL_DAYS = 15 -MONTH_KERNEL_DAYS = 45 -DAY_MAX_POINTS = 1.0 -MONTH_MAX_POINTS = 0.35 -VIM_SHARE = 0.6 -NARAYANA_SHARE = 0.4 - - -def representative_event_date(event: dict[str, Any]) -> date | None: - precision = str(event.get("precision") or "") - if precision not in {"day", "month"}: - return None - raw_start = event.get("date_start") or event.get("date") - raw_end = event.get("date_end") or raw_start - try: - start = date.fromisoformat(str(raw_start)[:10]) - end = date.fromisoformat(str(raw_end)[:10]) - except ValueError: - return None - if precision == "day" or start == end: - return start - mid_day = min(15, end.day) - try: - return start.replace(day=mid_day) - except ValueError: - return start - - -def _nearest_delta(starts: Sequence[date], event_date: date) -> tuple[date | None, int | None]: - eligible = [ - item for item in starts - if abs((item - event_date).days) <= PROXIMITY_WINDOW_DAYS - ] - if not eligible: - return None, None - nearest = min(eligible, key=lambda item: (abs((item - event_date).days), item.toordinal())) - return nearest, abs((nearest - event_date).days) - - -def _kernel(delta_days: int | None, width: float) -> float: - if delta_days is None or width <= 0: - return 0.0 - return max(0.0, 1.0 - (delta_days / width)) - - -def score_transition_proximity( - *, - event_date: date, - precision: str, - vim_starts: Sequence[date], - narayana_starts: Sequence[date] | None = None, - vim_pd_starts: Sequence[date] | None = None, -) -> dict[str, Any]: - if precision not in {"day", "month"}: - return { - "points": 0.0, - "rule_ids": [], - "nearest_vim_delta_days": None, - "nearest_narayana_delta_days": None, - } - kernel_width = float(DAY_KERNEL_DAYS if precision == "day" else MONTH_KERNEL_DAYS) - cap = DAY_MAX_POINTS if precision == "day" else MONTH_MAX_POINTS - ad_starts = list(vim_starts) - pd_starts = list(vim_pd_starts or ()) - ad_date, ad_delta = _nearest_delta(ad_starts, event_date) - pd_date, pd_delta = _nearest_delta(pd_starts, event_date) - if pd_delta is not None and (ad_delta is None or pd_delta < ad_delta): - vim_delta = pd_delta - vim_kind = "pd" - vim_date = pd_date - else: - vim_delta = ad_delta - vim_kind = "ad" - vim_date = ad_date - _, narayana_delta = _nearest_delta(list(narayana_starts or ()), event_date) - vim_kernel = _kernel(vim_delta, kernel_width) - narayana_kernel = _kernel(narayana_delta, kernel_width) - points = round(cap * (VIM_SHARE * vim_kernel + NARAYANA_SHARE * narayana_kernel), 4) - rules: list[str] = [] - if vim_kernel > 0: - rules.append(f"vim_transition_proximity_{vim_kind}") - if narayana_kernel > 0: - rules.append("narayana_transition_proximity_ad") - return { - "points": points, - "rule_ids": rules, - "nearest_vim_delta_days": vim_delta, - "nearest_narayana_delta_days": narayana_delta, - "nearest_vim_date": vim_date, - } - - -def _context_time(context: dict[str, Any]) -> str | None: - feature = context.get("feature") if isinstance(context.get("feature"), dict) else {} - raw = feature.get("time") - if isinstance(raw, str) and len(raw) >= 5: - return raw[:5] - at = context.get("candidate_at") - if hasattr(at, "strftime"): - return at.strftime("%H:%M") - return None - - -def merge_transition_proximity( - matrix: dict[str, dict[str, dict[str, Any]]], - events: Sequence[dict[str, Any]], - static_contexts: Sequence[dict[str, Any]], - birth_date: str, - *, - public_technique_layers: Callable[[str, Sequence[str]], list[str]], -) -> None: - by_time = { - time: context - for context in static_contexts - if isinstance(context, dict) and (time := _context_time(context)) - } - # BUG-1324: one unfiltered dasha walk per candidate, then filter by event year. - # Released when this function returns. Not a module-level cache. - vim_cache: dict[tuple[Any, ...], list[date]] = {} - pd_cache: dict[tuple[Any, ...], list[date]] = {} - narayana_cache: dict[tuple[Any, ...], list[date] | None] = {} - for event in events: - if not isinstance(event, dict): - continue - event_id = str(event.get("id") or "") - cells = matrix.get(event_id) - if not event_id or not isinstance(cells, dict): - continue - event_date = representative_event_date(event) - if event_date is None: - continue - precision = str(event.get("precision") or "") - lo, hi = event_date.year - 1, event_date.year + 1 - for time, cell in cells.items(): - context = by_time.get(str(time)[:5]) - if not isinstance(cell, dict) or not isinstance(context, dict): - continue - moon = (context.get("planet_longitudes") or {}).get("Moon") - if not isinstance(moon, (int, float)): - continue - # Native contexts retain the local date even when the window crosses midnight. - # Legacy time-only contexts still use the request's date. - candidate_at = context.get("candidate_at") - candidate_date = candidate_at.date().isoformat() if isinstance(candidate_at, datetime) else birth_date - moon_key = round(float(moon), 6) - vim_key = (candidate_date, moon_key) - if vim_key not in vim_cache: - vim_cache[vim_key] = _vim_start_dates(candidate_date, float(moon), 1, 9999) - pd_cache[vim_key] = _vim_start_dates( - candidate_date, - float(moon), - 1, - 9999, - include_pratyantar=True, - ) - planets = context.get("planet_longitudes") or {} - asc = context.get("ascendant_index") - narayana_key = ( - candidate_date, - int(asc) if isinstance(asc, int) else None, - moon_key, - ) - if narayana_key not in narayana_cache: - narayana_cache[narayana_key] = ( - _narayana_start_dates(int(asc), planets, candidate_date, 1, 9999) - if isinstance(asc, int) and isinstance(planets, dict) - else None - ) - ad_starts = [item for item in vim_cache[vim_key] if lo <= item.year <= hi] - ad_set = set(ad_starts) - pd_only = [item for item in pd_cache[vim_key] if lo <= item.year <= hi and item not in ad_set] - narayana_starts = narayana_cache[narayana_key] - if narayana_starts is not None: - narayana_starts = [item for item in narayana_starts if lo <= item.year <= hi] - scored = score_transition_proximity( - event_date=event_date, - precision=precision, - vim_starts=ad_starts, - vim_pd_starts=pd_only, - narayana_starts=narayana_starts or [], - ) - if scored["points"] <= 0 and not scored["rule_ids"]: - continue - cell["points"] = round(float(cell.get("points") or 0) + float(scored["points"]), 4) - cell["rule_ids"] = sorted({ - *list(cell.get("rule_ids") or []), - *scored["rule_ids"], - }) - domain = str(event.get("domain") or cell.get("domain") or "") - cell["technique_layers"] = public_technique_layers(domain, cell["rule_ids"]) diff --git a/scripts/rectification/decision_policy.py b/scripts/rectification/decision_policy.py deleted file mode 100644 index 102ac00ef..000000000 --- a/scripts/rectification/decision_policy.py +++ /dev/null @@ -1,850 +0,0 @@ -from __future__ import annotations - -from collections.abc import Sequence -from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal -from typing import Any -from uuid import NAMESPACE_URL, uuid5 - -from scripts.active_rectification_events import CandidateScoreRow -from scripts.rectification.contracts import ( - EVENT_CONTRACT_VERSION, - RectificationRequest, - is_primary_scoreable_event, - is_scoreable_event, -) -from scripts.rectification.house_table import compact_house_table_from_contexts -from scripts.rectification.horary_observation import build_horary_observation -from scripts.rectification.refinement_packet import build_refinement_packet -from scripts.rectification.candidate_contrast import context_time, select_signature_representatives -from scripts.rectification.case_holdout import holdout_event_ids -from scripts.rectification.scoring_service import precision_weight -from scripts.rectification.sealed_holdout import holdout_passed, load_sealed_minute_holdout -from scripts.rectification_policy import ( - MAX_CONFIRMATION_WIDTH_MINUTES, - MIN_CONFIRMATION_DOMAINS, - MIN_CONFIRMATION_EVENTS, - MIN_CONFIRMATION_MARGIN_PERCENT, -) - -POLICY_VERSION = "rectification-candidate-policy-v4" -RECEIPT_VERSION = "candidate-decision-receipt-v2" -EXECUTION_LEDGER_VERSION = "rectification-execution-ledger-v2" -SCORE_QUANTUM = Decimal("0.0001") -TIE_ABSOLUTE_TOLERANCE = Decimal("0.0001") -# R1 (2026-10-02, BUG-1193): a range is accepted only with at least 4 dated -# scoreable events across 3 domains, counted on all of them (training + the -# reserved holdout). Single definition: references/rectification_policy.v1.json. -MIN_ACCEPTANCE_EVENTS = MIN_CONFIRMATION_EVENTS -MIN_ACCEPTANCE_DOMAINS = MIN_CONFIRMATION_DOMAINS -MIN_DATE_QUALITY_MEAN = Decimal("0.65") -MIN_DIAGNOSTIC_RETENTION = Decimal("0.75") -MIN_ACCEPTANCE_MARGIN_PERCENT = Decimal("10") -POLICY_SKIPPED_LAYERS = frozenset({"KP_cusps"}) - -_BAD_DATE_RELIABILITY = frozenset({"low", "uncertain", "unreliable"}) -_CLEAR_DATE_CONFLICT = frozenset({"", "none", "resolved", "no_conflict"}) - - -def _decimal(value: Any, default: str = "0") -> Decimal: - if isinstance(value, bool): - return Decimal(default) - try: - return Decimal(str(value)) - except Exception: - return Decimal(default) - - -def _column_times_for_packet( - request: RectificationRequest, - candidate_decisions: Sequence[dict[str, Any]], -) -> list[str]: - decision_times = [ - str(item.get("time") or "")[:5] - for item in candidate_decisions - if str(item.get("time") or "")[:5] - ] - requested = request.get("column_times") - if not isinstance(requested, list) or not requested: - return decision_times - wanted = {str(item)[:5] for item in requested if isinstance(item, str)} - subset = [time for time in decision_times if time in wanted] - return subset or decision_times - - -_AUDIT_LABELS = { - "d1-rashi": ("D1 本命盘", "本轮已按该分钟重算本命宫位。"), - "d2-hora": ("D2 财帛分盘", "本轮已对照财帛主题。"), - "d4-chaturthamsha": ("D4 迁移分盘", "本轮已对照居所或迁移。"), - "d5-panchamsha": ("D5 成就分盘", "本轮已对照学业或被委以责任的变化。"), - "d3-drekkana": ("D3 兄弟分盘", "本轮已对照兄弟姐妹主题。"), - "d7-saptamsha": ("D7 子女分盘", "本轮已对照子女或伴侣细节。"), - "d9-navamsa": ("D9 婚姻分盘", "本轮已对照关系主题,可用 D9 上升类型表作校时方法,不是命运承诺。"), - "d10-dashamsa": ("D10 事业分盘", "本轮已对照事业主题,可用 D10 上升类型表作校时方法,不是命运承诺。"), - "d11-labhamsha": ("D11 收益分盘", "本轮已对照收益主题。"), - "d12-dwadashamsha": ("D12 父母分盘", "本轮已对照家人主题。"), - "d24-chaturvimshamsha": ("D24 教育分盘", "本轮已对照学业主题。"), - "d30-trimshamsha": ("D30 健康压力分盘", "本轮已对照健康压力主题。"), - "vimshottari-dasha": ("Vimshottari", "本轮已对照主限。"), - "narayana-dasha": ("Narayana", "本轮已对照分盘大运。"), - "gochara": ("Gochara", "本轮已做受控行运辅助对照。"), - "ashtakavarga": ("Ashtakavarga", "本轮已做 Ashtakavarga 辅助对照。"), - "shadbala": ("Shadbala", "本轮已做已核验的 Shadbala 分量辅助对照。"), - "arudha-pada": ("Arudha Pada", "本轮已做 Arudha 辅助对照。"), - "functional-benefic-malefic": ("功能吉凶星", "本轮已叠加本命功能吉凶星。"), - "dasha-transition-proximity": ("换运贴近度", "本轮已对照日级事件与候选换运日期的贴近程度。"), -} - - -def natal_recast_copy(time: str, lagna: str) -> dict[str, Any]: - return { - "time": time[:5], - "lagna": lagna, - "user_meaning": ( - f"本命宫位已按 {time[:5]} 重算(上升 {lagna})。" - "下面是本轮实际执行的技法,不能当作唯一分钟确认。" - ), - "unique_minute_claim": False, - "confirmation_allowed": False, - } - - -def _executed_public_methods(built: dict[str, Any]) -> list[str]: - methods: set[str] = set() - for contributions in (built.get("matrix") or {}).values(): - if not isinstance(contributions, dict): - continue - for cell in contributions.values(): - if not isinstance(cell, dict): - continue - for layer in cell.get("technique_layers") or []: - if layer in _AUDIT_LABELS: - methods.add(str(layer)) - for rule in cell.get("rule_ids") or []: - text = str(rule) - if "transition_proximity" in text: - methods.add("dasha-transition-proximity") - elif text.startswith("vim_"): - methods.add("vimshottari-dasha") - elif text.startswith("narayana_"): - methods.add("narayana-dasha") - elif "functional_benefic" in text or "functional_malefic" in text: - methods.add("functional-benefic-malefic") - elif text.startswith("gochara") or "controlled_transit" in text: - methods.add("gochara") - elif "ashtakavarga" in text: - methods.add("ashtakavarga") - elif "shadbala" in text: - methods.add("shadbala") - elif "arudha" in text: - methods.add("arudha-pada") - return [key for key in _AUDIT_LABELS if key in methods] - - -def _clock_minutes(value: Any) -> int | None: - text = str(value or "")[:5] - if len(text) != 5 or text[2] != ":": - return None - try: - hour = int(text[:2]) - minute = int(text[3:]) - except ValueError: - return None - if hour > 23 or minute > 59: - return None - return hour * 60 + minute - - -def indistinguishable_width_minutes(candidates: Sequence[dict[str, Any]]) -> int: - if not candidates: - return 0 - ranked = sorted(candidates, key=lambda row: int(row.get("rank") or 0)) - top = ranked[0] - if all(row.get("cluster_intervals") for row in ranked): - from scripts.rectification.candidate_window import interval_union_width - return max(int(top.get("tied_minute_count") or 1), interval_union_width([ - interval for row in ranked for interval in row["cluster_intervals"] - ]), 1) - starts: list[int] = [] - ends: list[int] = [] - for row in ranked: - start = _clock_minutes(row.get("cluster_start") or row.get("time")) - end = _clock_minutes(row.get("cluster_end") or row.get("time")) - if start is not None: - starts.append(start) - if end is not None: - ends.append(end) - span = (max(ends) - min(starts) + 1) if starts and ends else 0 - tied = int(top.get("tied_minute_count") or 1) - return max(tied, span, 1) - - -def vedastro_audit_row(status: str) -> dict[str, str]: - if status == "passed": - return { - "technique": "VedAstro 分钟级校验", - "status": "executed", - "note": "官方分钟敏感校验已通过。仍不能单独确认唯一分钟。", - } - if status == "failed": - return { - "technique": "VedAstro 分钟级校验", - "status": "blocked", - "note": "官方分钟敏感校验未能区分相邻分钟,不能写确认。", - } - return { - "technique": "VedAstro 分钟级校验", - "status": "blocked", - "note": "官方分钟敏感校验尚未跑通。未调用不等于失败,但缺这一层不能写确认。", - } - - -def unique_minute_audit_row(allowed: bool) -> dict[str, str]: - if allowed: - return { - "technique": "唯一分钟确认", - "status": "executed", - "note": "确认门已允许。只有用户明确同意才能写已确认校正时间。", - } - return { - "technique": "唯一分钟确认", - "status": "blocked", - "note": "本会话以代表性时间收口,不确认唯一分钟。", - } - - -def rewrite_confirmation_audit_rows(receipt: dict[str, Any]) -> None: - rows = receipt.get("technique_audit_table") - if not isinstance(rows, list): - return - exact = (receipt.get("gates") or {}).get("exact_confirmation") or {} - vedastro_status = str(exact.get("external_validation_status") or "not_evaluated") - allowed = receipt.get("confirmation_allowed") is True - replacements = { - "VedAstro 分钟级校验": vedastro_audit_row(vedastro_status), - "唯一分钟确认": unique_minute_audit_row(allowed), - } - receipt["technique_audit_table"] = [ - replacements.get(str(row.get("technique")), row) if isinstance(row, dict) else row - for row in rows - ] - - -def apply_confirmation_decision(receipt: dict[str, Any]) -> dict[str, Any]: - gates = receipt.setdefault("gates", {}) - exact = gates.setdefault("exact_confirmation", {}) - vedastro_status = str(exact.get("external_validation_status") or "not_evaluated") - if vedastro_status not in {"passed", "failed", "not_evaluated"}: - vedastro_status = "not_evaluated" - exact["external_validation_status"] = vedastro_status - holdout = load_sealed_minute_holdout() - engine_granted = exact.get("engine_granted") is True - adjacent_passed = exact.get("adjacent_passed") is True - vedastro_ok = vedastro_status == "passed" - holdout_ok = holdout_passed(holdout) - confirmation_allowed = bool(engine_granted and adjacent_passed and vedastro_ok and holdout_ok) - reasons = [str(item) for item in (receipt.get("confirmation_reasons") or []) if str(item)] - for flag, reason in ( - (engine_granted, "engine_exact_confirmation_not_granted"), - (vedastro_ok, "external_validation_not_passed"), - (adjacent_passed, "adjacent_minutes_indistinguishable"), - (holdout_ok, "public_aa_holdout_not_ready"), - ): - if flag: - reasons = [item for item in reasons if item != reason] - elif reason not in reasons: - reasons.append(reason) - receipt["confirmation_allowed"] = confirmation_allowed - receipt["confirm_allowed"] = confirmation_allowed - receipt["unique_minute_claim"] = False - exact["unique_minute_path"] = ( - "awaiting_user_consent" if confirmation_allowed else "closed_at_representative" - ) - exact["passed"] = confirmation_allowed - exact["fail_closed"] = True - exact["external_validation_status"] = vedastro_status - exact["holdout"] = holdout - exact["reason"] = ( - "confirmation_allowed" - if confirmation_allowed - else "engine_and_external_validation_must_explicitly_pass" - ) - receipt["confirmation_reasons"] = reasons - receipt["reasons"] = [ - *list(receipt.get("acceptance_reasons") or []), - *reasons, - ] - natal = receipt.get("natal_recast") - if isinstance(natal, dict): - natal["confirmation_allowed"] = False - natal["unique_minute_claim"] = False - rewrite_confirmation_audit_rows(receipt) - return receipt - - -def apply_vedastro_minute_sensitive_to_receipt( - receipt: dict[str, Any], - status: str, - *, - summary: dict[str, Any] | None = None, -) -> dict[str, Any]: - exact = receipt.setdefault("gates", {}).setdefault("exact_confirmation", {}) - normalized = status if status in {"passed", "failed", "not_evaluated"} else "not_evaluated" - exact["external_validation_status"] = normalized - if summary is not None: - exact["vedastro_minute_sensitive"] = summary - return apply_confirmation_decision(receipt) - - -def build_technique_audit( - built: dict[str, Any], - *, - house_table: dict[str, Any] | None, - vedastro_status: str = "not_evaluated", - confirmation_allowed: bool = False, -) -> list[dict[str, str]]: - executed = set(_executed_public_methods(built)) - if house_table: - executed.add("d1-rashi") - rows: list[dict[str, str]] = [] - for method in _AUDIT_LABELS: - if method not in executed: - continue - label, note = _AUDIT_LABELS[method] - rows.append({"technique": label, "status": "executed", "note": note}) - rows.append(_kp_audit_row(built)) - rows.extend(( - vedastro_audit_row(vedastro_status), - unique_minute_audit_row(confirmation_allowed), - )) - return rows - - -def _kp_audit_row(built: dict[str, Any]) -> dict[str, str]: - executed = False - for context in built.get("static_contexts") or []: - if not isinstance(context, dict): - continue - feature = context.get("feature") - snapshot = feature.get("kp_cusps") if isinstance(feature, dict) else None - if isinstance(snapshot, dict) and snapshot.get("status") == "executed": - executed = True - break - if executed: - return { - "technique": "KP 宫头", - "status": "executed", - "note": "已按 Swiss Ephemeris Placidus + Krishnamurti 观察 12 宫头;不计分,不参与提出门或确认门。", - } - return { - "technique": "KP 宫头", - "status": "blocked", - "note": "Swiss Ephemeris Placidus 宫头无法计算或尚未执行。KP 观察不计分,不挡提出门。", - } - - -def _quantized_score(row: CandidateScoreRow) -> Decimal: - return _decimal(row.get("score")).quantize(SCORE_QUANTUM, rounding=ROUND_HALF_UP) - - -def _distribute_percent(weights: Sequence[Decimal]) -> list[int]: - if not weights: - return [] - total = sum(weights, Decimal(0)) - if total == 0: - base, remainder = divmod(100, len(weights)) - return [base + (1 if index < remainder else 0) for index in range(len(weights))] - exact = [weight * Decimal(100) / total for weight in weights] - floors = [int(value.to_integral_value(rounding=ROUND_FLOOR)) for value in exact] - remaining = 100 - sum(floors) - order = sorted( - range(len(weights)), - key=lambda index: (-(exact[index] - Decimal(floors[index])), index), - ) - for index in order[:remaining]: - floors[index] += 1 - return floors - - -def _relative_support_proportional(scores: Sequence[Decimal]) -> list[int]: - return _distribute_percent([max(score, Decimal(0)) for score in scores]) - - -def _relative_support_offset(scores: Sequence[Decimal], floor: Decimal) -> list[int]: - return _distribute_percent([max(score - floor, Decimal(0)) for score in scores]) - - -def _relative_support_softmax(scores: Sequence[Decimal], temperature: Decimal) -> list[int]: - from math import exp - if not scores: - return [] - peak = max(scores) - temp = temperature if temperature > 0 else Decimal("0.5") - weights = [Decimal(str(exp(float((score - peak) / temp)))) for score in scores] - return _distribute_percent(weights) - - -RELATIVE_SUPPORT_MODE = "proportional" -RELATIVE_SUPPORT_TEMPERATURE = Decimal("0.5") - - -def _relative_support( - scores: Sequence[Decimal], - *, - floor: Decimal | None = None, - mode: str | None = None, - temperature: Decimal | None = None, -) -> list[int]: - if not scores: - return [] - selected = mode or RELATIVE_SUPPORT_MODE - if selected == "softmax": - return _relative_support_softmax( - scores, - temperature if temperature is not None else RELATIVE_SUPPORT_TEMPERATURE, - ) - if selected == "offset" and floor is not None: - return _relative_support_offset(scores, floor) - return _relative_support_proportional(scores) - - -def build_candidate_decisions( - rows: Sequence[CandidateScoreRow], - *, - result_id: str, - static_contexts: Sequence[dict[str, Any]] | None = None, - support_mode: str | None = None, - temperature: Decimal | None = None, -) -> list[dict[str, Any]]: - ranked = sorted(rows, key=lambda row: (-_quantized_score(row), row["time"])) - public_rows = select_signature_representatives(ranked, static_contexts) - if not public_rows: - return [] - public_scores = [_quantized_score(row) for row in public_rows] - all_scores = [_quantized_score(row) for row in ranked] - floor = min(all_scores) if all_scores else Decimal(0) - supports = _relative_support( - public_scores, - floor=floor, - mode=support_mode, - temperature=temperature, - ) - decisions = [] - for index, row in enumerate(public_rows): - score = _quantized_score(row) - tied_minute_count = sum( - abs(score - other) <= TIE_ABSOLUTE_TOLERANCE - for other in all_scores - ) - cluster_times, cluster_start, cluster_end = _cluster_span(row) - from scripts.rectification.candidate_window import intervals_from_positions - position = {key: row[key] for key in ("candidate_date", "window_index", "window_offset_minutes", "segment_index") if key in row} - coverage = intervals_from_positions(row.get("cluster_positions", [])) - decisions.append({ - **position, - **({"cluster_intervals": coverage} if coverage else {}), - "candidate_id": str(uuid5(NAMESPACE_URL, f"{POLICY_VERSION}:{result_id}:{row['time']}")), - "rank": index + 1, - "time": row["time"], - "relative_support": supports[index], - "tied_minute_count": tied_minute_count, - "cluster_times": cluster_times, - "cluster_start": cluster_start, - "cluster_end": cluster_end, - }) - return decisions - - -def _cluster_span(row: dict[str, Any]) -> tuple[list[str], str, str]: - raw = row.get("cluster_times") - times: list[str] = [] - seen: set[str] = set() - values = raw if isinstance(raw, list) and raw else [row.get("time")] - for item in values: - text = str(item or "")[:5] - if len(text) != 5 or text[2] != ":" or text in seen: - continue - seen.add(text) - times.append(text) - if not times: - clock = str(row.get("time") or "")[:5] - times = [clock] if len(clock) == 5 and clock[2] == ":" else [] - positions = {item["time"]: item["window_index"] for item in row.get("cluster_positions", [])} - times.sort(key=lambda value: positions.get(value, int(value[:2]) * 60 + int(value[3:5]))) - start = times[0] if times else str(row.get("time") or "")[:5] - end = times[-1] if times else start - return times, start, end - - -def _gate(passed: bool, **details: Any) -> dict[str, Any]: - return {"passed": passed, **details} - - -def _actionable_missing_layers(layers: Any) -> list[str]: - return sorted({ - str(layer) - for layer in (layers or []) - if str(layer) not in POLICY_SKIPPED_LAYERS - }) - - -def _date_quality(events: Sequence[dict[str, Any]]) -> dict[str, Any]: - weights = [_decimal(precision_weight(str(event["precision"]))) for event in events] - total = sum(weights, Decimal(0)) - mean = total / Decimal(len(weights)) if weights else Decimal(0) - low_reliability = sorted( - event["id"] - for event in events - if str(event.get("date_reliability") or "").strip().lower() in _BAD_DATE_RELIABILITY - ) - unresolved_conflicts = sorted( - event["id"] - for event in events - if str(event.get("date_conflict_status") or "").strip().lower() not in _CLEAR_DATE_CONFLICT - ) - passed = bool(events) and mean >= MIN_DATE_QUALITY_MEAN and not low_reliability and not unresolved_conflicts - return _gate( - passed, - precision_weight_total=float(total), - precision_weight_mean=float(mean.quantize(SCORE_QUANTUM, rounding=ROUND_HALF_UP)), - minimum_precision_weight_mean=float(MIN_DATE_QUALITY_MEAN), - low_reliability_event_ids=low_reliability, - unresolved_conflict_event_ids=unresolved_conflicts, - ) - - -def _diagnostic_quality(diagnostics: dict[str, Any]) -> dict[str, Any]: - retention_names = ( - "leave_one_event_out_retention_rate", - "leave_one_domain_out_retention_rate", - "date_sensitivity_retention_rate", - ) - retentions = {name: _decimal(diagnostics.get(name)) for name in retention_names} - margin = _decimal(diagnostics.get("primary_secondary_margin_percent")) - passed = ( - all(value >= MIN_DIAGNOSTIC_RETENTION for value in retentions.values()) - and margin >= MIN_ACCEPTANCE_MARGIN_PERCENT - ) - return _gate( - passed, - minimum_retention=float(MIN_DIAGNOSTIC_RETENTION), - minimum_margin_percent=float(MIN_ACCEPTANCE_MARGIN_PERCENT), - margin_percent=float(margin), - **{name: float(value) for name, value in retentions.items()}, - ) - - -def build_decision_receipt( - request: RectificationRequest, - candidate_decisions: Sequence[dict[str, Any]], - built: dict[str, Any], - diagnostics: dict[str, Any], -) -> dict[str, Any]: - scoreable_events = [event for event in request["events"] if is_primary_scoreable_event(event)] - holdout = holdout_event_ids(request["events"]) - training_events = [ - event for event in scoreable_events - if str(event.get("id") or "") not in holdout - ] - domains = sorted({event["domain"] for event in training_events}) - scoreable_domains = sorted({event["domain"] for event in scoreable_events}) - candidate_presence = _gate(bool(candidate_decisions), candidate_count=len(candidate_decisions)) - event_quality = _gate( - len(scoreable_events) >= MIN_ACCEPTANCE_EVENTS, - scoreable_event_count=len(scoreable_events), - training_event_count=len(training_events), - minimum=MIN_ACCEPTANCE_EVENTS, - ) - domain_diversity = _gate( - len(scoreable_domains) >= MIN_ACCEPTANCE_DOMAINS, - scoreable_domain_count=len(scoreable_domains), - minimum=MIN_ACCEPTANCE_DOMAINS, - domains=scoreable_domains, - ) - date_quality = _date_quality(training_events) - top_tied_count = candidate_decisions[0]["tied_minute_count"] if candidate_decisions else 0 - unique_top = _gate(top_tied_count == 1, tied_minute_count=top_tied_count) - diagnostic_quality = _diagnostic_quality(diagnostics) - skipped_layers = sorted( - str(layer) - for layer in (built.get("missing_layers") or []) - if str(layer) in POLICY_SKIPPED_LAYERS - ) - actionable_missing_layers = _actionable_missing_layers(built.get("missing_layers")) - required_layers = _gate( - not actionable_missing_layers, - missing_layers=actionable_missing_layers, - skipped_by_policy=skipped_layers, - ) - - # Adoption is the session result when a representative time exists. - # Unique-top and diagnostic stability still block confirmation, not accept. - acceptance_allowed = all(( - candidate_presence["passed"], - event_quality["passed"], - domain_diversity["passed"], - date_quality["passed"], - )) - margin = _decimal(diagnostics.get("primary_secondary_margin_percent")) - if acceptance_allowed and margin >= Decimal("20"): - overall_confidence = "high" - elif acceptance_allowed: - overall_confidence = "medium" - else: - overall_confidence = "low" - - acceptance_reasons: list[str] = [] - for passed, reason in ( - (candidate_presence["passed"], "no_candidates"), - (event_quality["passed"], "insufficient_events"), - (domain_diversity["passed"], "insufficient_domain_diversity"), - (date_quality["passed"], "low_date_quality"), - ): - if not passed: - acceptance_reasons.append(reason) - confirmation_reasons = [] - if not unique_top["passed"]: - confirmation_reasons.append("tied_top_score") - if not diagnostic_quality["passed"]: - confirmation_reasons.append("insufficient_diagnostic_stability") - if not required_layers["passed"]: - confirmation_reasons.append("missing_mandatory_layers") - reasons = [*acceptance_reasons, *confirmation_reasons] - - representative = candidate_decisions[0] if candidate_decisions else None - width = indistinguishable_width_minutes(candidate_decisions) - grid_times = [str(item)[:5] for item in (built.get("candidate_times") or []) if str(item or "")[:5]] - if not grid_times: - for context in built.get("static_contexts") or []: - if not isinstance(context, dict): - continue - time = context_time(context) - if time and time not in grid_times: - grid_times.append(time) - if not grid_times: - grid_times = [item["time"] for item in candidate_decisions] - packet = build_refinement_packet( - request, - built, - representative_time=representative["time"] if representative else None, - candidate_times=grid_times, - cluster_width_minutes=width, - include_discriminators=int(request.get("minute_step") or 1) <= 1, - column_times=_column_times_for_packet(request, candidate_decisions), - clusters=candidate_decisions, - ) - if packet["dasha_agreement"]["status"] == "conflict": - if overall_confidence == "high": - overall_confidence = "medium" - elif overall_confidence == "medium": - overall_confidence = "low" - reasons.append("vimshottari_narayana_conflict") - confirmation_reasons.append("vimshottari_narayana_conflict") - adjacent_passed = unique_top["passed"] and width <= MAX_CONFIRMATION_WIDTH_MINUTES - confirmation_event_quality = len(scoreable_events) >= MIN_CONFIRMATION_EVENTS - confirmation_domain_quality = len(domains) >= MIN_CONFIRMATION_DOMAINS - confirmation_margin = margin >= Decimal(MIN_CONFIRMATION_MARGIN_PERCENT) - dasha_conflict = packet["dasha_agreement"]["status"] == "conflict" - if not confirmation_event_quality: - confirmation_reasons.append("insufficient_confirmation_events") - if not confirmation_domain_quality: - confirmation_reasons.append("insufficient_confirmation_domains") - if not confirmation_margin: - confirmation_reasons.append("insufficient_confirmation_margin") - if not adjacent_passed: - confirmation_reasons.append("adjacent_minutes_indistinguishable") - fit_high = packet["event_fit_rate"].get("band") == "high" - propose_allowed = bool( - acceptance_allowed - and required_layers["passed"] - and ( - fit_high - or all(( - diagnostic_quality["passed"], - confirmation_event_quality, - confirmation_domain_quality, - )) - ) - ) - engine_granted = all(( - propose_allowed, - unique_top["passed"], - adjacent_passed, - confirmation_margin, - not dasha_conflict, - )) - if not engine_granted: - confirmation_reasons.append("engine_exact_confirmation_not_granted") - exact_confirmation = { - "passed": False, - "fail_closed": True, - "engine_granted": engine_granted, - "adjacent_passed": adjacent_passed, - "indistinguishable_width_minutes": width, - "max_confirmation_width_minutes": MAX_CONFIRMATION_WIDTH_MINUTES, - "external_validation_status": "not_evaluated", - "unique_minute_path": "closed_at_representative", - "required_scoreable_events": MIN_CONFIRMATION_EVENTS, - "required_scoreable_domains": MIN_CONFIRMATION_DOMAINS, - "reason": "engine_and_external_validation_must_explicitly_pass", - } - receipt = { - "receipt_version": RECEIPT_VERSION, - "contract_version": "v2", - "event_contract_version": EVENT_CONTRACT_VERSION, - "policy_version": POLICY_VERSION, - "decision_policy_version": POLICY_VERSION, - "display_allowed": bool(candidate_decisions), - "selection_allowed": acceptance_allowed, - "acceptance_allowed": acceptance_allowed, - "propose_allowed": propose_allowed, - "confirmation_allowed": False, - "accept_allowed": acceptance_allowed, - "confirm_allowed": False, - "representative_candidate_id": representative["candidate_id"] if representative else None, - "representative_time": representative["time"] if representative else None, - "overall_confidence": overall_confidence, - "margin_percent": float(margin), - "reasons": reasons, - "acceptance_reasons": acceptance_reasons, - "confirmation_reasons": confirmation_reasons, - "tie_policy": { - "score_quantum": float(SCORE_QUANTUM), - "absolute_tolerance": float(TIE_ABSOLUTE_TOLERANCE), - "rounding": "ROUND_HALF_UP", - }, - "gates": { - "candidate_presence": candidate_presence, - "event_quality": event_quality, - "domain_diversity": domain_diversity, - "date_quality": date_quality, - "unique_top": unique_top, - "diagnostic_quality": diagnostic_quality, - "required_layers": required_layers, - "exact_confirmation": exact_confirmation, - }, - } - house_tables_by_time: dict[str, dict[str, Any]] = {} - house_times: list[str] = [] - seen_house_times: set[str] = set() - for context in built.get("static_contexts") or []: - if not isinstance(context, dict): - continue - time = context_time(context) - if time and time not in seen_house_times: - seen_house_times.add(time) - house_times.append(time) - for decision in candidate_decisions: - time = str(decision.get("time") or "")[:5] - if time and time not in seen_house_times: - seen_house_times.add(time) - house_times.append(time) - for time in house_times: - table = compact_house_table_from_contexts(built.get("static_contexts"), time) - if table: - house_tables_by_time[table["time"]] = table - house_table = house_tables_by_time.get(representative["time"] if representative else "") or compact_house_table_from_contexts( - built.get("static_contexts"), - representative["time"] if representative else None, - ) - if house_table: - receipt["house_table"] = house_table - recast = natal_recast_copy(house_table["time"], house_table["lagna"]) - receipt["natal_recast"] = recast - if house_tables_by_time: - receipt["house_tables_by_time"] = house_tables_by_time - receipt["technique_audit_table"] = build_technique_audit( - built, - house_table=house_table, - vedastro_status="not_evaluated", - confirmation_allowed=False, - ) - receipt.update({ - "window_scan": packet["window_scan"], - "event_dasha_ledger": packet["event_dasha_ledger"], - "event_dasha_ledger_by_time": packet.get("event_dasha_ledger_by_time") or {}, - "prospective_windows_by_time": packet.get("prospective_windows_by_time") or {}, - "column_compare_ms": packet.get("column_compare_ms"), - "event_fit_rate": packet["event_fit_rate"], - "dasha_agreement": packet["dasha_agreement"], - "lagna_contrast": packet["lagna_contrast"], - "nakshatra_boundary": packet["nakshatra_boundary"], - "precision_stage": packet["precision_stage"], - "oos_blind_prompts": packet["oos_blind_prompts"], - "discriminating_event_probes": packet.get("discriminating_event_probes") or [], - "guided_collect_windows": packet.get("guided_collect_windows") or [], - "event_clarification_probes": packet.get("event_clarification_probes") or [], - "evidence_collection_probes": packet.get("evidence_collection_probes") or [], - "candidate_contrast_opportunities": packet.get("candidate_contrast_opportunities") or [], - "holdout_validation_probes": packet.get("holdout_validation_probes") or [], - "dropped_probes": packet.get("dropped_probes") or [], - "dropped_asked_probe_keys": int(request.get("dropped_asked_probe_keys") or 0), - "prospective_probes": packet.get("prospective_probes") or [], - "horary_observation": build_horary_observation(request), - "unique_minute_claim": False, - }) - return apply_confirmation_decision(receipt) - - -def build_execution_ledger( - request: RectificationRequest, - built: dict[str, Any], - diagnostics: dict[str, Any], - candidate_decisions: Sequence[dict[str, Any]], -) -> list[dict[str, Any]]: - matrix = built.get("matrix") or {} - date_sensitivity = { - item.get("event_id"): item - for item in built.get("date_sensitivity") or [] - if isinstance(item, dict) - } - entries: list[dict[str, Any]] = [] - all_layers: set[str] = set() - for event in request["events"]: - candidates = matrix.get(event["id"], {}) - layers = sorted({ - layer - for contribution in candidates.values() - for layer in contribution.get("technique_layers", []) - }) - all_layers.update(layers) - sensitivity = date_sensitivity.get(event["id"], {}) - scoreable = is_scoreable_event(event) - entries.append({ - "ledger_version": EXECUTION_LEDGER_VERSION, - "stage": "event_scoring", - "status": "executed" if scoreable and candidates else "not_executed" if scoreable else "retained_not_scored", - "source": "python-engine", - "event_id": event["id"], - "domain": event["domain"], - "event_kind": event["event_kind"], - "date_precision": event["precision"], - "precision_weight": precision_weight(event["precision"]), - "sampled_date_count": len(sensitivity.get("sample_dates") or []), - "candidate_count": len(candidates), - "technique_layers": layers, - }) - for layer in sorted(all_layers): - entries.append({ - "ledger_version": EXECUTION_LEDGER_VERSION, - "stage": "technique_layer", - "method": layer, - "status": "executed", - "source": "python-engine", - }) - entries.extend(( - { - "ledger_version": EXECUTION_LEDGER_VERSION, - "stage": "candidate_ranking", - "status": "executed" if candidate_decisions else "not_executed", - "source": "python-decision-policy", - "candidate_count": len(candidate_decisions), - }, - { - "ledger_version": EXECUTION_LEDGER_VERSION, - "stage": "diagnostics", - "status": "executed" if diagnostics else "not_executed", - "source": "python-engine", - "metrics": sorted(diagnostics), - }, - )) - return entries diff --git a/scripts/rectification/diagnostics_service.py b/scripts/rectification/diagnostics_service.py deleted file mode 100644 index 50c3672fb..000000000 --- a/scripts/rectification/diagnostics_service.py +++ /dev/null @@ -1,142 +0,0 @@ -from __future__ import annotations - -from collections import defaultdict -from statistics import variance -from typing import Any, Sequence - -from scripts.active_rectification_events import CandidateScoreRow -from scripts.rectification.contracts import RectificationRequest -from scripts.rectification.refinement_packet import window_scan - - -def _winner(rows: Sequence[CandidateScoreRow]) -> str | None: - return max(rows, key=lambda row: row["score"])["time"] if rows else None - - -def _minute_value(value: str) -> int: - return int(value[:2]) * 60 + int(value[3:]) - - -def _primary_cluster(rows: Sequence[CandidateScoreRow], relative_floor: float = .97) -> list[str]: - if not rows: - return [] - peak = max(row["score"] for row in rows) - floor = peak * relative_floor if peak >= 0 else peak / relative_floor - selected = sorted((row["time"] for row in rows if row["score"] >= floor), key=_minute_value) - if not selected: - return [] - groups: list[list[str]] = [] - for current in selected: - if groups and (_minute_value(current) - _minute_value(groups[-1][-1])) % 1_440 == 1: - groups[-1].append(current) - else: - groups.append([current]) - if len(groups) > 1 and (_minute_value(groups[0][0]) - _minute_value(groups[-1][-1])) % 1_440 == 1: - groups[0] = [*groups.pop(), *groups[0]] - scores = {row["time"]: row["score"] for row in rows} - return max(groups, key=lambda group: (max(scores[time] for time in group), sum(max(scores[time], 0) for time in group))) - - -def _subtract(rows: Sequence[CandidateScoreRow], removed_ids: set[str]) -> list[CandidateScoreRow]: - return [{**row, "score": round(row["score"] - sum(item["points"] for item in row["evidence"] if item["event_id"] in removed_ids), 4)} for row in rows] - - -def _candidate_feature_contrast(built: dict[str, Any], primary_time: str, secondary_time: str) -> list[str]: - features = { - value["time"]: value - for context in built.get("static_contexts") or [] - if isinstance((value := context.get("feature")), dict) and isinstance(value.get("time"), str) - } - primary = features.get(primary_time) - secondary = features.get(secondary_time) - if not primary or not secondary: - return [] - layers = [] - for section in ("varga_ascendants", "arudha_signs"): - primary_values = primary.get(section) or {} - secondary_values = secondary.get(section) or {} - layers.extend( - key for key in set(primary_values) | set(secondary_values) - if primary_values.get(key) != secondary_values.get(key) - ) - fingerprints = (("ashtakavarga", "Ashtakavarga"), ("shadbala", "Shadbala")) - primary_fingerprints = primary.get("fingerprints") or {} - secondary_fingerprints = secondary.get("fingerprints") or {} - layers.extend( - layer for key, layer in fingerprints - if primary_fingerprints.get(key) != secondary_fingerprints.get(key) - ) - return sorted(set(layers))[:8] - - -def _candidate_contrast(built: dict[str, Any], primary_time: str, secondary_time: str) -> tuple[list[str], list[str]]: - event_deltas: list[tuple[float, str]] = [] - for event_id, candidates in built["matrix"].items(): - primary = candidates.get(primary_time) - secondary = candidates.get(secondary_time) - if not primary or not secondary: - continue - delta = abs(float(primary["points"]) - float(secondary["points"])) - if delta > 1e-9: - event_deltas.append((delta, event_id)) - events = [event_id for _, event_id in sorted(event_deltas, key=lambda item: (-item[0], item[1]))] - return _candidate_feature_contrast(built, primary_time, secondary_time), events - - -def run_diagnostics(request: RectificationRequest, rows: list[CandidateScoreRow], built: dict[str, Any]) -> dict[str, Any]: - primary = set(_primary_cluster(rows)) - event_runs = [] - domain_runs = [] - event_domain = {event["id"]: event["domain"] for event in request["events"]} - for event in request["events"]: - winner = _winner(_subtract(rows, {event["id"]})) - event_runs.append({"removed_event_id": event["id"], "winner": winner, "retained": winner in primary}) - by_domain: dict[str, set[str]] = defaultdict(set) - for event_id, domain in event_domain.items(): - by_domain[domain].add(event_id) - for domain, event_ids in by_domain.items(): - winner = _winner(_subtract(rows, event_ids)) - domain_runs.append({"removed_domain": domain, "winner": winner, "retained": winner in primary}) - top = sorted(rows, key=lambda row: row["score"], reverse=True) - top_score = top[0]["score"] if top else 0 - secondary = next((row for row in top if row["time"] not in primary), None) - margin = 0 if not secondary else max(0, (top_score - secondary["score"]) / max(abs(top_score), 1e-9) * 100) - positive_total = sum(max(row["score"], 0) for row in rows) - primary_mass = sum(max(row["score"], 0) for row in rows if row["time"] in primary) - date_items = [] - for item in built["date_sensitivity"]: - date_items.append({ - **{key: value for key, value in item.items() if key != "sample_winners"}, - "candidate_cluster_retention_rate": sum(winner in primary for winner in item["sample_winners"]) / len(item["sample_winners"]), - }) - layers: dict[str, float] = defaultdict(float) - for event_id, candidates in built["matrix"].items(): - for contribution in candidates.values(): - for layer in contribution["technique_layers"]: - layers[layer] += abs(contribution["points"]) - clusters = [_primary_cluster(rows)] - candidate_splits = [] - if secondary and clusters[0]: - contrast_layers, contrast_event_ids = _candidate_contrast(built, top[0]["time"], secondary["time"]) - candidate_splits.append({ - "left_cluster": {"start": clusters[0][0], "end": clusters[0][-1]}, - "right_cluster": {"start": secondary["time"], "end": secondary["time"]}, - "technique_layers": contrast_layers, - "event_ids": contrast_event_ids, - }) - return { - "primary_cluster_retention_rate": 1.0 if primary else 0.0, - "leave_one_event_out_retention_rate": sum(item["retained"] for item in event_runs) / len(event_runs) if event_runs else 0.0, - "leave_one_domain_out_retention_rate": sum(item["retained"] for item in domain_runs) / len(domain_runs) if domain_runs else 0.0, - "date_sensitivity_retention_rate": sum(item["candidate_cluster_retention_rate"] for item in date_items) / len(date_items) if date_items else 0.0, - "neighbor_support_minutes": len(primary), - "primary_secondary_margin_percent": round(min(margin, 100), 4), - "cluster_mass_ratio": primary_mass / positive_total if positive_total else 0.0, - "unstable_event_ids": [item["removed_event_id"] for item in event_runs if not item["retained"]], - "most_discriminating_layers": [name for name, _ in sorted(layers.items(), key=lambda item: item[1], reverse=True)[:12]], - "event_date_sensitivity": date_items, - "candidate_splits": candidate_splits, - "leave_one_event_out": event_runs, - "leave_one_domain_out": domain_runs, - "window_scan": window_scan(built), - } diff --git a/scripts/rectification/horary_observation.py b/scripts/rectification/horary_observation.py deleted file mode 100644 index efeeaec74..000000000 --- a/scripts/rectification/horary_observation.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Display-only Horary recast for birth-time rectification. - -If the user gives the time they first asked the question, recast a natal-like -chart at that local datetime. Never score it. Never block propose or confirm. -""" - -from __future__ import annotations - -import re -from typing import Any - -from scripts.rectification.house_table import SIGNS_CN -from scripts.rectification.kp_cusp_observation import observe_kp_cusps - -_CLOCK = re.compile(r"(?:[01]?\d|2[0-3]):[0-5]\d") - - -def _question_clock(event: dict[str, Any]) -> str: - summary = str(event.get("summary") or "") - match = _CLOCK.search(summary) - if match: - hour, minute = match.group(0).split(":") - return f"{int(hour):02d}:{int(minute):02d}" - return "12:00" - - -def build_horary_observation(request: dict[str, Any]) -> dict[str, Any]: - events = [ - event for event in (request.get("events") or []) - if isinstance(event, dict) and event.get("event_kind") == "horary_query" - ] - if not events: - return { - "status": "skipped", - "user_meaning": "没有第一次问起这件事的时间,占问观察未执行。", - "unique_minute_claim": False, - } - try: - lat = float(request["lat"]) - lon = float(request["lon"]) - tz = float(request["tz"]) - except (KeyError, TypeError, ValueError): - return { - "status": "blocked", - "user_meaning": "占问时间已记录,但观察盘未能重算。不计分,不挡提出门。", - "unique_minute_claim": False, - } - event = events[0] - date_text = str(event.get("date_start") or "")[:10] - clock = _question_clock(event) - try: - year, month, day = (int(part) for part in date_text.split("-")) - hour, minute = (int(part) for part in clock.split(":")) - import domain_calculation_service - chart = domain_calculation_service.compute_chart({ - "year": year, - "month": month, - "day": day, - "hour": hour, - "minute": minute, - "lat": float(request["lat"]), - "lon": float(request["lon"]), - "tz": float(request["tz"]), - "ayanamsa": "raman", - "node_mode": "mean", - }) - asc = chart.get("ascendant") or {} - sign = str(asc.get("sign") or "") - lagna = SIGNS_CN.get(sign, sign) - birth_info = chart.get("birth_info") if isinstance(chart.get("birth_info"), dict) else {} - kp = observe_kp_cusps(birth_info.get("julian_day"), float(request["lat"]), float(request["lon"])) - angles = {} - if kp.get("status") == "executed": - for house in ("1", "4", "7", "10"): - row = (kp.get("houses") or {}).get(house) or {} - angles[house] = { - "sub_lord": row.get("sub_lord"), - "nakshatra_lord": row.get("nakshatra_lord"), - } - return { - "status": "executed", - "question_date": date_text, - "question_time": clock, - "lagna": lagna if lagna else None, - "kp_angles": angles, - "user_meaning": ( - f"已按问起时间 {date_text} {clock} 重算占问盘作观察,不计分,不确认唯一分钟。" - ), - "unique_minute_claim": False, - } - except (TypeError, ValueError, KeyError, OverflowError, OSError): - return { - "status": "blocked", - "question_date": date_text, - "question_time": clock, - "user_meaning": "占问时间已记录,但观察盘未能重算。不计分,不挡提出门。", - "unique_minute_claim": False, - } diff --git a/scripts/rectification/scoring_service.py b/scripts/rectification/scoring_service.py deleted file mode 100644 index 09c286f42..000000000 --- a/scripts/rectification/scoring_service.py +++ /dev/null @@ -1,389 +0,0 @@ -from __future__ import annotations - -import hashlib -import json -from collections import defaultdict -from collections.abc import Callable, Sequence -from datetime import date, timedelta -from typing import Any - -from scripts.active_rectification_event_engine import compute_candidate_static_contexts, compute_event_candidate_rows -from scripts.active_rectification_events import CandidateScoreRow -from scripts.rectification.dasha_transition_proximity import merge_transition_proximity -from scripts.rectification.contracts import LifeEvent, RectificationRequest, is_scoreable_event -from scripts.rectification.case_holdout import holdout_event_ids - -# scoring-10 (2026-10-02, BUG-1181): functional benefic / malefic profile v2 -# (bphs_ch34_general_with_sign_exceptions_v2, 57782aea) feeds the -# *_functional_benefic_auxiliary / *_functional_malefic_auxiliary rules, so identical -# input scores differently; cached scoring-9 results must not be reused as -# current. The dated candidate-window contract is unchanged (scoring-9+). -# scoring-11 (2026-10-07, BUG-1260): D5/D11 sign mappings change education and -# finance varga points for the same input. Cached scoring-10 results must not -# be reused as current. Policy and the dated window contract stay as they are. -# scoring-12 (2026-10-08, BUG-1275): sidereal longitudes include nutation. -# scoring-13 (2026-11-04, BUG-1560 / BUG-1570, product decision): varga.py -# even-sign D30 follows BPHS ch. 6 (health_pressure, feature facts v4) and -# Venus is a functional malefic for Aries / Scorpio (BPHS 34.20 / 34.35), so -# the same input scores differently. Policy and the dated contract unchanged. -# scoring-14 (2026-11-04, #166 astrologer rulings, product decision; BUG-1583..1588): -# Shadbala Sthana (BPHS Saptavargaja values, Moolatrikona Moon 3 / Mercury 15, -# whole-sign Kendradi) and Drik (BPHS 26 special aspects, Mercury with any malefic) -# feed the Shadbala auxiliary; jaimini.py Arudha 1/7 exception counts from the -# first-count pada. Same input scores differently. Policy and dated contract unchanged. -# scoring-15 (2026-11-04, #166 batch 2, BUG-1590): functional roles make Gemini -# Saturn (8, 9) and Virgo Saturn (5, 6) mixed, which the *_functional_* rules read. -ALGORITHM_VERSION = "rectification-v5-matrix-scoring-15" -INPUT_CONTRACT_VERSION = "rectification-calculation-spec-v5" -PRECISION_WEIGHTS = { - "day": 1.0, - "month": 0.8, - "quarter": 0.65, - "year": 0.5, - "range": 0.35, -} - -_ENGINE_KIND_BY_NATIVE_KIND: dict[str, tuple[str, str]] = { - "education_start": ("education", "education_milestone"), - "education_completion": ("education", "education_milestone"), - "education_interruption": ("education", "education_milestone"), - "education_change": ("education", "education_milestone"), - "education_milestone": ("education", "education_milestone"), - "career_entry": ("career", "career_change"), - "career_change": ("career", "career_change"), - "promotion": ("career", "career_change"), - "career_pressure": ("career", "career_change"), - "career_exit": ("career", "career_change"), - "business_start": ("career", "career_change"), - "relationship_start": ("relationship", "relationship_start"), - "relationship_commitment": ("relationship", "relationship_start"), - "relationship_separation": ("relationship", "relationship_change"), - "relationship_end": ("relationship", "relationship_change"), - "relationship_change": ("relationship", "relationship_change"), - "relocation": ("relocation", "relocation"), - "foreign_move": ("relocation", "relocation"), - "return": ("relocation", "relocation"), - "home_change": ("relocation", "relocation"), - "finance_gain": ("finance", "finance_change"), - "finance_loss": ("finance", "finance_change"), - "income_change": ("finance", "finance_change"), - "asset_change": ("finance", "finance_change"), - "finance_change": ("finance", "finance_change"), - "self_health_event": ("health_pressure", "self_health_event"), - "pressure_period": ("health_pressure", "self_health_event"), - "family_event": ("family", "family_event"), - "appearance_note": ("appearance", "appearance_note"), - "birthmark_or_scar": ("appearance", "birthmark_or_scar"), - "occupation_note": ("occupation", "occupation_note"), -} - - -def _parse(value: str) -> date: - return date.fromisoformat(value) - - -def _iso(value: date) -> str: - return value.isoformat() - - -def _month_end(value: date) -> date: - next_month = value.replace(day=28) + timedelta(days=4) - return next_month - timedelta(days=next_month.day) - - -def _even_dates(start: date, end: date, count: int) -> list[date]: - if count <= 1 or start == end: - return [start] - span = (end - start).days - return sorted({start + timedelta(days=round(span * index / (count - 1))) for index in range(count)}) - - -def sample_event_dates(event: LifeEvent) -> list[str]: - start, end = _parse(event["date_start"]), _parse(event["date_end"]) - precision = event["precision"] - if start > end: - raise ValueError("invalid_event_date_range") - if precision == "day" or start == end: - return [_iso(start)] - if precision == "month": - middle = start.replace(day=min(15, _month_end(start).day)) - return sorted({_iso(start), _iso(middle), _iso(end)}) - if precision == "quarter": - values: list[date] = [] - cursor = start.replace(day=15) - while cursor <= end and len(values) < 3: - values.append(cursor) - cursor = (cursor.replace(day=28) + timedelta(days=4)).replace(day=15) - return [_iso(item) for item in values] or [_iso(start)] - if precision == "year": - return [_iso(start.replace(month=month, day=15)) for month in range(1, 13)] - return [_iso(item) for item in _even_dates(start, end, 12)] - - -def _legacy_request(request: RectificationRequest, event: LifeEvent, sampled_date: str) -> dict[str, Any]: - engine_domain, _ = _ENGINE_KIND_BY_NATIVE_KIND[event["event_kind"]] - legacy_request = { - "birth_date": request["birth_date"], - "start_time": request["start_time"], - "end_time": request["end_time"], - "lat": request["lat"], - "lon": request["lon"], - "tz": request["tz"], - "events": [{ - "id": event["id"], "domain": engine_domain, - "event_kind": event["event_kind"], - "date": sampled_date, "precision": "day", "summary": event.get("summary", ""), - }], - } - for key in ("ayanamsa", "node_mode", "minute_step", "candidate_intervals"): - if key in request: - legacy_request[key] = request[key] - return legacy_request - - -def _canonical(value: Any) -> str: - return json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(",", ":")) - - -_SUPPORT_RULES = ( - "functional_benefic_auxiliary", - "arudha_auxiliary", - "ashtakavarga_target_house_support_auxiliary", - "shadbala_sthana_drik_naisargika_support_auxiliary", - "controlled_transit_jupiter_domain_house", -) -_PRESSURE_RULES = ( - "functional_malefic_auxiliary", - "ashtakavarga_target_house_pressure_auxiliary", - "shadbala_sthana_drik_naisargika_pressure_auxiliary", - "controlled_transit_saturn_domain_house", -) - -_KIND_SEMANTICS: dict[str, tuple[int, float]] = { - "education_start": (1, 1.0), - "education_completion": (1, 1.2), - "education_interruption": (-1, 1.0), - "education_change": (0, 1.0), - "career_entry": (1, 1.0), - "career_change": (0, 1.0), - "promotion": (1, 1.2), - "career_pressure": (-1, 1.0), - "career_exit": (-1, 1.2), - "business_start": (1, 1.2), - "relationship_start": (1, 1.0), - "relationship_commitment": (1, 1.2), - "relationship_separation": (-1, 1.0), - "relationship_end": (-1, 1.2), - "relationship_change": (-1, 1.0), - "relocation": (0, 1.0), - "foreign_move": (1, 1.0), - "return": (1, 0.8), - "home_change": (0, 1.0), - "finance_gain": (1, 1.0), - "finance_loss": (-1, 1.0), - "income_change": (0, 1.0), - "asset_change": (0, 1.0), - "self_health_event": (-1, 1.0), - "pressure_period": (-1, 1.2), - "family_event": (0, 1.0), - "appearance_note": (0, 0.8), - "birthmark_or_scar": (-1, 0.8), - "occupation_note": (0, 0.8), -} - - -def precision_weight(precision: str) -> float: - return PRECISION_WEIGHTS[precision] - - -def public_technique_layers(domain: str, rule_ids: Sequence[str]) -> list[str]: - """Public methods actually computed for this event. Career always lists D1-10 and D10.""" - layers: set[str] = set() - for rule in rule_ids: - if rule.startswith(("event_kind:", "event_kind_profile:")): - continue - if "transition_proximity" in rule: - layers.add("dasha-transition-proximity") - continue - layers.add(rule.split(":", 1)[0]) - if domain == "career": - layers.update({"d1-rashi", "d10-dashamsa"}) - elif domain == "family": - layers.update({"d1-rashi", "d12-dwadashamsha", "d7-saptamsha", "d3-drekkana"}) - elif domain == "education": - layers.update({"d1-rashi", "d24-chaturvimshamsha", "d5-panchamsha"}) - elif domain == "relocation": - layers.update({"d1-rashi", "d4-chaturthamsha"}) - elif domain == "finance": - layers.update({"d1-rashi", "d2-hora", "d11-labhamsha"}) - elif domain == "health_pressure": - layers.update({"d1-rashi", "d30-trimshamsha"}) - elif domain in {"appearance", "marks"}: - layers.add("d1-rashi") - elif domain == "occupation": - layers.update({"d1-rashi", "d10-dashamsa"}) - return sorted(layers) - - -def _event_kind_factor(event_kind: str, rule_ids: Sequence[str]) -> float: - direction, intensity = _KIND_SEMANTICS.get(event_kind, (0, 1.0)) - support = sum(any(rule.endswith(marker) for marker in _SUPPORT_RULES) for rule in rule_ids) - pressure = sum(any(rule.endswith(marker) for marker in _PRESSURE_RULES) for rule in rule_ids) - semantic_signal = direction * (support - pressure) * intensity - return max(0.8, min(1.2, 1 + 0.08 * semantic_signal)) - - -def _kind_adjusted_evidence(event: LifeEvent, evidence: dict[str, Any]) -> dict[str, Any]: - event_kind = event["event_kind"] - rules = list(evidence["rule_ids"]) - direction, _ = _KIND_SEMANTICS.get(event_kind, (0, 1.0)) - semantic_label = "support" if direction > 0 else "pressure" if direction < 0 else "change" - return { - **evidence, - "rule_ids": [*rules, f"event_kind_profile:{event_kind}:{semantic_label}"], - "points": round( - float(evidence["points"]) - * _event_kind_factor(event_kind, rules) - * precision_weight(event["precision"]), - 4, - ), - } - - -def scoreable_request(request: RectificationRequest) -> RectificationRequest: - return {**request, "events": [event for event in request["events"] if is_scoreable_event(event)]} - - -def build_event_contribution_matrix( - request: RectificationRequest, - row_provider: Callable[[dict[str, Any]], Sequence[CandidateScoreRow]] | None = None, - static_contexts: Sequence[dict[str, Any]] | None = None, -) -> dict[str, Any]: - scoring_request = scoreable_request(request) - if not scoring_request["events"]: - return { - "candidate_times": [], "matrix": {}, "date_sensitivity": [], - "missing_layers": [], "static_contexts": None, - } - if static_contexts is None and row_provider is None: - static_contexts = compute_candidate_static_contexts(scoring_request) - provider = row_provider or (lambda value: compute_event_candidate_rows(value, static_contexts=static_contexts)) - matrix: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) - missing_layers: set[str] = set() - date_sensitivity: list[dict[str, Any]] = [] - candidate_grid: list[str] | None = None - for event in scoring_request["events"]: - samples = sample_event_dates(event) - sample_rows = [] - for sampled in samples: - rows = list(provider(_legacy_request(scoring_request, event, sampled))) - sample_rows.append([ - {**row, "score": adjusted["points"], "evidence": [adjusted]} - for row in rows - for adjusted in [_kind_adjusted_evidence(event, row["evidence"][0])] - ]) - grids = [[row["time"] for row in rows] for rows in sample_rows] - if any(grid != grids[0] for grid in grids[1:]) or (candidate_grid is not None and grids[0] != candidate_grid): - raise ValueError("candidate_grid_mismatch") - candidate_grid = grids[0] - winners = [] - for rows in sample_rows: - winners.append(max(rows, key=lambda row: row["score"])["time"]) - missing_layers.update(layer for row in rows for layer in row["missing_layers"]) - for index, candidate_time in enumerate(candidate_grid): - evidences = [rows[index]["evidence"][0] for rows in sample_rows] - points = [float(item["points"]) for item in evidences] - matrix[event["id"]][candidate_time] = { - "points": round(sum(points) / len(points), 4), - "rule_ids": sorted({rule for item in evidences for rule in item["rule_ids"]}), - "technique_layers": public_technique_layers( - event["domain"], - [rule for item in evidences for rule in item["rule_ids"]], - ), - } - winner = max(set(winners), key=winners.count) - mean = sum(matrix[event["id"]][time]["points"] for time in candidate_grid) / len(candidate_grid) - variance = sum((matrix[event["id"]][time]["points"] - mean) ** 2 for time in candidate_grid) / len(candidate_grid) - date_sensitivity.append({ - "event_id": event["id"], - "declared_date_range": {"start": event["date_start"], "end": event["date_end"], "precision": event["precision"]}, - "sample_dates": samples, - "winner_retention_rate": winners.count(winner) / len(winners), - "score_variance": round(variance, 6), - "sample_winners": winners, - }) - matrix_payload = dict(matrix) - if static_contexts: - merge_transition_proximity( - matrix_payload, - scoring_request["events"], - static_contexts, - scoring_request["birth_date"], - public_technique_layers=public_technique_layers, - ) - return { - "candidate_times": candidate_grid or [], - "matrix": matrix_payload, - "date_sensitivity": date_sensitivity, - "missing_layers": sorted(missing_layers), - "static_contexts": static_contexts, - **({"candidate_intervals": request["candidate_intervals"]} if "candidate_intervals" in request else {}), - } - - -def score_from_matrix(request: RectificationRequest, built: dict[str, Any]) -> list[CandidateScoreRow]: - holdout = holdout_event_ids(request["events"]) - rows: list[CandidateScoreRow] = [] - for candidate_time in built["candidate_times"]: - evidence = [] - for event in request["events"]: - if not is_scoreable_event(event): - continue - if event["id"] in holdout: - continue - contribution = (built.get("matrix") or {}).get(event["id"], {}).get(candidate_time) - if not isinstance(contribution, dict): - continue - evidence.append({ - "event_id": event["id"], "domain": event["domain"], "candidate_time": candidate_time, - "rule_ids": contribution["rule_ids"], "points": contribution["points"], - }) - rows.append({ - "time": candidate_time, - "score": round(sum(item["points"] for item in evidence), 4), - "evidence": evidence, - "missing_layers": built["missing_layers"], - }) - return rows - - -def calculation_spec(request: RectificationRequest) -> dict[str, Any]: - def json_number(value: float) -> int | float: - return int(value) if value.is_integer() else value - - spec = { - "version": INPUT_CONTRACT_VERSION if "candidate_intervals" in request else "rectification-calculation-spec-v4", - "birthDate": request["birth_date"], - "candidateRange": {"start": request["start_time"], "end": request["end_time"]}, - "latitude": json_number(request["lat"]), - "longitude": json_number(request["lon"]), - "timezoneOffsetHours": json_number(request["tz"]), - "ayanamsa": request.get("ayanamsa", "raman"), - "nodeMode": request.get("node_mode", "mean"), - "minuteStep": int(request.get("minute_step") or 1), - } - for source, target in ( - ("birth_time_source", "birthTimeSource"), - ("timezone_id", "timezoneId"), - ("timezone_source", "timezoneSource"), - ("local_time_status", "localTimeStatus"), - ): - if source in request: - spec[target] = request[source] # type: ignore[literal-required] - if "candidate_intervals" in request: - spec["candidateIntervals"] = request["candidate_intervals"] - return spec - - -def sha256(value: Any) -> str: - return hashlib.sha256(_canonical(value).encode()).hexdigest() diff --git a/scripts/rectification/sealed_holdout.py b/scripts/rectification/sealed_holdout.py deleted file mode 100644 index 94eafb671..000000000 --- a/scripts/rectification/sealed_holdout.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Product-facing sealed public AA holdout contract. - -This module does not invent cases. A human updates -`references/rectification_sealed_holdout.v1.json` after a valid passing -evaluation of a frozen public AA set. LOEO/LODO are not a holdout. -""" - -from __future__ import annotations - -import json -from pathlib import Path -from typing import Any, Final - -ROOT = Path(__file__).resolve().parents[2] -HOLDOUT_PATH: Final = ROOT / "references" / "rectification_sealed_holdout.v1.json" - - -def load_sealed_minute_holdout() -> dict[str, Any]: - data = json.loads(HOLDOUT_PATH.read_text(encoding="utf-8")) - if not isinstance(data, dict): - raise ValueError("sealed holdout contract must be an object") - status = str(data.get("status") or "not_ready").strip() or "not_ready" - return { - "sealed_benchmark_id": str(data.get("sealed_benchmark_id") or "").strip(), - "status": status if status == "ready" else "not_ready", - "valid_public_aa_cases": int(data.get("valid_public_aa_cases") or 0), - "required_cases": int(data.get("required_cases") or 20), - "top_1_rate": float(data.get("top_1_rate") or 0), - "confirmation_coverage_rate": float(data.get("confirmation_coverage_rate") or 0), - } - - -def holdout_passed(holdout: dict[str, Any] | None = None) -> bool: - row = holdout or load_sealed_minute_holdout() - return ( - row["status"] == "ready" - and int(row["valid_public_aa_cases"]) >= int(row["required_cases"]) - and float(row["confirmation_coverage_rate"]) > 0 - ) diff --git a/scripts/rectification/varga_style_calibration_report.py b/scripts/rectification/varga_style_calibration_report.py deleted file mode 100644 index 85eb68fe9..000000000 --- a/scripts/rectification/varga_style_calibration_report.py +++ /dev/null @@ -1,135 +0,0 @@ -"""Offline hit-rate for yearless personality probes. - -Reads an anonymized JSON export. Prints n and hit rate grouped by D9 / D10 / -nakshatra. Never prints a per-case row. -""" - -from __future__ import annotations - -import argparse -import json -import sys -from collections import defaultdict -from pathlib import Path -from typing import Any, Iterable, Mapping - -GROUPS = ("d9", "d10", "nakshatra") -HOSPITAL = "hospital_record" -MAX_UNCERTAINTY_MINUTES = 2 - - -def _text(value: object) -> str: - return value.strip() if isinstance(value, str) else "" - - -def _int(value: object) -> int | None: - if isinstance(value, bool) or value is None: - return None - if isinstance(value, int) and not isinstance(value, bool): - return value - if isinstance(value, float) and value.is_integer(): - return int(value) - if isinstance(value, str) and value.strip().lstrip("-").isdigit(): - return int(value.strip()) - return None - - -def infer_group(row: Mapping[str, Any]) -> str | None: - explicit = _text(row.get("group")).lower() - if explicit in GROUPS: - return explicit - key = _text(row.get("semantic_key") or row.get("semanticKey")).lower() - if key.startswith("varga.d9.") or ".d9." in key: - return "d9" - if key.startswith("varga.d10.") or ".d10." in key: - return "d10" - if "nakshatra" in key: - return "nakshatra" - return None - - -def _sign(value: object) -> str: - return _text(value) - - -def selected_sign(row: Mapping[str, Any]) -> str | None: - answer = _text(row.get("answer_class") or row.get("answerClass")) - if not answer or answer in {"unsure", "no"}: - return None - options = row.get("options") - if not isinstance(options, list): - return None - for option in options: - if not isinstance(option, Mapping): - continue - option_class = _text(option.get("answer_class") or option.get("answerClass")) - if option_class != answer: - continue - sign = _sign(option.get("sign")) - return sign or None - return None - - -def recorded_sign(row: Mapping[str, Any]) -> str | None: - sign = _sign(row.get("recorded_sign") or row.get("recordedSign")) - return sign or None - - -def hospital_case(row: Mapping[str, Any]) -> bool: - if _text(row.get("birth_time_source") or row.get("birthTimeSource")) != HOSPITAL: - return False - before = _int(row.get("uncertainty_before_minutes") or row.get("uncertaintyBeforeMinutes")) - after = _int(row.get("uncertainty_after_minutes") or row.get("uncertaintyAfterMinutes")) - if before is None or after is None: - return False - return before <= MAX_UNCERTAINTY_MINUTES and after <= MAX_UNCERTAINTY_MINUTES - - -def summarize(payload: Mapping[str, Any] | Iterable[Any]) -> dict[str, dict[str, float | int | None]]: - cases = payload.get("cases") if isinstance(payload, Mapping) else payload - if not isinstance(cases, list): - cases = [] - hits: dict[str, int] = defaultdict(int) - total: dict[str, int] = defaultdict(int) - for case in cases: - if not isinstance(case, Mapping) or not hospital_case(case): - continue - answers = case.get("answers") - if not isinstance(answers, list): - continue - for answer in answers: - if not isinstance(answer, Mapping): - continue - group = infer_group(answer) - chosen = selected_sign(answer) - recorded = recorded_sign(answer) - if group is None or not chosen or not recorded: - continue - total[group] += 1 - if chosen == recorded: - hits[group] += 1 - out: dict[str, dict[str, float | int | None]] = {} - for group in GROUPS: - n = total[group] - rate = round(hits[group] / n, 3) if n else None - out[group] = {"n": n, "hit_rate": rate} - return out - - -def load_payload(path: Path) -> Any: - return json.loads(path.read_text(encoding="utf-8")) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description="Yearless personality probe hit-rate (hospital records only).") - parser.add_argument("path", type=Path, help="Anonymized JSON export") - args = parser.parse_args(argv) - payload = load_payload(args.path) - report = summarize(payload) - json.dump(report, sys.stdout, ensure_ascii=False) - sys.stdout.write("\n") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/rectification/vedastro_validate_cache.py b/scripts/rectification/vedastro_validate_cache.py deleted file mode 100644 index e0d59b0dd..000000000 --- a/scripts/rectification/vedastro_validate_cache.py +++ /dev/null @@ -1,111 +0,0 @@ -"""Day-long memory and a time budget for the rectification VedAstro check (issue #130). - -``/api/rectification/v5/vedastro-validate`` runs up to two minute snapshots -and one range scan per supported event for each candidate, each with the -adapter's own timeout. When VedAstro is rate limited every delivery turn ran -them all again (worst case about 15 s), and the total could outlast the 12 s -the frontend waits. - -- A result that failed because of VedAstro itself (timeout, exception, no - official response) is kept in memory for a day, keyed by the evidence - fingerprint and the candidate pair. A result decided by the evidence (a - pass, or layers that do not discriminate) is not kept: it is computed again. -- The whole check has ``VALIDATE_BUDGET_SECONDS`` (under the frontend's 12 s). - A call that would start past the budget is not made and counts as a - timeout; one that starts near the end runs with the time that is left. - Calls with time to spare keep the adapter's own timeout, so a normal run is - byte-identical to before. -""" -from __future__ import annotations - -import hashlib -import json -import threading -import time -from collections import OrderedDict -from typing import Any, Callable - -try: - from scripts.vedastro_runtime_context import temporary_timeout_seconds -except ModuleNotFoundError: # pragma: no cover - script execution path - from vedastro_runtime_context import temporary_timeout_seconds - -KEEP_SECONDS = 24 * 60 * 60 -MAX_ENTRIES = 256 -# The frontend's postEngine timeout for this route is 12 s. -VALIDATE_BUDGET_SECONDS = 11.0 -# Below this the adapter floors the timeout at 1 s anyway; do not start a call. -MIN_CALL_SECONDS = 1.0 -SERVICE_BLOCKERS = frozenset({"vedastro_timeout", "vedastro_exception", "vedastro_official_response_missing"}) - -_entries: "OrderedDict[str, tuple[float, dict[str, Any]]]" = OrderedDict() -_guard = threading.Lock() - - -def validation_key(request_body: dict[str, Any], candidate_times: list[str]) -> str: - """Evidence fingerprint (the whole request without the pair) plus the pair, in order.""" - canonical = json.dumps( - {"request": request_body, "candidate_times": list(candidate_times)}, - ensure_ascii=False, - sort_keys=True, - separators=(",", ":"), - default=str, - ) - return hashlib.sha256(canonical.encode("utf-8")).hexdigest() - - -def remembered_failure(key: str, *, now: float | None = None) -> dict[str, Any] | None: - moment = time.time() if now is None else now - with _guard: - entry = _entries.get(key) - if entry is None: - return None - if entry[0] <= moment: - _entries.pop(key, None) - return None - _entries.move_to_end(key) - return json.loads(json.dumps(entry[1])) - - -def remember_if_service_failure(key: str, result: dict[str, Any], *, now: float | None = None) -> bool: - blockers = set(result.get("blockers") or []) - if result.get("passed") or not blockers & SERVICE_BLOCKERS: - return False - moment = time.time() if now is None else now - with _guard: - _entries[key] = (moment + KEEP_SECONDS, json.loads(json.dumps(result))) - _entries.move_to_end(key) - while len(_entries) > MAX_ENTRIES: - _entries.popitem(last=False) - return True - - -def clear() -> None: - with _guard: - _entries.clear() - - -class ValidateBudget: - """One check's deadline, shared by all its adapter calls.""" - - def __init__( - self, - adapter_timeout: Callable[[], float] | None = None, - *, - seconds: float = VALIDATE_BUDGET_SECONDS, - clock: Callable[[], float] = time.monotonic, - ) -> None: - self._adapter_timeout = adapter_timeout - self._clock = clock - self._deadline = clock() + seconds - - def call(self, safe_call: Callable[..., dict[str, Any]], call: Callable[..., Any], *args: Any, **kwargs: Any) -> dict[str, Any]: - remaining = self._deadline - self._clock() - if remaining < MIN_CALL_SECONDS: - return {"available": False, "status": "timeout", "_failure_kind": "timeout"} - # An adapter that does not say its timeout is left alone until the budget runs out. - per_call = self._adapter_timeout() if self._adapter_timeout is not None else float("inf") - if remaining >= per_call or per_call == float("inf"): - return safe_call(call, *args, **kwargs) - with temporary_timeout_seconds(remaining): - return safe_call(call, *args, **kwargs) diff --git a/scripts/rectification_prior_calibration.py b/scripts/rectification_prior_calibration.py deleted file mode 100644 index a8e5895c3..000000000 --- a/scripts/rectification_prior_calibration.py +++ /dev/null @@ -1,290 +0,0 @@ -#!/usr/bin/env python3 -"""Compare relative_support scales on public minute-rectification cases. - -Reads development cases for inspection and the sealed holdout for the -enablement gate. Scores each window once, then rebuilds public candidate -decisions under proportional / offset / softmax temperatures. -""" -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import traceback -from calendar import monthrange -from datetime import date, datetime -from decimal import Decimal -from pathlib import Path -from typing import Any -from uuid import NAMESPACE_URL, uuid5 - -ROOT = Path(__file__).resolve().parents[1] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.rectification.candidate_contrast import cluster_contexts_by_signature, context_time -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.decision_policy import build_candidate_decisions -from scripts.rectification.scoring_service import ( - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) - -DEVELOPMENT_MANIFEST = ROOT / "references" / "real_case_calibration" / "minute_rectification_development_v1.json" -HOLDOUT_MANIFEST = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v3.json" -LEAD = 8 -TODAY = date(2026, 9, 6) -KIND_BY_DOMAIN = { - "education": "education_milestone", - "career": "career_change", - "relationship": "relationship_commitment", - "relocation": "relocation", - "health_pressure": "self_health_event", - "health": "self_health_event", - "finance": "finance_change", - "family": "family_event", -} -SCHEMES: tuple[dict[str, Any], ...] = ( - {"id": "proportional", "mode": "proportional", "temperature": None}, - {"id": "offset", "mode": "offset", "temperature": None}, - {"id": "softmax_0.25", "mode": "softmax", "temperature": Decimal("0.25")}, - {"id": "softmax_0.5", "mode": "softmax", "temperature": Decimal("0.5")}, - {"id": "softmax_1", "mode": "softmax", "temperature": Decimal("1")}, - {"id": "softmax_2", "mode": "softmax", "temperature": Decimal("2")}, -) - - -def _clock(value: str) -> int: - return int(value[:2]) * 60 + int(value[3:5]) - - -def _hhmm_from_minutes(value: int) -> str: - wrapped = value % 1440 - return f"{wrapped // 60:02d}:{wrapped % 60:02d}" - - -def _shift_clock(value: str, delta: int) -> str: - return _hhmm_from_minutes(_clock(value) + delta) - - -def _expand_date(raw: str, precision: str) -> tuple[str, str]: - text = str(raw or "").strip() - if precision == "day": - day = date.fromisoformat(text) - return day.isoformat(), day.isoformat() - if precision == "month": - month = date.fromisoformat(f"{text}-01") if len(text) == 7 else date.fromisoformat(text[:10]).replace(day=1) - last = monthrange(month.year, month.month)[1] - return month.isoformat(), month.replace(day=last).isoformat() - year = int(text[:4]) - return f"{year}-01-01", f"{year}-12-31" - - -def _event_kind(event: dict[str, Any]) -> str: - domain = str(event.get("domain") or "") - description = str(event.get("description") or "").lower() - if domain == "relationship" and not any(token in description for token in ("married", "wedding", "wife", "husband")): - return "relationship_start" - return KIND_BY_DOMAIN[domain] - - -def _request_from_case(case: dict[str, Any]) -> dict[str, Any]: - birth = case["birth"] - true_time = str(birth["time"])[:5] - radius = int(case.get("candidate_radius_minutes") or 10) - events = [] - for event in case.get("events") or []: - precision = str(event.get("precision") or "year") - start, end = _expand_date(str(event.get("date") or ""), precision) - domain = str(event.get("domain") or "") - events.append({ - "id": str(uuid5(NAMESPACE_URL, str(event.get("id") or ""))), - "domain": domain, - "event_kind": _event_kind(event), - "date_start": start, - "date_end": end, - "precision": precision, - "summary": str(event.get("description") or event.get("id") or domain)[:200], - }) - return normalize_rectification_request({ - "birth_date": str(birth["date"]), - "start_time": _shift_clock(true_time, -radius), - "end_time": _shift_clock(true_time, radius), - "lat": float(birth["latitude"]), - "lon": float(birth["longitude"]), - "tz": float(birth["timezone_offset"]), - "events": events, - }, today=TODAY) - - -def _cluster_bounds(time: str, clusters: list[dict[str, Any]]) -> tuple[str, str]: - for cluster in clusters: - times = [str(item)[:5] for item in cluster.get("times") or [] if str(item)] - if time not in times: - continue - ordered = sorted(times, key=_clock) - return ordered[0], ordered[-1] - return time, time - - -def _union_metrics( - decisions: list[dict[str, Any]], - *, - true_time: str, - start_time: str, - clusters: list[dict[str, Any]], -) -> dict[str, Any]: - if not decisions: - return {"width": None, "covers": False, "peak": 0, "valid_count": 0} - peak = max(int(item["relative_support"]) for item in decisions) - valid = [item for item in decisions if peak - int(item["relative_support"]) < LEAD] - origin = _clock(start_time) - points: list[int] = [] - for item in valid: - time = str(item["time"])[:5] - lo, hi = _cluster_bounds(time, clusters) - for stamp in (time, lo, hi): - points.append((_clock(stamp) - origin) % 1440) - width = (max(points) - min(points) + 1) if points else None - true_offset = (_clock(true_time) - origin) % 1440 - covers = width is not None and min(points) <= true_offset <= max(points) - return { - "width": width, - "covers": covers, - "peak": peak, - "valid_count": len(valid), - "supports": [int(item["relative_support"]) for item in decisions], - } - - -def _score_case(case: dict[str, Any]) -> dict[str, Any]: - request = _request_from_case(case) - scoring = scoreable_request(request) - built = build_event_contribution_matrix(scoring) - rows = score_from_matrix(scoring, built) - contexts = built.get("static_contexts") if isinstance(built.get("static_contexts"), list) else None - clusters = cluster_contexts_by_signature( - [item for item in (contexts or []) if isinstance(item, dict) and context_time(item)] - ) if contexts else [] - true_time = str(case["birth"]["time"])[:5] - schemes = {} - for scheme in SCHEMES: - decisions = build_candidate_decisions( - rows, - result_id=str(uuid5(NAMESPACE_URL, case["case_id"])), - static_contexts=contexts, - support_mode=scheme["mode"], - temperature=scheme["temperature"], - ) - schemes[scheme["id"]] = _union_metrics( - decisions, - true_time=true_time, - start_time=request["start_time"], - clusters=clusters, - ) - return { - "case_id": case["case_id"], - "radius": int(case.get("candidate_radius_minutes") or 10), - "schemes": schemes, - } - - -def _summarize(rows: list[dict[str, Any]]) -> dict[str, Any]: - table: dict[str, Any] = {} - for scheme in SCHEMES: - widths = [int(item["schemes"][scheme["id"]]["width"]) for item in rows if item["schemes"][scheme["id"]]["width"] is not None] - covered = sum(1 for item in rows if item["schemes"][scheme["id"]]["covers"]) - table[scheme["id"]] = { - "n": len(rows), - "coverage": covered, - "median_width": statistics.median(widths) if widths else None, - "mean_width": round(statistics.mean(widths), 2) if widths else None, - } - return table - - -def _pick_scheme(holdout: dict[str, Any]) -> dict[str, Any]: - baseline = holdout["proportional"] - old_coverage = int(baseline["coverage"]) - old_median = baseline["median_width"] - passing = [] - for scheme_id, row in holdout.items(): - if scheme_id == "proportional": - continue - median = row["median_width"] - if median is None or old_median is None: - continue - if int(row["coverage"]) >= old_coverage - 1 and median < old_median: - passing.append((scheme_id, row)) - if not passing: - return {"id": "proportional", "enabled": False, "reason": "no_scheme_passed_holdout_gate"} - preferred = [item for item in passing if item[0] == "offset"] - chosen = preferred[0] if preferred else min(passing, key=lambda item: (item[1]["median_width"], -item[1]["coverage"])) - return {"id": chosen[0], "enabled": True, "reason": "passed_holdout_gate"} - - -def _load_cases(path: Path, *, holdout_only: bool) -> list[dict[str, Any]]: - payload = json.loads(path.read_text(encoding="utf-8")) - cases = list(payload.get("cases") or []) - if holdout_only: - cases = [item for item in cases if item.get("excluded_from_tuning") is True] - return cases - - -def run(limit: int | None = None) -> dict[str, Any]: - development_cases = _load_cases(DEVELOPMENT_MANIFEST, holdout_only=False) - holdout_cases = _load_cases(HOLDOUT_MANIFEST, holdout_only=True) - if limit is not None: - development_cases = development_cases[:limit] - holdout_cases = holdout_cases[:limit] - development_rows = [_score_case(item) for item in development_cases] - holdout_rows = [_score_case(item) for item in holdout_cases] - development = _summarize(development_rows) - holdout = _summarize(holdout_rows) - return { - "lead": LEAD, - "development": development, - "holdout": holdout, - "selection": _pick_scheme(holdout), - "development_rows": development_rows, - "holdout_rows": holdout_rows, - } - - -def _print_table(title: str, table: dict[str, Any]) -> None: - print(title) - print(f"{'scheme':<16} {'coverage':>10} {'median':>10} {'mean':>10}") - for scheme_id, row in table.items(): - print( - f"{scheme_id:<16} " - f"{row['coverage']}/{row['n']:<7} " - f"{str(row['median_width']):>10} " - f"{str(row['mean_width']):>10}" - ) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--limit", type=int, default=None) - parser.add_argument("--json-out", type=Path) - args = parser.parse_args() - try: - report = run(args.limit) - except Exception: - traceback.print_exc() - return 1 - _print_table("development", report["development"]) - print() - _print_table("holdout", report["holdout"]) - print() - print("selection", json.dumps(report["selection"], ensure_ascii=False)) - if args.json_out: - args.json_out.parent.mkdir(parents=True, exist_ok=True) - args.json_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/answer_flip_tolerance.py b/scripts/research/answer_flip_tolerance.py deleted file mode 100644 index 88b99536c..000000000 --- a/scripts/research/answer_flip_tolerance.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/env python3 -"""R1 (2026-09-26): yes/no answer-error tolerance of the six-question replay. - -Offline only; production scoring, probe gates and Skill text are untouched. -Replays the same six probes the 2026-09-14 precision-gate / cluster-width -research used (production G0 gate, lead-8 union delivery), but with 1 or 2 of -the answered questions flipped (yes<->no). Flip sets are drawn with fixed -string seeds and repeated; an exhaustive all-combinations pass is reported as -a cross-check of the sampled numbers. - -This is the public AA open set (v4), not a blind test. Every six-question -number is still an upper bound in one respect: the probe list is not re-drawn -after each answer (the same limitation as the 09-14 replays). - -Run: - python3 scripts/research/answer_flip_tolerance.py # full run - python3 scripts/research/answer_flip_tolerance.py --limit 2 # smoke -""" - -from __future__ import annotations - -import argparse -import json -import sys -import traceback -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - NODE_MODE, - compute_candidate_static_contexts, -) -import scripts.rectification.event_probes as event_probes # noqa: E402 -from scripts.research.cluster_width_lib import ( # noqa: E402 - SEPARATION_LEAD, - delivery_from_public, - merge_adjacent_traced, - metrics_bundle, - public_from_clusters, - raw_signature_clusters, - shannon_entropy, - still_valid_public, -) -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.offline_research_20260926_lib import ( # noqa: E402 - FLIP_SEED, - answerable_indices, - exhaustive_flip_sets, - flipped_answers, - median_of, - rate, - sample_flip_sets, -) -from scripts.research.precision_gate_lib import finest_precision # noqa: E402 -from scripts.research.precision_gate_sweep import generate_probes, score_bundle # noqa: E402 -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - apply_answer, - optimal_answer, -) - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -REPORT_JSON = ROOT / "docs" / "research" / "answer_flip_tolerance_2026_09_26.json" -RADII = (10, 30, 60) -FLIP_COUNTS = (0, 1, 2) -REPEATS = 30 - - -def public_for(rows: Sequence[dict[str, Any]], contexts: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: - raw = raw_signature_clusters(contexts) - by_time = {str(row["time"])[:5]: row for row in rows if str(row.get("time"))} - merged, _trace = merge_adjacent_traced(raw, by_time) - public = public_from_clusters(merged, rows) - for row in public: - row["score"] = float(row.get("score") or 0) - return public - - -def replay_with_answers( - *, - probes: Sequence[dict[str, Any]], - answers: Sequence[str | None], - public: Sequence[dict[str, Any]], - true_time: str, - window_times: Sequence[str], -) -> dict[str, Any]: - """Same bookkeeping as cluster_width_probe.replay_public + evaluate_delivery, - but the answer to each asked probe comes from `answers`.""" - reps = [str(row["time"])[:5] for row in public] - scores = {str(row["time"])[:5]: float(row.get("score") or 0) for row in public} - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - for probe, answer in zip(list(probes)[:ASK_COUNT], answers): - if answer is None: - continue - scores, conflicts, eliminated = apply_answer( - scores, conflicts, eliminated, probe, answer, reps, - ) - posterior = [ - {**row, "score": scores.get(str(row["time"])[:5], row["score"])} - for row in public - ] - valid = still_valid_public(posterior, scores, eliminated, lead=SEPARATION_LEAD) - delivery = delivery_from_public(valid) - alive = [row for row in posterior if str(row["time"])[:5] not in eliminated] - metrics = metrics_bundle( - public=alive, - true_time=true_time, - window_times=window_times, - delivery_times=delivery["times"], - delivery_width=delivery["width"], - independent=True, - entropy_scores=[scores.get(str(row["time"])[:5], 0.0) for row in alive], - ) - true_rep_eliminated = any( - true_time in (row.get("cluster_times") or [str(row.get("time"))[:5]]) - and str(row["time"])[:5] in eliminated - for row in public - ) - return { - "top1": bool(metrics["top1_hit"]), - "coverage": bool(metrics["coverage"]), - "width": delivery["width"], - "tie": bool(metrics["tie"]), - "eliminated": len(eliminated), - "truth_eliminated": true_rep_eliminated, - "entropy": round(shannon_entropy(max(s, 0.0) for t, s in scores.items() if t not in eliminated), 4), - } - - -def run_case(case: dict[str, Any], radius: int, repeats: int) -> dict[str, Any]: - case_id = case["case_id"] - true_time = str(case["birth"]["time"])[:5] - request = scoring_request_for({**case, "candidate_radius_minutes": radius}, radius) - contexts = compute_candidate_static_contexts(request) - events = list(case.get("events") or []) - bundle = score_bundle(case, radius, events, contexts, None) - rows = bundle["rows"] - times = [str(row["time"])[:5] for row in rows] - probes = generate_probes( - bundle["request"], bundle["built"], times, true_time, - gate="G0", precision=finest_precision(events), refresh=False, - ) - asked = list(probes)[:ASK_COUNT] - optimal = [optimal_answer(probe, true_time) for probe in asked] - public = public_for(rows, list(bundle["built"].get("static_contexts") or contexts)) - out: dict[str, Any] = { - "case_id": case_id, - "radius": radius, - "asked": len(asked), - "answerable": len(answerable_indices(optimal)), - "public_clusters": len(public), - "runs": {}, - "exhaustive": {}, - } - for k in FLIP_COUNTS: - if k == 0: - sets: list[tuple[int, ...]] = [()] - full: list[tuple[int, ...]] = [()] - else: - sets = sample_flip_sets(optimal, k, repeats, case_id=case_id, radius=radius) - full = exhaustive_flip_sets(optimal, k) - out["runs"][str(k)] = [ - {"flipped": list(item), **replay_with_answers( - probes=asked, answers=flipped_answers(optimal, item), - public=public, true_time=true_time, window_times=times, - )} - for item in sets - ] - out["exhaustive"][str(k)] = [ - {"flipped": list(item), **replay_with_answers( - probes=asked, answers=flipped_answers(optimal, item), - public=public, true_time=true_time, window_times=times, - )} - for item in full - ] - return out - - -def summarize(case_rows: Sequence[dict[str, Any]], key: str) -> dict[str, Any]: - table: dict[str, Any] = {} - for radius in sorted({row["radius"] for row in case_rows}): - table[str(radius)] = {} - for k in FLIP_COUNTS: - runs = [run for row in case_rows if row["radius"] == radius for run in row[key].get(str(k), [])] - eligible = [row for row in case_rows if row["radius"] == radius and row[key].get(str(k))] - per_case_cov = [ - all(run["coverage"] for run in row[key][str(k)]) for row in eligible - ] - base = [row[key]["0"][0] for row in eligible] - table[str(radius)][str(k)] = { - "baseline_same_cases": { - "truth_in_range": rate(base, "coverage"), - "head_hit": rate(base, "top1"), - "width_median": median_of(base, "width"), - }, - "cases": len(eligible), - "runs": len(runs), - "truth_in_range": rate(runs, "coverage"), - "head_hit": rate(runs, "top1"), - "width_median": median_of(runs, "width"), - "tie": rate(runs, "tie"), - "truth_eliminated": rate(runs, "truth_eliminated"), - "cases_ever_squeezed": sum(1 for ok in per_case_cov if not ok), - } - return table - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--repeats", type=int, default=REPEATS) - parser.add_argument("--radii", nargs="+", type=int, default=list(RADII)) - parser.add_argument("--no-write", action="store_true") - args = parser.parse_args() - holdout = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(holdout["cases"])[: args.limit or None] - assert event_probes.MIN_BOUNDARY_DAYS == 45 and event_probes.REFRESH_MIN_BOUNDARY_DAYS == 30 - case_rows: list[dict[str, Any]] = [] - errors: list[dict[str, Any]] = [] - for case in cases: - for radius in args.radii: - try: - case_rows.append(run_case(case, radius, args.repeats)) - except Exception as exc: # noqa: BLE001 - errors.append({"case_id": case["case_id"], "radius": radius, - "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()}) - print(f"done {case['case_id']}", flush=True) - assert event_probes.MIN_BOUNDARY_DAYS == 45 and event_probes.REFRESH_MIN_BOUNDARY_DAYS == 30 - payload = { - "generated_at": "2026-09-26", - "nature": "offline replay on the public AA open set (v4); not a blind test, not accuracy", - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "holdout": str(HOLDOUT.relative_to(ROOT)), - "case_count": len(cases), - "radii": list(args.radii), - "minute_step": MINUTE_STEP, - "ask_count": ASK_COUNT, - "flip_seed": FLIP_SEED, - "repeats": args.repeats, - "gate": "G0 production (45 / refresh 30)", - "delivery": f"lead-{SEPARATION_LEAD} union of non-eliminated clusters", - "sampled": summarize(case_rows, "runs"), - "exhaustive": summarize(case_rows, "exhaustive"), - "answerable_per_case": { - str(radius): [row["answerable"] for row in case_rows if row["radius"] == radius] - for radius in args.radii - }, - "per_case": [ - { - "case_id": row["case_id"], - "radius": row["radius"], - "answerable": row["answerable"], - **{ - f"k{k}": { - "truth_in_range": rate(row["exhaustive"].get(str(k), []), "coverage"), - "head_hit": rate(row["exhaustive"].get(str(k), []), "top1"), - "width_median": median_of(row["exhaustive"].get(str(k), []), "width"), - } - for k in FLIP_COUNTS - }, - } - for row in case_rows - ], - "errors": errors, - "command": "python3 scripts/research/answer_flip_tolerance.py", - } - if not args.no_write: - REPORT_JSON.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps({"sampled": payload["sampled"], "errors": len(errors)}, ensure_ascii=False, indent=1)) - return 0 if not errors else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/cluster_width_probe.py b/scripts/research/cluster_width_probe.py deleted file mode 100644 index 96452b533..000000000 --- a/scripts/research/cluster_width_probe.py +++ /dev/null @@ -1,778 +0,0 @@ -#!/usr/bin/env python3 -"""Offline probe: why delivered rectification ranges equal the search window. - -Reads production scoring and clustering. Does not change their defaults. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import traceback -from dataclasses import dataclass -from datetime import date -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import AYANAMSA, NODE_MODE # noqa: E402 -from scripts.rectification.candidate_contrast import SIGNATURE_LAYERS # noqa: E402 -from scripts.rectification.event_probes import discriminating_event_probes # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, -) -from scripts.research.cluster_width_lib import ( # noqa: E402 - DEFAULT_MAX_CLUSTERS, - SEPARATION_LEAD, - cluster_of, - delivery_from_public, - layer_change_counts, - merge_adjacent_traced, - metrics_bundle, - minute_mass_from_public, - public_from_clusters, - raw_signature_clusters, - shannon_entropy, - smallest_mass_interval, - still_valid_public, - truth_cluster_independent, -) -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - apply_answer, - optimal_answer, -) - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -PREV_JSON = ROOT / "docs" / "research" / "minute_resolution_2026_09_14.json" -PREV_MD = ROOT / "docs" / "research" / "minute_resolution_2026_09_14.md" -REPORT_MD = ROOT / "docs" / "research" / "cluster_width_2026_09_14.md" -REPORT_JSON = ROOT / "docs" / "research" / "cluster_width_2026_09_14.json" -TODAY = date(2026, 9, 14) -RADII = (10, 30, 60) -WINDOW_BY_RADIUS = {10: 21, 30: 61, 60: 121} -ASK = ASK_COUNT -ERRATA_MARKER = "## 勘误(2026-09-14 簇宽度研究)" - - -@dataclass(frozen=True) -class Variant: - name: str - max_clusters: int | None = DEFAULT_MAX_CLUSTERS - max_peak_delta: float | None = None - mass: float | None = None - - @property - def kind(self) -> str: - if self.mass is not None: - return "W3" - if self.max_peak_delta is not None: - return "W2" - if self.max_clusters != DEFAULT_MAX_CLUSTERS: - return "W1" - return "baseline" - - -def all_variants() -> list[Variant]: - return [ - Variant("baseline"), - Variant("W1@128", max_clusters=128), - Variant("W1@none", max_clusters=None), - Variant("W2@1", max_peak_delta=1.0), - Variant("W2@2", max_peak_delta=2.0), - Variant("W2@4", max_peak_delta=4.0), - Variant("W2@8", max_peak_delta=8.0), - Variant("W3@0.7", mass=0.70), - Variant("W3@0.8", mass=0.80), - Variant("W3@0.9", mass=0.90), - ] - - -def previous_sweep_width_is_full_window(baseline: dict[str, Any]) -> bool: - for radius, expected in WINDOW_BY_RADIUS.items(): - row = baseline.get(str(radius)) or baseline.get(radius) - if not isinstance(row, dict): - return False - width = row.get("width_median") - if width is None or abs(float(width) - expected) > 1e-9: - return False - return True - - -def verdict(baseline: dict[str, Any], candidate: dict[str, Any]) -> str: - if baseline.get("n") == 0 or candidate.get("n") == 0: - return "uncertain" - needed = ("top1", "coverage", "width_median", "independent") - if any(candidate.get(key) is None or baseline.get(key) is None for key in needed): - return "uncertain" - cover_ok = candidate["coverage"] + 1e-9 >= baseline["coverage"] - squeezed_ok = candidate.get("squeezed", 0) <= baseline.get("squeezed", 0) - hit_ok = candidate["top1"] + 1e-9 >= baseline["top1"] - if not cover_ok or not squeezed_ok: - return "no_benefit" - width_down = candidate["width_median"] < baseline["width_median"] - 1e-9 - independent_up = candidate["independent"] >= baseline["independent"] + 0.10 - 1e-12 - if (width_down or independent_up) and hit_ok: - return "benefit" - if hit_ok and abs(candidate["width_median"] - baseline["width_median"]) <= 1e-9: - if abs(candidate["independent"] - baseline["independent"]) <= 1e-9: - return "no_benefit" - if not hit_ok: - return "no_benefit" - return "uncertain" - - -def _score_map(rows: Sequence[dict[str, Any]]) -> dict[str, float]: - return {str(row["time"])[:5]: float(row.get("score") or 0) for row in rows if str(row.get("time"))} - - -def _by_time_rows(rows: Sequence[dict[str, Any]]) -> dict[str, dict[str, Any]]: - return {str(row["time"])[:5]: row for row in rows if str(row.get("time"))} - - -def replay_public( - *, - probes: Sequence[dict[str, Any]], - public: Sequence[dict[str, Any]], - prior: dict[str, float], - true_time: str, -) -> dict[str, Any]: - reps = [str(row["time"])[:5] for row in public] - asked = list(probes)[:ASK] - scores = {time: prior.get(time, 0.0) for time in reps} - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - curve = [shannon_entropy(max(scores[time], 0.0) for time in reps if time not in eliminated)] - for probe in asked: - answer = optimal_answer(probe, true_time) - if answer is None: - curve.append(curve[-1] if curve else 0.0) - continue - scores, conflicts, eliminated = apply_answer( - scores, conflicts, eliminated, probe, answer, reps, - ) - curve.append(shannon_entropy( - max(scores.get(time, 0.0), 0.0) for time in reps if time not in eliminated - )) - return { - "scores": scores, - "eliminated": sorted(eliminated), - "asked": len(asked), - "probes": len(probes), - "entropy": curve, - "true_alive": true_time not in eliminated and any( - true_time in (row.get("cluster_times") or [str(row.get("time"))[:5]]) - for row in public - if str(row.get("time"))[:5] not in eliminated - ), - } - - -def delivery_for_variant( - variant: Variant, - public: Sequence[dict[str, Any]], - scores: dict[str, float], - eliminated: set[str], -) -> dict[str, Any]: - valid = still_valid_public(public, scores, eliminated, lead=SEPARATION_LEAD) - union = delivery_from_public(valid) - if variant.mass is None: - return { - "mode": "union_lead8", - **union, - "valid_count": len(valid), - } - mass = minute_mass_from_public(valid, scores) - interval = smallest_mass_interval(mass, variant.mass) - return { - "mode": f"mass_{variant.mass}", - "times": interval["times"], - "width": interval["width"], - "start": interval["start"], - "end": interval["end"], - "valid_count": len(valid), - "mass_share": interval["mass_share"], - } - - -def score_variant( - *, - raw_clusters: Sequence[dict[str, Any]], - rows: Sequence[dict[str, Any]], - variant: Variant, - true_time: str, - window_times: Sequence[str], - probes: Sequence[dict[str, Any]], -) -> dict[str, Any]: - by_time = _by_time_rows(rows) - merged, trace = merge_adjacent_traced( - raw_clusters, - by_time, - max_clusters=variant.max_clusters, - max_peak_delta=variant.max_peak_delta, - ) - public = public_from_clusters(merged, rows) - for row in public: - row["score"] = float(row.get("score") or 0) - prior = {str(row["time"])[:5]: float(row.get("score") or 0) for row in public} - independent = truth_cluster_independent(true_time, raw_clusters, merged) - engine_union = delivery_from_public(public) - engine_delivery = delivery_for_variant(variant, public, prior, set()) - engine = metrics_bundle( - public=public, - true_time=true_time, - window_times=window_times, - delivery_times=engine_delivery["times"], - delivery_width=engine_delivery["width"], - independent=independent, - ) - replay = replay_public( - probes=probes, - public=public, - prior=prior, - true_time=true_time, - ) - posterior_public = [] - for row in public: - stamp = str(row["time"])[:5] - posterior_public.append({**row, "score": replay["scores"].get(stamp, row["score"])}) - replay_delivery = delivery_for_variant( - variant, posterior_public, replay["scores"], set(replay["eliminated"]), - ) - replay_union = delivery_from_public( - still_valid_public(posterior_public, replay["scores"], set(replay["eliminated"]), lead=None), - ) - replay_metrics = metrics_bundle( - public=[row for row in posterior_public if str(row["time"])[:5] not in set(replay["eliminated"])], - true_time=true_time, - window_times=window_times, - delivery_times=replay_delivery["times"], - delivery_width=replay_delivery["width"], - independent=independent, - entropy_scores=[ - replay["scores"].get(str(row["time"])[:5], 0.0) - for row in posterior_public - if str(row["time"])[:5] not in set(replay["eliminated"]) - ], - ) - deltas = [item["delta"] for item in trace] - return { - "engine": engine, - "engine_union_width": engine_union["width"], - "engine_delivery": {key: engine_delivery[key] for key in ("mode", "width", "start", "end", "valid_count")}, - "replay": { - **replay_metrics, - "asked": replay["asked"], - "probes": replay["probes"], - "entropy_curve": replay["entropy"], - "eliminated_count": len(replay["eliminated"]), - "true_alive": replay["true_alive"], - "union_alive_width": replay_union["width"], - }, - "independent": independent, - "raw_clusters": len(raw_clusters), - "merged_clusters": len(merged), - "merge_count": len(trace), - "merge_deltas": deltas, - "merge_delta_median": statistics.median(deltas) if deltas else None, - "true_raw_size": len((cluster_of(true_time, raw_clusters) or {}).get("times") or []), - "true_merged_size": len((cluster_of(true_time, merged) or {}).get("times") or []), - } - - -def summarize(rows: Sequence[dict[str, Any]], *, stage: str) -> dict[str, Any]: - if not rows: - return { - "n": 0, "top1": None, "coverage": None, "width_median": None, "tie": None, - "entropy0": None, "entropy6": None, "squeezed": None, "independent": None, - "public_median": None, "merge_median": None, "raw_median": None, - } - if stage == "engine": - payloads = [row["engine"] for row in rows] - entropy6 = None - else: - payloads = [row["replay"] for row in rows] - entropy6 = [ - (row["replay"].get("entropy_curve") or [None])[-1] - for row in rows - ] - entropy6 = [item for item in entropy6 if item is not None] - widths = [item["width"] for item in payloads if item.get("width") is not None] - return { - "n": len(rows), - "top1": round(sum(1 for item in payloads if item["top1_hit"]) / len(rows), 4), - "coverage": round(sum(1 for item in payloads if item["coverage"]) / len(rows), 4), - "width_median": statistics.median(widths) if widths else None, - "tie": round(sum(1 for item in payloads if item["tie"]) / len(rows), 4), - "entropy0": round(sum(row["engine"]["entropy"] for row in rows) / len(rows), 4), - "entropy6": round(sum(entropy6) / len(entropy6), 4) if entropy6 else None, - "squeezed": sum(1 for item in payloads if item["truth_squeezed"]), - "independent": round(sum(1 for row in rows if row["independent"]) / len(rows), 4), - "public_median": statistics.median([row["merged_clusters"] for row in rows]), - "merge_median": statistics.median([row["merge_count"] for row in rows]), - "raw_median": statistics.median([row["raw_clusters"] for row in rows]), - "elim_median": statistics.median([row["replay"]["eliminated_count"] for row in rows]), - "union_alive_median": statistics.median([ - row["replay"]["union_alive_width"] - for row in rows - if row["replay"].get("union_alive_width") is not None - ]) if stage == "replay" else None, - "engine_union_median": statistics.median([ - row["engine_union_width"] for row in rows if row.get("engine_union_width") is not None - ]), - } - - -def md_table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) -> str: - def cell(value: Any) -> str: - if value is None: - return "—" - if isinstance(value, float): - return f"{value:.3f}".rstrip("0").rstrip(".") - return str(value) - - line = "| " + " | ".join(headers) + " |" - sep = "| " + " | ".join("---" if index == 0 else "---:" for index in range(len(headers))) + " |" - body = ["| " + " | ".join(cell(item) for item in row) + " |" for row in rows] - return "\n".join([line, sep, *body]) - - -def load_previous_m0() -> dict[str, Any]: - if not PREV_JSON.exists(): - return {"present": False} - payload = json.loads(PREV_JSON.read_text(encoding="utf-8")) - remaining: dict[str, list[int]] = {} - alive: dict[str, int] = {} - for radius, variants in (payload.get("results") or {}).items(): - rows = variants.get("baseline") or [] - remaining[str(radius)] = [int(row.get("replay", {}).get("remaining_count") or 0) for row in rows] - alive[str(radius)] = sum(1 for row in rows if row.get("replay", {}).get("true_alive")) - return { - "present": True, - "baseline": payload.get("baseline") or {}, - "full_window": previous_sweep_width_is_full_window(payload.get("baseline") or {}), - "remaining_median": { - radius: statistics.median(values) if values else None - for radius, values in remaining.items() - }, - "true_alive": alive, - "case_count": payload.get("case_count"), - } - - -def append_previous_errata(m0: dict[str, Any], elim_summaries: dict[str, Any]) -> None: - if not PREV_MD.exists(): - return - text = PREV_MD.read_text(encoding="utf-8") - if ERRATA_MARKER in text: - start = text.index(ERRATA_MARKER) - text = text[:start].rstrip() + "\n" - lines = [ - "", - ERRATA_MARKER, - "", - "上一轮表里的「区间宽度中位」取的是**全部公开簇成员的并集跨度**,没有把答案淘汰算进去。", - "`scripts/research/minute_resolution_sweep.py` 的 `metrics_from_public` 遍历每一个公开簇的 `cluster_times`;", - "`cap_clusters_by_adjacent_merge` 按设计不丢分钟,所以并集恒等于搜索窗。六题回放虽然调用了 `apply_answer`,", - "但 `summarize()` 仍读 `engine.width`,回放里的 `remaining_count` 还是代表分钟封顶 5,不是交付区间宽度。", - "", - "因此「所有方案宽度中位数都等于整窗」只对**不含淘汰的引擎并集口径**成立,不能直接当成线上范围卡在答完题之后的宽度。", - "线上 `unionStillValidRange` 用的是未淘汰且落后头名不足 8 分的簇覆盖并集。含淘汰后的数字见 `docs/research/cluster_width_2026_09_14.md`。", - "", - "| 半径 | 上一轮宽度中位(无淘汰) | 六题后线上口径宽度中位 | 真值仍在回放剩余代表里 |", - "| --- | ---: | ---: | ---: |", - ] - previous = m0.get("baseline") or {} - for radius in RADII: - old = (previous.get(str(radius)) or {}).get("width_median") - new = (elim_summaries.get(str(radius)) or {}).get("width_median") - alive = (m0.get("true_alive") or {}).get(str(radius)) - n = (previous.get(str(radius)) or {}).get("n") or m0.get("case_count") - alive_cell = "—" if alive is None or n is None else f"{alive}/{n}" - lines.append(f"| ±{radius} | {old if old is not None else '—'} | {new if new is not None else '—'} | {alive_cell} |") - lines.append("") - PREV_MD.write_text(text.rstrip() + "\n" + "\n".join(lines) + "\n", encoding="utf-8") - - -def _w3_squeeze_rows(payload: dict[str, Any]) -> list[str]: - found: list[str] = [] - for radius_key, variants in (payload.get("results") or {}).items(): - for name, rows in variants.items(): - if not str(name).startswith("W3"): - continue - for row in rows: - if row.get("replay", {}).get("truth_squeezed"): - found.append(f"{name} ±{radius_key} `{row['case_id']}`") - return found - - -def write_report(payload: dict[str, Any]) -> None: - m0 = payload["m0"] - squeezed_rows = _w3_squeeze_rows(payload) - by_radius = payload.get("by_radius") or {} - replay10 = by_radius.get("10", {}).get("baseline", {}).get("replay", {}) - replay30 = by_radius.get("30", {}).get("baseline", {}).get("replay", {}) - replay60 = by_radius.get("60", {}).get("baseline", {}).get("replay", {}) - if not payload.get("w3_squeeze_note"): - payload["w3_squeeze_note"] = ( - "±10 / ±60 能收窄且覆盖不降;±30 的 0.7/0.8 覆盖下降。" - + (" 挤出:" + ";".join(squeezed_rows) if squeezed_rows else "") - ) - if not payload.get("lead"): - payload["lead"] = ( - "读数字时先看 M0:**上一轮「宽度中位 = 整窗」是测量口径,不是线上答完题之后的行为。** " - "不含淘汰时并集确实恒等于搜索窗(21 / 61 / 121);按线上 `unionStillValidRange` 做六题淘汰后," - f"宽度中位已经是 **{replay10.get('width_median')} / {replay30.get('width_median')} / {replay60.get('width_median')}**," - "真值覆盖仍是 20/20。合并在步长 2 的三档半径上不会触发(簇数低于 64)。" - ) - lines = [ - "# 交付区间宽度与簇合并测量(2026-09-14)", - "", - f"- 口径:ayanamsa `{payload['ayanamsa']}`,node mode `{payload['node_mode']}`。不得与上游 true-node 数字直接对比。", - f"- 数据:`{payload['holdout']}`,{payload['case_count']} 例公开 Rodden-AA。", - f"- 半径:{', '.join(f'±{item}' for item in payload['radii'])},步长 {payload['minute_step']} 分钟。", - "- 性质:离线测量。生产 `candidate_contrast.py` / `scoring_service.py` / `active_rectification_event_engine.py` 默认值未改。", - "- 线上对照:`unionStillValidRange` = 未淘汰且落后头名不足 8 分的簇覆盖并集(`MIN_SEPARATION_LEAD = 8`)。", - "", - "## 结论", - "", - ] - overall = payload["verdicts"] - labels = [row["verdict"] for row in overall.values()] - if labels and all(item == "benefit" for item in labels): - headline = "**有改法过门,见下表推荐参数。** 线上默认簇上限与并集交付先不动,另立实现单。" - elif labels and all(item == "no_benefit" for item in labels): - headline = "**无收益,不立实现单。** 线上 `MAX_PUBLIC_CLUSTERS=64` 与簇并集交付保持不动。" - else: - headline = "**不确定,不立实现单。** 线上 `MAX_PUBLIC_CLUSTERS=64` 与「公开簇并集」交付保持不动。" - payload["headline"] = headline - lines.append(headline) - lines.append("") - lines.append("| 改法 | 判定 | 要点 |") - lines.append("| --- | --- | --- |") - lines.append("| **W1 提高簇上限** | 无收益 | 本网格合并次数全是 0,改上限与基线相同 |") - lines.append("| **W2 按分差拒绝合并** | 无收益 | 同上,合并不触发,分差门槛无事可拒 |") - squeezed_note = payload.get("w3_squeeze_note") or "见分半径表" - lines.append(f"| **W3 分位覆盖区间** | 不确定 | {squeezed_note} |") - lines.append("") - if payload.get("lead"): - lines.append(payload["lead"]) - lines.append("") - lines.append("过运与三大外部引擎未参与本单(纯聚类/交付口径,不解释运势)。") - lines.append("") - lines.append("| 改法 | 判定 | 说明 |") - lines.append("| --- | --- | --- |") - for name, row in overall.items(): - lines.append(f"| {name} | **{row['verdict']}** | {row['note']} |") - lines.extend(["", "## M0 · 上一轮宽度口径", ""]) - if m0.get("present"): - lines.append( - "上一轮 `width_median` **不含淘汰**,取全部公开簇并集。公开簇划分整个搜索窗且合并从不丢分钟," - "所以该口径下宽度等于整窗是恒等式。" - ) - lines.append("") - m0_rows = [] - for radius in payload["radii"]: - prev = (m0.get("baseline") or {}).get(str(radius), {}) - engine = payload["by_radius"][str(radius)]["baseline"]["engine"] - replay = payload["by_radius"][str(radius)]["baseline"]["replay"] - m0_rows.append([ - f"±{radius}", - prev.get("width_median"), - engine.get("engine_union_median"), - replay.get("union_alive_median"), - replay.get("width_median"), - replay.get("squeezed"), - ]) - lines.append(md_table( - ["半径", "上一轮宽度(无淘汰)", "本轮引擎并集", "六题后未淘汰并集", "六题后线上口径(lead 8)", "真值挤出"], - m0_rows, - )) - else: - lines.append("未找到上一轮 JSON,无法对照。") - lines.extend(["", "## M1 · 簇结构画像(生产合并,max=64)", ""]) - portrait_rows = [] - for radius in payload["radii"]: - portrait = payload["portrait"][str(radius)] - portrait_rows.append([ - f"±{radius}", - portrait["raw_median"], - portrait["merge_median"], - portrait["merged_median"], - portrait["independent"], - portrait["candidates_median"], - ", ".join(portrait["constant_layers"]) or "无", - ]) - lines.append(md_table( - ["半径", "合并前簇数中位", "合并次数中位", "合并后簇数中位", "真值簇独立率", "窗内候选中位", "±10 内恒定层"], - portrait_rows, - )) - lines.append("") - lines.append(payload["portrait_note"]) - lines.append("") - raw_max = [] - for radius in payload["radii"]: - rows = (payload.get("results") or {}).get(str(radius), {}).get("baseline") or [] - raw_max.append(max((int(row["raw_clusters"]) for row in rows), default=0)) - if raw_max: - lines.append( - f"签名簇最多 {max(raw_max)},仍低于 64。真值簇独立率在三档半径上都是 20/20。" - "±10 窗内 `md` 恒定;变化最多的是 `d24`。" - ) - lines.extend(["", "### ±10 签名层变化", ""]) - layer_rows = [] - for layer, stats in payload["layers_pm10"].items(): - layer_rows.append([ - layer, - stats["unique_median"], - stats["changes_median"], - stats["constant_share"], - ]) - lines.append(md_table(["层", "取值种数中位", "相邻变化次数中位", "窗内恒定比例"], layer_rows)) - lines.extend(["", "## M2 · 三个改法(六题后线上口径)", ""]) - for radius in payload["radii"]: - lines.append(f"### ±{radius} 分钟") - lines.append("") - table = [] - for name, stages in payload["by_radius"][str(radius)].items(): - summary = stages["replay"] - table.append([ - name, - summary["top1"], - summary["coverage"], - summary["width_median"], - summary["tie"], - summary["independent"], - summary["public_median"], - summary["squeezed"], - ]) - lines.append(md_table( - ["方案", "头名簇命中", "区间覆盖", "宽度中位", "并列率", "真值簇独立率", "公开簇中位", "挤出"], - table, - )) - lines.append("") - if squeezed_rows: - lines.append( - "W3 挤出的例子:" + ";".join(squeezed_rows) - + "。任务书硬红线「不得为了把宽度做窄而牺牲真值覆盖率」,所以 W3 不能直接上线。" - ) - lines.append("") - lines.extend([ - "## 方法", - "", - "1. 每个例子走生产 `build_event_contribution_matrix` + `score_from_matrix`,再按签名层聚簇。", - "2. 合并实现复刻 `cap_clusters_by_adjacent_merge`,研究脚本内可改上限或加分差门槛,不改线上模块。", - "3. 引擎并集 = 全部公开簇 `cluster_times` 的 min–max(上一轮口径)。", - "4. 线上口径 = 对公开代表做六题最优答淘汰,再取落后头名不足 8 分的簇覆盖并集。", - "5. W3 在同一组仍然有效簇上,取覆盖 posterior 质量 70/80/90% 的最短连续钟面区间。", - "6. 真值簇独立 = 真分钟所在的合并前签名簇,合并后成员集合不变。", - "", - f"错误 {len(payload.get('errors') or [])} 例。{payload.get('case_count', 0)} 例跑完。", - "", - ]) - REPORT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8") - REPORT_JSON.write_text(json.dumps(payload, ensure_ascii=True, indent=2) + "\n", encoding="utf-8") - - -def portrait_from_baseline(rows: Sequence[dict[str, Any]], layers: Sequence[dict[str, Any]]) -> dict[str, Any]: - constant = [] - if layers: - shares = {} - for layer in SIGNATURE_LAYERS: - shares[layer] = sum(1 for item in layers if item.get(layer, {}).get("constant")) / len(layers) - constant = [layer for layer, share in shares.items() if share >= 0.8] - return { - "raw_median": statistics.median([row["raw_clusters"] for row in rows]) if rows else None, - "merge_median": statistics.median([row["merge_count"] for row in rows]) if rows else None, - "merged_median": statistics.median([row["merged_clusters"] for row in rows]) if rows else None, - "independent": round(sum(1 for row in rows if row["independent"]) / len(rows), 4) if rows else None, - "candidates_median": statistics.median([row["engine"]["window_width"] for row in rows]) if rows else None, - "constant_layers": constant, - } - - -def run(args: argparse.Namespace) -> dict[str, Any]: - holdout = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(holdout["cases"]) - if args.limit: - cases = cases[: args.limit] - radii = tuple(int(item) for item in args.radii) - variants = all_variants() - results: dict[str, dict[str, list[dict[str, Any]]]] = { - str(radius): {variant.name: [] for variant in variants} for radius in radii - } - layers_pm10: list[dict[str, Any]] = [] - errors: list[dict[str, Any]] = [] - for case in cases: - case_id = case["case_id"] - true_time = str(case["birth"]["time"])[:5] - print(f"case {case_id}", flush=True) - try: - for radius in radii: - request = scoring_request_for(case, radius) - built = build_event_contribution_matrix(request) - rows = score_from_matrix(request, built) - contexts = list(built.get("static_contexts") or []) - window_times = [str(row["time"])[:5] for row in rows] - raw = raw_signature_clusters(contexts) - layer_stats = layer_change_counts(contexts) - if radius == 10: - layers_pm10.append({"case_id": case_id, **layer_stats}) - probes = discriminating_event_probes( - {**request, "refresh_probes": False}, - built, - scan=window_scan(built), - candidate_times=list(window_times), - representative_time=true_time, - today=TODAY, - ) - print( - f" radius ±{radius} candidates={len(window_times)} raw_clusters={len(raw)} probes={len(probes)}", - flush=True, - ) - for variant in variants: - scored = score_variant( - raw_clusters=raw, - rows=rows, - variant=variant, - true_time=true_time, - window_times=window_times, - probes=probes, - ) - scored["case_id"] = case_id - results[str(radius)][variant.name].append(scored) - except Exception as exc: # noqa: BLE001 - errors.append({ - "case_id": case_id, - "error": f"{type(exc).__name__}: {exc}", - "trace": traceback.format_exc(), - }) - print(f" FAIL {case_id}: {exc}", flush=True) - by_radius: dict[str, dict[str, dict[str, Any]]] = {} - portrait: dict[str, Any] = {} - for radius in radii: - by_radius[str(radius)] = {} - for variant in variants: - rows = results[str(radius)][variant.name] - by_radius[str(radius)][variant.name] = { - "engine": summarize(rows, stage="engine"), - "replay": summarize(rows, stage="replay"), - } - portrait[str(radius)] = portrait_from_baseline(results[str(radius)]["baseline"], layers_pm10 if radius == 10 else []) - layer_summary = {} - for layer in SIGNATURE_LAYERS: - unique = [item[layer]["unique"] for item in layers_pm10] - changes = [item[layer]["changes"] for item in layers_pm10] - constant = [item[layer]["constant"] for item in layers_pm10] - layer_summary[layer] = { - "unique_median": statistics.median(unique) if unique else None, - "changes_median": statistics.median(changes) if changes else None, - "constant_share": round(sum(constant) / len(constant), 4) if constant else None, - } - merge_never = all((portrait[str(radius)]["merge_median"] or 0) == 0 for radius in radii) - if merge_never: - portrait_note = ( - "三档半径上合并次数中位都是 0:步长 2 分钟时候选数最多 61,低于 `MAX_PUBLIC_CLUSTERS=64`," - "`cap_clusters_by_adjacent_merge` 根本不会触发。宽度等于整窗,是因为公开簇**划分**了整个窗口,不是因为弱簇被并回去。" - ) - else: - portrait_note = "合并确实发生了。下面看被合并的分差和真值簇是否还独立。" - verdicts: dict[str, dict[str, str]] = {} - names = [variant.name for variant in variants if variant.name != "baseline"] - for name in names: - notes = [] - labels = [] - for radius in radii: - base = by_radius[str(radius)]["baseline"]["replay"] - cand = by_radius[str(radius)][name]["replay"] - label = verdict(base, cand) - labels.append(label) - notes.append(f"±{radius}:{label}") - if all(item == "benefit" for item in labels): - final = "benefit" - elif all(item == "no_benefit" for item in labels): - final = "no_benefit" - else: - final = "uncertain" - verdicts[name] = {"verdict": final, "note": ";".join(notes)} - squeezed_rows = [] - for radius_key, variants in results.items(): - for name, rows in variants.items(): - if not str(name).startswith("W3"): - continue - for row in rows: - if row.get("replay", {}).get("truth_squeezed"): - squeezed_rows.append(f"{name} ±{radius_key} `{row['case_id']}`") - if any(row["verdict"] == "benefit" for row in verdicts.values()): - headline = "**有改法过门,见下表推荐参数。** 线上默认簇上限与并集交付先不动,另立实现单。" - elif all(row["verdict"] == "no_benefit" for row in verdicts.values()): - headline = "**无收益,不立实现单。** 线上 `MAX_PUBLIC_CLUSTERS=64` 与簇并集交付保持不动。" - else: - headline = "**不确定,不立实现单。** 线上 `MAX_PUBLIC_CLUSTERS=64` 与「公开簇并集」交付保持不动。" - w3_squeeze_note = ( - "±10 / ±60 能收窄且覆盖不降;±30 的 0.7/0.8 覆盖下降。" - + (" 挤出:" + ";".join(squeezed_rows) if squeezed_rows else "") - ) - replay10 = by_radius.get("10", {}).get("baseline", {}).get("replay", {}) - replay30 = by_radius.get("30", {}).get("baseline", {}).get("replay", {}) - replay60 = by_radius.get("60", {}).get("baseline", {}).get("replay", {}) - lead = ( - "读数字时先看 M0:**上一轮「宽度中位 = 整窗」是测量口径,不是线上答完题之后的行为。** " - "不含淘汰时并集确实恒等于搜索窗(21 / 61 / 121);按线上 `unionStillValidRange` 做六题淘汰后," - f"宽度中位已经是 **{replay10.get('width_median')} / {replay30.get('width_median')} / {replay60.get('width_median')}**," - "真值覆盖仍是 20/20。合并在步长 2 的三档半径上不会触发(簇数低于 64)。" - ) - m0 = load_previous_m0() - payload = { - "generated_at": TODAY.isoformat(), - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "holdout": str(HOLDOUT.relative_to(ROOT)).replace("\\", "/"), - "case_count": len(cases), - "radii": list(radii), - "minute_step": MINUTE_STEP, - "separation_lead": SEPARATION_LEAD, - "headline": headline, - "lead": lead, - "w3_squeeze_note": w3_squeeze_note, - "m0": m0, - "portrait": portrait, - "portrait_note": portrait_note, - "layers_pm10": layer_summary, - "by_radius": by_radius, - "verdicts": verdicts, - "errors": errors, - "results": results, - } - write_report(payload) - elim = { - str(radius): by_radius[str(radius)]["baseline"]["replay"] - for radius in radii - } - append_previous_errata(m0, elim) - return payload - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", nargs="+", default=[str(item) for item in RADII]) - args = parser.parse_args() - payload = run(args) - print( - f"wrote {REPORT_MD} cases={payload['case_count']} errors={len(payload['errors'])}", - flush=True, - ) - return 0 if not payload["errors"] else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/fewer_probes_card_replay.py b/scripts/research/fewer_probes_card_replay.py deleted file mode 100644 index b07c2cb81..000000000 --- a/scripts/research/fewer_probes_card_replay.py +++ /dev/null @@ -1,274 +0,0 @@ -#!/usr/bin/env python3 -"""Offline replay for TASK-rectification-fewer-probes-card-20260926 (D1/D2). - -Same method as `guided_collect_holdout_replay.py` (the script behind -`docs/research/guided_collect_holdout_2026_09_16.json`): v4 open holdout -(public AA cases), six discriminating probes answered from the true minute, -then guided window events injected on the true candidate's own boundary date -(`truth`) or on the furthest remaining candidate's (`opposite`, control). - -What differs is the question being asked. The 09-16 replay stopped at the -first injection that met the precision gate ("how many events to the gate"). -This replay models the production delivery rule on both sides and compares -the **final delivered range**: - -* before — `GUIDED_COLLECT_LIMIT = 6` and the card waits until the guided pool - is asked out (BUG-751 D6): every window in the receipt is asked. -* after — at most two guided windows per Case (D1, enforced in the frontend - pool as `GUIDED_WINDOW_CASE_LIMIT = 2`; the engine list stays at - `GUIDED_COLLECT_LIMIT = 6` because `event_probes.py` is part of the frozen - scoring identity); once the targeted seven and their one re-ask are asked - the card is delivered whether or not the gate is met (D2). Windows are asked - before the targeted lines, so the first two windows of the receipt are - still asked. - -The targeted seven lines are identical on both sides and are not modelled; the -question count below is six probes plus the guided windows asked. - -Metrics per radius: truth-in-delivered-range rate, median delivered width, -mean questions asked. Not a merge gate by itself; the numbers go in -`docs/tasks/PROGRESS-rectification-fewer-probes-card-20260926.md`. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import time -import traceback -from datetime import date -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - NODE_MODE, - compute_candidate_static_contexts, -) -from scripts.rectification.event_probes import ( # noqa: E402 - GUIDED_COLLECT_LIMIT, - discriminating_event_probes, - guided_collect_windows, -) -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) -from scripts.research.guided_collect_holdout_replay import ( # noqa: E402 - RADII, - TODAY, - _hhmm, - _minutes, - load_cases, - posterior_state, - precision_gate, - remaining_times, - synthetic_event, - window_boundary_dates, -) -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.probe_supply_after_six import ASK_COUNT # noqa: E402 - -REPORT_JSON = ROOT / "docs" / "research" / "fewer_probes_card_replay_2026_09_26.json" -#: Engine receipt cap (unchanged) and the frontend per-Case cap (D1). -BEFORE_LIMIT = GUIDED_COLLECT_LIMIT -AFTER_LIMIT = 2 # frontend `GUIDED_WINDOW_CASE_LIMIT` - - -def _outcome(state: dict[str, Any], true_time: str) -> dict[str, Any]: - delivery = state["delivery"] - start, end = delivery.get("start"), delivery.get("end") - inside = ( - start is not None - and end is not None - and _minutes(start) <= _minutes(true_time) <= _minutes(end) - ) - gate = precision_gate(state["valid"], state["scores"]) - return { - "start": start, - "end": end, - "width": delivery.get("width"), - "truth_in_range": bool(inside), - "truth_eliminated": true_time in state["eliminated"], - "gate_met": bool(gate["met"]), - "gap": gate["gap"], - "percents": gate["percents"], - } - - -def evaluate_case(case: dict[str, Any], radius: int, direction: str) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - request = scoring_request_for(case, radius) - request["ayanamsa"] = AYANAMSA - request["node_mode"] = NODE_MODE - request["minute_step"] = MINUTE_STEP - static_contexts = compute_candidate_static_contexts(request) - built = build_event_contribution_matrix(request, static_contexts=static_contexts) - rows = score_from_matrix(request, built) - times = [stamp for row in rows if (stamp := _hhmm(row.get("time")))] - probes = discriminating_event_probes( - {**request, "refresh_probes": False, "asked_probe_keys": []}, - built, - scan=window_scan(built), - candidate_times=times, - representative_time=true_time, - today=TODAY, - )[:ASK_COUNT] - state = posterior_state(rows=rows, contexts=static_contexts, probes=probes, true_time=true_time) - after_six = _outcome(state, true_time) - pool = remaining_times(state) or times - windows_before = guided_collect_windows(request, built, candidate_times=pool, today=TODAY) - # D1: the Case asks the first two windows of the receipt, in receipt order. - windows_after = windows_before[:AFTER_LIMIT] - boundaries = window_boundary_dates(request, built, candidate_times=pool, today=TODAY) - if direction == "truth": - source_time = true_time - else: - source_time = max(pool, key=lambda stamp: abs(_minutes(stamp) - _minutes(true_time))) if pool else true_time - - def inject(windows: Sequence[dict[str, Any]]) -> dict[str, Any]: - extras: list[dict[str, Any]] = [] - for index, window in enumerate(windows): - key = (int(window["year"]), int(window["month_lo"]), int(window["month_hi"])) - per_time = boundaries.get(key) or {} - when = per_time.get(source_time) - if when is None and per_time: - when = per_time[min(per_time, key=lambda stamp: abs(_minutes(stamp) - _minutes(source_time)))] - if when is None: - when = date(int(window["year"]), int(window["month_lo"]), 1) - extras.append(synthetic_event(window, index, when=when)) - if not extras: - return after_six - injected = scoreable_request({**request, "events": list(request["events"]) + extras}) - rebuilt = build_event_contribution_matrix(injected, static_contexts=static_contexts) - new_rows = score_from_matrix(injected, rebuilt) - final = posterior_state(rows=new_rows, contexts=static_contexts, probes=probes, true_time=true_time) - return _outcome(final, true_time) - - before = inject(windows_before) - after = inject(windows_after) - return { - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "windows_before": len(windows_before), - "windows_after": len(windows_after), - "questions_before": ASK_COUNT + len(windows_before), - "questions_after": ASK_COUNT + len(windows_after), - "after_six": after_six, - "before": before, - "after": after, - "same_range": (before["start"], before["end"]) == (after["start"], after["end"]), - } - - -def _median(values: Sequence[float]) -> float | None: - return statistics.median(values) if values else None - - -def summarize(rows: Sequence[dict[str, Any]], radius: int, direction: str) -> dict[str, Any]: - subset = [ - row for row in rows - if row.get("radius") == radius and row.get("direction") == direction and not row.get("error") - ] - n = len(subset) - - def side(name: str) -> dict[str, Any]: - widths = [row[name]["width"] for row in subset if row[name]["width"] is not None] - return { - "truth_in_range": sum(1 for row in subset if row[name]["truth_in_range"]), - "truth_in_range_rate": round(sum(1 for row in subset if row[name]["truth_in_range"]) / n, 4) if n else None, - "median_width": _median(widths), - "gate_met": sum(1 for row in subset if row[name]["gate_met"]), - } - - return { - "radius": radius, - "direction": direction, - "n": n, - "after_six": side("after_six"), - "before": { - **side("before"), - "mean_questions": round(statistics.mean(row["questions_before"] for row in subset), 2) if n else None, - "mean_guided": round(statistics.mean(row["windows_before"] for row in subset), 2) if n else None, - }, - "after": { - **side("after"), - "mean_questions": round(statistics.mean(row["questions_after"] for row in subset), 2) if n else None, - "mean_guided": round(statistics.mean(row["windows_after"] for row in subset), 2) if n else None, - }, - "same_range_cases": sum(1 for row in subset if row["same_range"]), - "errors": sum( - 1 for row in rows - if row.get("radius") == radius and row.get("direction") == direction and row.get("error") - ), - } - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", default=",".join(str(item) for item in RADII)) - parser.add_argument("--directions", default="truth,opposite") - parser.add_argument("--json-out", default=str(REPORT_JSON)) - args = parser.parse_args() - radii = tuple(int(item) for item in str(args.radii).split(",") if item.strip()) - directions = tuple(item.strip() for item in str(args.directions).split(",") if item.strip()) - cases = load_cases() - if args.limit: - cases = cases[: args.limit] - started = time.perf_counter() - rows: list[dict[str, Any]] = [] - for case in cases: - for radius in radii: - for direction in directions: - label = f"{case.get('case_id')} ±{radius} {direction}" - try: - result = evaluate_case(case, radius, direction) - rows.append(result) - print( - f"{label} q={result['questions_before']}->{result['questions_after']} " - f"in={result['before']['truth_in_range']}->{result['after']['truth_in_range']} " - f"w={result['before']['width']}->{result['after']['width']} same={result['same_range']}", - flush=True, - ) - except Exception as exc: # noqa: BLE001 - rows.append({ - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "error": f"{type(exc).__name__}: {exc}", - "trace": traceback.format_exc(limit=8), - }) - print(f"{label} ERROR {type(exc).__name__}: {exc}", flush=True) - summaries = [summarize(rows, radius, direction) for radius in radii for direction in directions] - payload = { - "generated_at": TODAY.isoformat(), - "method": "guided_collect_holdout_replay.py (2026-09-16), final delivered range compared", - "holdout": "references/real_case_calibration/minute_rectification_holdout_v4.json", - "ask_count": ASK_COUNT, - "guided_collect_limit_before": BEFORE_LIMIT, - "guided_window_case_limit_after": AFTER_LIMIT, - "elapsed_s": round(time.perf_counter() - started, 1), - "summaries": summaries, - "rows": [{key: value for key, value in row.items() if key != "trace"} for row in rows], - "errors": [row for row in rows if row.get("error")], - } - out = Path(args.json_out) - out.parent.mkdir(parents=True, exist_ok=True) - out.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps(summaries, ensure_ascii=False, indent=2), flush=True) - print(f"wrote {out} in {payload['elapsed_s']}s", flush=True) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/futile_collect_stop_replay.py b/scripts/research/futile_collect_stop_replay.py deleted file mode 100644 index 572d9adc7..000000000 --- a/scripts/research/futile_collect_stop_replay.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python3 -"""Offline replay for TASK-rectification-futile-collect-stop-20260929 (D1). - -Hard red line 1: after the training gate opens, the Case no longer injects -spoken / guided events (targeted seven, skip re-ask, guided boundary windows). -Same method as `fewer_probes_card_replay.py` (v4 open holdout, six -discriminating probes answered from the true minute, guided windows injected -on the true candidate's own boundary date (`truth`) or on the furthest -remaining candidate's (`opposite`, control)). - -* baseline — production before D1: the first `GUIDED_WINDOW_CASE_LIMIT = 2` - guided windows of the receipt are asked and injected (`after` in - `fewer_probes_card_replay.py`). -* d1 — nothing is injected after the six probes (`after_six`). - -The targeted seven lines ask for events whose dates only a real person knows; -they cannot be modelled on the open holdout and are left out on both sides -(same as the 09-26 replay). This is an open-set replay, not a blind test. - -Gate: per radius x direction, d1 truth-in-range count >= baseline and d1 -median width <= baseline. Writes -`docs/research/futile_collect_stop_replay_2026_09_29.json`. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import time -import traceback -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.research.fewer_probes_card_replay import evaluate_case # noqa: E402 -from scripts.research.guided_collect_holdout_replay import RADII, load_cases # noqa: E402 - -REPORT_JSON = ROOT / "docs" / "research" / "futile_collect_stop_replay_2026_09_29.json" - - -def _median(values: Sequence[float]) -> float | None: - return statistics.median(values) if values else None - - -def summarize(rows: Sequence[dict[str, Any]], radius: int, direction: str) -> dict[str, Any]: - subset = [ - row for row in rows - if row.get("radius") == radius and row.get("direction") == direction and not row.get("error") - ] - n = len(subset) - - def side(name: str) -> dict[str, Any]: - widths = [row[name]["width"] for row in subset if row[name]["width"] is not None] - inside = sum(1 for row in subset if row[name]["truth_in_range"]) - return { - "truth_in_range": inside, - "truth_in_range_rate": round(inside / n, 4) if n else None, - "median_width": _median(widths), - } - - baseline = side("after") - d1 = side("after_six") - passed = ( - n > 0 - and d1["truth_in_range"] >= baseline["truth_in_range"] - and d1["median_width"] is not None - and baseline["median_width"] is not None - and d1["median_width"] <= baseline["median_width"] - ) - return { - "radius": radius, - "direction": direction, - "n": n, - "baseline": { - **baseline, - "mean_injected": round(statistics.mean(row["windows_after"] for row in subset), 2) if n else None, - }, - "d1": {**d1, "mean_injected": 0.0}, - "width_worse_cases": sum( - 1 for row in subset - if row["after_six"]["width"] is not None and row["after"]["width"] is not None - and row["after_six"]["width"] > row["after"]["width"] - ), - "truth_lost_cases": sum( - 1 for row in subset - if row["after"]["truth_in_range"] and not row["after_six"]["truth_in_range"] - ), - "gate_pass": passed, - "errors": sum( - 1 for row in rows - if row.get("radius") == radius and row.get("direction") == direction and row.get("error") - ), - } - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", default=",".join(str(item) for item in RADII)) - parser.add_argument("--directions", default="truth,opposite") - parser.add_argument("--json-out", default=str(REPORT_JSON)) - args = parser.parse_args() - radii = tuple(int(item) for item in str(args.radii).split(",") if item.strip()) - directions = tuple(item.strip() for item in str(args.directions).split(",") if item.strip()) - cases = load_cases() - if args.limit: - cases = cases[: args.limit] - started = time.perf_counter() - rows: list[dict[str, Any]] = [] - for case in cases: - for radius in radii: - for direction in directions: - label = f"{case.get('case_id')} ±{radius} {direction}" - try: - result = evaluate_case(case, radius, direction) - rows.append(result) - print( - f"{label} baseline w={result['after']['width']} in={result['after']['truth_in_range']} " - f"d1 w={result['after_six']['width']} in={result['after_six']['truth_in_range']}", - flush=True, - ) - except Exception as exc: # noqa: BLE001 - rows.append({ - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "error": f"{type(exc).__name__}: {exc}", - "trace": traceback.format_exc(limit=8), - }) - print(f"{label} ERROR {type(exc).__name__}: {exc}", flush=True) - summaries = [summarize(rows, radius, direction) for radius in radii for direction in directions] - payload = { - "method": "fewer_probes_card_replay.evaluate_case; baseline=after (2 guided windows injected), d1=after_six (none)", - "holdout": "references/real_case_calibration/minute_rectification_holdout_v4.json", - "elapsed_s": round(time.perf_counter() - started, 1), - "all_cells_pass": all(item["gate_pass"] for item in summaries), - "summaries": summaries, - "rows": [ - { - "case_id": row.get("case_id"), - "radius": row.get("radius"), - "direction": row.get("direction"), - **({"error": row["error"]} if row.get("error") else { - "baseline": {key: row["after"][key] for key in ("start", "end", "width", "truth_in_range")}, - "d1": {key: row["after_six"][key] for key in ("start", "end", "width", "truth_in_range")}, - "windows_injected": row["windows_after"], - }), - } - for row in rows - ], - } - out = Path(args.json_out) - out.parent.mkdir(parents=True, exist_ok=True) - out.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps(summaries, ensure_ascii=False, indent=2), flush=True) - print(f"wrote {out} in {payload['elapsed_s']}s all_cells_pass={payload['all_cells_pass']}", flush=True) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/generate_varga_segment_goldens.py b/scripts/research/generate_varga_segment_goldens.py deleted file mode 100644 index f21436c51..000000000 --- a/scripts/research/generate_varga_segment_goldens.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Generate public v5 engine goldens; expected values come from accepted research.""" -from __future__ import annotations - -import json -import hashlib -import platform -from pathlib import Path - -from scripts.research import varga_resolution_lib as vr - -ROOT = Path(__file__).resolve().parents[2] - - -def main(): - cache = ROOT / "artifacts/varga-impl-validation-20260930/replay-cache" - accepted_path = ROOT / "docs/research/varga_resolution_research_2026_09_30.json" - accepted = json.loads(accepted_path.read_text(encoding="utf-8")) - records = [] - for case in vr.load_cases()[:12]: - for radius in (10, 30): - replay = vr.CaseReplay(case, radius, cache_dir=cache) - state = vr.replay_scores(replay.public, replay.probes, replay.true_time) - for chart in ("D1", "D9", "D10"): - segments = replay.segments((chart,)) - ordered = vr.select_probes_by_segment(replay.public, replay.probes, segments, replay.true_time) - summary = vr.segment_shares(vr.minute_weights(state, "raw"), segments, replay.true_time) - accepted_cell = next(row for row in accepted["m1"]["by_radius"][str(radius)][chart]["raw"]["per_case"] - if row["case_id"] == replay.case_id) - actual_cell = {key: summary[key] for key in ("top_share", "top_is_truth", "truth_retained", "alive_segments")} - actual_cell["segments_in_window"] = len(segments) - if any(value != accepted_cell[key] for key, value in actual_cell.items()): - raise ValueError(f"accepted_raw_parity_mismatch:{replay.case_id}:{radius}:{chart}; use the calibrated Python runtime") - records.append({ - "case_id": replay.case_id, "radius": radius, "chart": chart, - "rows": replay.public, - "posterior_rows": state["public"], "eliminated": sorted(state["eliminated"]), - "probes": replay.probes, "segments": segments, - "offsets": {minute: vr.offset_of(minute, replay.true_time) for minute in replay.times}, - "truth_offset": 0, "truth_time": replay.true_time, - "expected_summary": summary, "accepted_cell": actual_cell, - "expected_order": [probe["semantic_key"] for probe in ordered["asked"]], - "answers": {probe["semantic_key"]: vr.optimal_answer(probe, replay.true_time) for probe in replay.probes}, - }) - path = ROOT / "frontend/tests/fixtures/varga-segment-v5-golden.json" - path.write_text(vr.stable_json({ - "source": "v5 public AA engine responses; raw cells strictly verified against accepted research", - "python_version": platform.python_version(), - "accepted_sha256": hashlib.sha256(accepted_path.read_bytes()).hexdigest(), - "order_source": "sequential accepted research function; m2 JSON does not store semantic-key lists", - "records": records, - }), encoding="utf-8") - print(f"generated {len(records)} chart goldens across 12 public cases") - - -if __name__ == "__main__": - main() diff --git a/scripts/research/guided_collect_holdout_replay.py b/scripts/research/guided_collect_holdout_replay.py deleted file mode 100644 index 98a992e5d..000000000 --- a/scripts/research/guided_collect_holdout_replay.py +++ /dev/null @@ -1,488 +0,0 @@ -#!/usr/bin/env python3 -"""Offline T2 replay: after six probes, inject guided_collect_windows events. - -F5 (2026-09-16): the injected event now lands on the **true** candidate's own -boundary date for that window's track and index, so the replay measures what a -user who really lived through that window would report. A second, opposite -pass injects the boundary of the candidate furthest from the true minute, as a -control. Neither pass is a merge gate; both numbers go in the progress note. - -Does not change production defaults. Writes a compact JSON summary for the -progress note. Not a merge gate. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import time -import traceback -from calendar import monthrange -from datetime import date -from pathlib import Path -from typing import Any, Sequence -from uuid import NAMESPACE_URL, uuid5 - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - NODE_MODE, - compute_candidate_static_contexts, -) -from scripts.rectification.event_probes import ( # noqa: E402 - GUIDED_ANY_DOMAIN, - GUIDED_COLLECT_LIMIT, - _birth_year, - _context_time, - _guided_track_starts, - _guided_year_windows, - _remaining_contexts, - _scoreable, - _static_contexts, - discriminating_event_probes, - guided_collect_windows, -) -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) -from scripts.rectification_policy import DELIVERY_MAX_WIDTH_MINUTES # noqa: E402 -from scripts.research.cluster_width_lib import ( # noqa: E402 - SEPARATION_LEAD, - delivery_from_public, - merge_adjacent_traced, - public_from_clusters, - raw_signature_clusters, - still_valid_public, -) -from scripts.research.cluster_width_probe import replay_public # noqa: E402 -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.probe_supply_after_six import ASK_COUNT, KIND_BY_DOMAIN # noqa: E402 - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -REPORT_JSON = ROOT / "docs" / "research" / "guided_collect_holdout_2026_09_16.json" -TODAY = date(2026, 9, 16) -RADII = (10, 30, 60) -RANGE_DELIVERY_TIE_PERCENT = 3 - - -def _hhmm(value: object) -> str | None: - text = str(value or "")[:5] - return text if len(text) == 5 and text[2] == ":" else None - - -def load_cases() -> list[dict[str, Any]]: - payload = json.loads(HOLDOUT.read_text(encoding="utf-8")) - return list(payload.get("cases") or []) - - -#: Windows are asked open now (BUG-749); the replay still needs one concrete -#: domain to write into the ledger, so an open window uses this one. -DEFAULT_OPEN_DOMAIN = "career" - - -def synthetic_event( - window: dict[str, Any], - index: int, - *, - when: date, -) -> dict[str, Any]: - """One month-precision event on `when`, labelled with the window's domain.""" - last = monthrange(when.year, when.month)[1] - raw_domain = str(window.get("domain") or "") - domain = DEFAULT_OPEN_DOMAIN if raw_domain in {"", GUIDED_ANY_DOMAIN} else raw_domain - kind = KIND_BY_DOMAIN.get(domain, "career_change") - stamp = f"{when.year:04d}-{when.month:02d}" - return { - "id": str(uuid5(NAMESPACE_URL, f"guided-collect:{index}:{domain}:{stamp}")), - "domain": domain, - "event_kind": kind, - "date_start": f"{stamp}-01", - "date_end": f"{stamp}-{last:02d}", - "precision": "month", - "summary": f"guided {domain} {stamp}", - } - - -def _minutes(value: str) -> int: - hour, minute = value.split(":")[:2] - return int(hour) * 60 + int(minute) - - -def window_boundary_dates( - request: dict[str, Any], - built: dict[str, Any], - *, - candidate_times: Sequence[str], - today: date, -) -> dict[tuple[int, int, int], dict[str, date]]: - """Map each guided window to the per-candidate boundary date behind it. - - Mirrors `guided_collect_windows`'s own loop so the (track, index) pairing - is the engine's, not a guess: for every window key (year, month_lo, - month_hi) it returns {candidate_time: that candidate's boundary date}. - """ - birth_date = str(request.get("birth_date") or "").strip() - birth_year = _birth_year(birth_date) - if birth_year is None: - return {} - remaining = _remaining_contexts(built, candidate_times) - if len(remaining) < 2: - remaining = _static_contexts(built) - work = [item for item in remaining if _scoreable(item)] - if len(work) < 2: - return {} - lo, hi = birth_year + 5, min(today.year, birth_year + 80) - vim_cache: dict[tuple[Any, ...], list[date]] = {} - narayana_cache: dict[tuple[Any, ...], list[date] | None] = {} - starts_by_time: dict[str, dict[str, list[date]]] = {} - for context in work: - stamp = _context_time(context) - if not stamp: - continue - starts_by_time[stamp] = _guided_track_starts( - context, - birth_date=birth_date, - lo=lo, - hi=hi, - include_pratyantar=True, - varga_narayana=True, - vim_cache=vim_cache, - narayana_cache=narayana_cache, - ) - out: dict[tuple[int, int, int], dict[str, date]] = {} - for track in ("vim", "nara", "nara:d9", "nara:d10"): - lengths = [len(starts_by_time.get(str(_context_time(item)) or "", {}).get(track) or []) for item in work] - if not lengths or min(lengths) == 0: - continue - for index in range(min(lengths)): - per_time: dict[str, date] = {} - for context in work: - stamp = _context_time(context) - dates = (starts_by_time.get(stamp or "") or {}).get(track) or [] - if stamp and index < len(dates): - per_time[stamp] = dates[index] - gathered = list(per_time.values()) - if len(gathered) < 2 or min(gathered) == max(gathered): - continue - for year, month_lo, month_hi in _guided_year_windows(gathered): - if year < lo or year > hi: - continue - out.setdefault((year, month_lo, month_hi), per_time) - return out - - -def posterior_state( - *, - rows: Sequence[dict[str, Any]], - contexts: Sequence[dict[str, Any]], - probes: Sequence[dict[str, Any]], - true_time: str, -) -> dict[str, Any]: - raw = raw_signature_clusters(contexts) - by_time = {stamp: row for row in rows if (stamp := _hhmm(row.get("time")))} - merged, _trace = merge_adjacent_traced(raw, by_time) - public = public_from_clusters(merged, rows) - prior = {stamp: float(row.get("score") or 0) for row in public if (stamp := _hhmm(row.get("time")))} - replay = replay_public(probes=probes, public=public, prior=prior, true_time=true_time) - posterior = [] - eliminated = set(replay["eliminated"]) - scores = dict(replay["scores"]) - for row in public: - stamp = _hhmm(row.get("time")) - if not stamp: - continue - posterior.append({**row, "score": scores.get(stamp, row.get("score") or 0)}) - valid = still_valid_public(posterior, scores, eliminated, lead=SEPARATION_LEAD) - delivery = delivery_from_public(valid) - return { - "scores": scores, - "eliminated": eliminated, - "public": posterior, - "valid": valid, - "delivery": delivery, - "merged": merged, - } - - -def precision_gate(valid: Sequence[dict[str, Any]], scores: dict[str, float]) -> dict[str, Any]: - delivery = delivery_from_public(valid) - width = delivery.get("width") - ranked = sorted( - valid, - key=lambda row: ( - -float(scores.get(_hhmm(row.get("time")) or "", row.get("score") or 0)), - str(row.get("time") or ""), - ), - ) - if not ranked: - return { - "met": False, - "width": width, - "tied_for_first": False, - "gap": None, - "percents": [], - } - if len(ranked) == 1: - return { - "met": width is not None and width <= DELIVERY_MAX_WIDTH_MINUTES, - "width": width, - "tied_for_first": False, - "gap": None, - "percents": [100], - } - s0 = float(scores.get(_hhmm(ranked[0].get("time")) or "", ranked[0].get("score") or 0)) - s1 = float(scores.get(_hhmm(ranked[1].get("time")) or "", ranked[1].get("score") or 0)) - tied = s0 == s1 - total = sum( - max(float(scores.get(_hhmm(row.get("time")) or "", row.get("score") or 0)), 0.0) - for row in ranked - ) - percents = [] - for row in ranked[:3]: - score = max(float(scores.get(_hhmm(row.get("time")) or "", row.get("score") or 0)), 0.0) - percents.append(round(score / total * 100) if total > 0 else 0) - gap = percents[0] - percents[1] - met = ( - width is not None - and width <= DELIVERY_MAX_WIDTH_MINUTES - and gap > RANGE_DELIVERY_TIE_PERCENT - and not tied - ) - return { - "met": met, - "width": width, - "tied_for_first": tied, - "gap": gap, - "percents": percents, - } - - -def remaining_times(state: dict[str, Any]) -> list[str]: - times: list[str] = [] - seen: set[str] = set() - for row in state["valid"]: - stamp = _hhmm(row.get("time")) - if stamp and stamp not in seen and stamp not in state["eliminated"]: - seen.add(stamp) - times.append(stamp) - for member in row.get("cluster_times") or []: - clock = _hhmm(member) - if clock and clock not in seen and clock not in state["eliminated"]: - seen.add(clock) - times.append(clock) - return times - - -def evaluate_case( - case: dict[str, Any], - radius: int, - direction: str = "truth", -) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - request = scoring_request_for(case, radius) - request["ayanamsa"] = AYANAMSA - request["node_mode"] = NODE_MODE - request["minute_step"] = MINUTE_STEP - static_contexts = compute_candidate_static_contexts(request) - built = build_event_contribution_matrix(request, static_contexts=static_contexts) - rows = score_from_matrix(request, built) - times = [stamp for row in rows if (stamp := _hhmm(row.get("time")))] - probes = discriminating_event_probes( - {**request, "refresh_probes": False, "asked_probe_keys": []}, - built, - scan=window_scan(built), - candidate_times=times, - representative_time=true_time, - today=TODAY, - ) - state = posterior_state(rows=rows, contexts=static_contexts, probes=probes[:ASK_COUNT], true_time=true_time) - gate = precision_gate(state["valid"], state["scores"]) - if gate["met"]: - return { - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "events_needed": 0, - "windows": 0, - "met": True, - "after_six": gate, - } - remaining = remaining_times(state) - windows = guided_collect_windows( - request, - built, - candidate_times=remaining or times, - today=TODAY, - ) - boundaries = window_boundary_dates( - request, - built, - candidate_times=remaining or times, - today=TODAY, - ) - pool = remaining or times - if direction == "truth": - source_time = true_time - else: - source_time = max( - pool, - key=lambda stamp: abs(_minutes(stamp) - _minutes(true_time)), - ) if pool else true_time - extras: list[dict[str, Any]] = [] - last_gate = gate - injected_from: list[str] = [] - for index, window in enumerate(windows): - key = (int(window["year"]), int(window["month_lo"]), int(window["month_hi"])) - per_time = boundaries.get(key) or {} - when = per_time.get(source_time) - if when is None and per_time: - when = per_time[min(per_time, key=lambda stamp: abs(_minutes(stamp) - _minutes(source_time)))] - if when is None: - when = date(int(window["year"]), int(window["month_lo"]), 1) - injected_from.append(f"{source_time}:{when.isoformat()}") - extras.append(synthetic_event(window, index, when=when)) - injected = {**request, "events": list(request["events"]) + extras} - rebuilt = build_event_contribution_matrix( - scoreable_request(injected), - static_contexts=static_contexts, - ) - new_rows = score_from_matrix(scoreable_request(injected), rebuilt) - state = posterior_state( - rows=new_rows, - contexts=static_contexts, - probes=probes[:ASK_COUNT], - true_time=true_time, - ) - last_gate = precision_gate(state["valid"], state["scores"]) - if last_gate["met"]: - return { - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "events_needed": len(extras), - "windows": len(windows), - "met": True, - "after_six": gate, - "final": last_gate, - "injected": injected_from, - } - return { - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "events_needed": None, - "windows": len(windows), - "met": False, - "after_six": gate, - "final": last_gate, - "injected": injected_from, - } - - -def summarize(rows: Sequence[dict[str, Any]], radius: int, direction: str) -> dict[str, Any]: - subset = [ - row for row in rows - if row.get("radius") == radius and row.get("direction") == direction and not row.get("error") - ] - needed = [int(row["events_needed"]) for row in subset if row.get("events_needed") is not None] - # Cases the six probes had not already settled: the only ones the guided - # windows can be credited for. - from_guided = [ - int(row["events_needed"]) for row in subset - if row.get("events_needed") not in (None, 0) - ] - met = sum(1 for row in subset if row.get("met")) - return { - "radius": radius, - "direction": direction, - "n": len(subset), - "met": met, - "met_after_six_only": sum(1 for row in subset if row.get("events_needed") == 0), - "met_via_guided": len(from_guided), - "median_events_to_gate": statistics.median(needed) if needed else None, - "median_events_via_guided": statistics.median(from_guided) if from_guided else None, - "median_windows": statistics.median([int(row.get("windows") or 0) for row in subset]) if subset else None, - "unmet": sum(1 for row in subset if not row.get("met")), - "errors": sum( - 1 for row in rows - if row.get("radius") == radius and row.get("direction") == direction and row.get("error") - ), - } - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", default="10,30,60") - parser.add_argument("--directions", default="truth,opposite") - parser.add_argument("--json-out", default=str(REPORT_JSON)) - args = parser.parse_args() - radii = tuple(int(item) for item in str(args.radii).split(",") if item.strip()) - directions = tuple(item.strip() for item in str(args.directions).split(",") if item.strip()) - cases = load_cases() - if args.limit: - cases = cases[: args.limit] - started = time.perf_counter() - rows: list[dict[str, Any]] = [] - for case in cases: - for radius in radii: - for direction in directions: - label = f"{case.get('case_id')} ±{radius} {direction}" - try: - result = evaluate_case(case, radius, direction) - rows.append(result) - print( - f"{label} needed={result.get('events_needed')} " - f"met={result.get('met')} windows={result.get('windows')}", - flush=True, - ) - except Exception as exc: # noqa: BLE001 - rows.append({ - "case_id": case.get("case_id"), - "radius": radius, - "direction": direction, - "error": f"{type(exc).__name__}: {exc}", - "trace": traceback.format_exc(limit=8), - "met": False, - "events_needed": None, - }) - print(f"{label} ERROR {type(exc).__name__}: {exc}", flush=True) - summaries = [summarize(rows, radius, direction) for radius in radii for direction in directions] - payload = { - "generated_at": TODAY.isoformat(), - "holdout": str(HOLDOUT.relative_to(ROOT)).replace("\\", "/"), - "ask_count": ASK_COUNT, - "guided_collect_limit": GUIDED_COLLECT_LIMIT, - "injection": ( - "truth = the true candidate's own boundary date for that window's " - "track and index; opposite = the boundary of the remaining " - "candidate furthest from the true minute" - ), - "delivery_max_width_minutes": DELIVERY_MAX_WIDTH_MINUTES, - "tie_percent": RANGE_DELIVERY_TIE_PERCENT, - "elapsed_s": round(time.perf_counter() - started, 1), - "summaries": summaries, - "rows": [ - {key: value for key, value in row.items() if key != "trace"} - for row in rows - ], - "errors": [row for row in rows if row.get("error")], - } - out = Path(args.json_out) - out.parent.mkdir(parents=True, exist_ok=True) - out.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps(summaries, ensure_ascii=False, indent=2), flush=True) - print(f"wrote {out} in {payload['elapsed_s']}s", flush=True) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/holdout_v5_baseline.py b/scripts/research/holdout_v5_baseline.py deleted file mode 100644 index 2cfb00682..000000000 --- a/scripts/research/holdout_v5_baseline.py +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env python3 -"""Baseline scorecard for a holdout dataset (v4 subset check / v5 full set). - -Runs the production scoring (variant "baseline" only) through the three existing -research harnesses without modifying them: - - * minute_resolution_sweep five metrics + six-question replay (head hit) - * cluster_width_probe six-question replay under the live unionStillValidRange - * futile_collect_stop_replay truth / opposite six-cell coverage and width - -The harnesses hard-code the v4 dataset and the 2026-09-14 report paths as module -constants; this runner points them at the requested dataset and at its own output -files, so the published 09-14 / 09-26 documents are never rewritten. - -Usage: - python scripts/research/holdout_v5_baseline.py --dataset v5 # full v5 - python scripts/research/holdout_v5_baseline.py --dataset v5 --case-filter inherited # v4 subset inside v5 - python scripts/research/holdout_v5_baseline.py --dataset v4 --out-dir /tmp/x # published-number check -""" - -from __future__ import annotations - -import argparse -import json -import sys -import time -import traceback -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.research import cluster_width_probe as cwp # noqa: E402 -from scripts.research import futile_collect_stop_replay as fcs # noqa: E402 -from scripts.research import guided_collect_holdout_replay as gch # noqa: E402 -from scripts.research import minute_resolution_sweep as mrs # noqa: E402 - -CAL = ROOT / "references" / "real_case_calibration" -DATASETS = { - "v4": CAL / "minute_rectification_holdout_v4.json", - "v5": CAL / "minute_rectification_holdout_v5.json", -} -DEFAULT_OUT = ROOT / "docs" / "research" -RADII = (10, 30, 60) - - -def filtered_dataset(path: Path, case_filter: str | None, out_dir: Path) -> Path: - """Write a filtered copy of the dataset so every harness sees the same case list.""" - payload = json.loads(path.read_text(encoding="utf-8")) - cases = list(payload.get("cases") or []) - if case_filter == "inherited": - cases = [c for c in cases if c.get("inherited_from_v4")] - elif case_filter == "new": - cases = [c for c in cases if not c.get("inherited_from_v4")] - payload["cases"] = cases - # The harnesses record HOLDOUT relative to the repository root, so the working - # copy must live inside the repository; it is removed once the run finishes. - target = CAL / f"_holdout_v5_baseline_tmp_{path.stem}_{case_filter or 'all'}.json" - target.write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") - return target - - -def baseline_only(module: Any) -> None: - module.all_variants = lambda: [module.Variant("baseline")] - - -def keep_published_reports_untouched() -> None: - """cluster_width_probe.run rewrites the errata table inside the 09-14 sweep report; never do that here.""" - cwp.append_previous_errata = lambda *args, **kwargs: None - - -def run_sweep(dataset: Path, out_dir: Path, tag: str, radii: tuple[int, ...]) -> dict[str, Any]: - mrs.HOLDOUT = dataset - mrs.REPORT_MD = out_dir / f"holdout_v5_baseline_sweep_{tag}.md" - mrs.REPORT_JSON = out_dir / f"holdout_v5_baseline_sweep_{tag}.json" - baseline_only(mrs) - payload = mrs.run(argparse.Namespace(limit=0, radii=[str(r) for r in radii], quick=False)) - return {"baseline": payload["baseline"], "case_count": payload["case_count"], "errors": payload["errors"]} - - -def run_cluster_width(dataset: Path, out_dir: Path, tag: str, radii: tuple[int, ...]) -> dict[str, Any]: - cwp.HOLDOUT = dataset - cwp.REPORT_MD = out_dir / f"holdout_v5_baseline_cluster_width_{tag}.md" - cwp.REPORT_JSON = out_dir / f"holdout_v5_baseline_cluster_width_{tag}.json" - baseline_only(cwp) - keep_published_reports_untouched() - payload = cwp.run(argparse.Namespace(limit=0, radii=[str(r) for r in radii])) - replay = { - str(radius): payload["by_radius"][str(radius)]["baseline"].get("replay") - for radius in radii - if str(radius) in payload["by_radius"] - } - return {"replay": replay, "case_count": payload["case_count"], "errors": payload.get("errors", [])} - - -def run_futile(dataset: Path, radii: tuple[int, ...]) -> dict[str, Any]: - gch.HOLDOUT = dataset - cases = gch.load_cases() - rows: list[dict[str, Any]] = [] - for case in cases: - for radius in radii: - for direction in ("truth", "opposite"): - try: - rows.append(fcs.evaluate_case(case, radius, direction)) - except Exception as exc: # noqa: BLE001 - rows.append({ - "case_id": case.get("case_id"), "radius": radius, "direction": direction, - "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc(limit=6), - }) - summaries = [fcs.summarize(rows, radius, direction) for radius in radii for direction in ("truth", "opposite")] - return { - "summaries": summaries, - "errors": [row for row in rows if row.get("error")], - "case_count": len(cases), - } - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--dataset", choices=sorted(DATASETS), default="v5") - parser.add_argument("--case-filter", choices=["inherited", "new"], default=None) - parser.add_argument("--out-dir", default=str(DEFAULT_OUT)) - parser.add_argument("--radii", default=",".join(str(r) for r in RADII)) - parser.add_argument("--skip", default="", help="comma list of harnesses to skip: sweep,cluster,futile") - parser.add_argument("--json-out", default=None) - args = parser.parse_args() - - out_dir = Path(args.out_dir) - out_dir.mkdir(parents=True, exist_ok=True) - radii = tuple(int(item) for item in args.radii.split(",") if item.strip()) - skip = {item.strip() for item in args.skip.split(",") if item.strip()} - tag = f"{args.dataset}_{args.case_filter or 'all'}" - dataset = filtered_dataset(DATASETS[args.dataset], args.case_filter, out_dir) - - started = time.perf_counter() - result: dict[str, Any] = { - "dataset": str(DATASETS[args.dataset].relative_to(ROOT)).replace("\\", "/"), - "case_filter": args.case_filter, - "radii": list(radii), - "variant": "baseline (production scoring, no research variants)", - "ayanamsa": "raman", - "node_mode": "mean", - } - if "sweep" not in skip: - result["sweep"] = run_sweep(dataset, out_dir, tag, radii) - print("sweep done", json.dumps(result["sweep"]["baseline"]), flush=True) - if "cluster" not in skip: - result["cluster_width"] = run_cluster_width(dataset, out_dir, tag, radii) - print("cluster_width done", json.dumps(result["cluster_width"]["replay"]), flush=True) - if "futile" not in skip: - result["futile_collect"] = run_futile(dataset, radii) - print("futile done", json.dumps(result["futile_collect"]["summaries"]), flush=True) - result["elapsed_s"] = round(time.perf_counter() - started, 1) - json_out = Path(args.json_out) if args.json_out else out_dir / f"holdout_v5_baseline_{tag}_2026_09_29.json" - json_out.write_text(json.dumps(result, ensure_ascii=True, indent=2) + "\n", encoding="utf-8") - dataset.unlink(missing_ok=True) - print(f"wrote {json_out} elapsed={result['elapsed_s']}s") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/house_lord_gochara_supply.py b/scripts/research/house_lord_gochara_supply.py deleted file mode 100644 index 0127ece68..000000000 --- a/scripts/research/house_lord_gochara_supply.py +++ /dev/null @@ -1,1084 +0,0 @@ -#!/usr/bin/env python3 -"""Offline measurement: house-lord gochara relaxations vs lagna/minute ranking. - -Does not change production `active_rectification_event_engine.py` or -`scoring_service.py` defaults. H1–H4 are temporary patches inside this script. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import subprocess -import sys -import traceback -from dataclasses import dataclass -from datetime import date, datetime, timedelta -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - DOMAIN_CONFIG, - NODE_MODE, - AYANAMSA, - _event_datetime, - _house_lords, - _relative_house, - compute_candidate_static_contexts, - compute_event_candidate_rows, -) -from scripts.active_rectification_events import precision_weight # noqa: E402 -from scripts.rectification.candidate_contrast import cluster_contexts_by_signature # noqa: E402 -from scripts.rectification.event_probes import ( # noqa: E402 - _static_contexts, - discriminating_event_probes, -) -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - scoreable_request, -) -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - TODAY, - apply_answer, - asked_key, - optimal_answer, - range_width, - remaining_after_six, - request_from_case, - top1_hit, -) -import dasha_analyzer # noqa: E402 -import domain_calculation_service # noqa: E402 -import narayana_dasha # noqa: E402 - -HOLDOUT_MANIFEST = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v3.json" -BLOCK_RADIUS_MINUTES = 120 -LAGNA_SCAN_STEP = 2 -TRANSIT_POINTS = 0.25 -H4_MD_POINTS = 1.0 -H4_AD_POINTS = 0.5 -H4_H1_POINTS = 0.25 -DEFAULT_H1_ORB = 3.0 -DEFAULT_H2_ORB = 2.0 - -_TRANSIT_CACHE: dict[tuple[Any, ...], dict[str, Any]] = {} -_DASHA_CACHE: dict[tuple[Any, ...], tuple[list[dict[str, Any]], Any]] = {} - - -@dataclass(frozen=True) -class Relaxation: - h1: bool = False - h2: bool = False - h3: bool = False - h4: bool = False - h1_orb: float = DEFAULT_H1_ORB - h2_orb: float = DEFAULT_H2_ORB - - @property - def name(self) -> str: - labels = [ - label - for label, on in (("H1", self.h1), ("H2", self.h2), ("H3", self.h3), ("H4", self.h4)) - if on - ] - base = "+".join(labels) if labels else "baseline" - extra: list[str] = [] - if self.h1 and abs(self.h1_orb - DEFAULT_H1_ORB) > 1e-9: - extra.append(f"h1orb{self.h1_orb:g}") - if self.h2 and abs(self.h2_orb - DEFAULT_H2_ORB) > 1e-9: - extra.append(f"h2orb{self.h2_orb:g}") - return base if not extra else f"{base}@{'+'.join(extra)}" - - -def all_relaxations() -> list[Relaxation]: - rows: list[Relaxation] = [] - for mask in range(16): - rows.append(Relaxation( - h1=bool(mask & 1), - h2=bool(mask & 2), - h3=bool(mask & 4), - h4=bool(mask & 8), - )) - return rows - - -def orb_sensitivity_relaxations() -> list[Relaxation]: - rows = [Relaxation()] - for orb in (1.0, 3.0, 5.0): - rows.append(Relaxation(h1=True, h1_orb=orb)) - for orb in (1.0, 2.0, 5.0): - rows.append(Relaxation(h2=True, h2_orb=orb)) - return rows - - -def circ_delta(left: float, right: float) -> float: - delta = abs(left - right) % 360.0 - return min(delta, 360.0 - delta) - - -def aspect_name(left: float, right: float, orb: float) -> str | None: - distance = circ_delta(left, right) - if distance <= orb: - return "conjunction" - if abs(distance - 180.0) <= orb: - return "opposition" - if abs(distance - 90.0) <= orb: - return "square" - return None - - -def planet_lon(chart: dict[str, Any], name: str) -> float | None: - item = (chart.get("planets") or {}).get(name) or {} - value = item.get("lon") - return float(value) if isinstance(value, (int, float)) else None - - -def _chart_args(request: dict[str, Any], when: datetime) -> dict[str, Any]: - return { - "year": when.year, - "month": when.month, - "day": when.day, - "hour": when.hour, - "minute": when.minute, - "lat": request["lat"], - "lon": request["lon"], - "tz": request["tz"], - "ayanamsa": request.get("ayanamsa", AYANAMSA), - "node_mode": request.get("node_mode", NODE_MODE), - } - - -def transit_chart(request: dict[str, Any], when: datetime) -> dict[str, Any]: - key = ( - when.year, when.month, when.day, when.hour, when.minute, - round(float(request["lat"]), 5), round(float(request["lon"]), 5), - float(request["tz"]), - request.get("ayanamsa", AYANAMSA), - request.get("node_mode", NODE_MODE), - ) - cached = _TRANSIT_CACHE.get(key) - if cached is not None: - return cached - chart = domain_calculation_service.compute_chart(_chart_args(request, when)) - _TRANSIT_CACHE[key] = chart - return chart - - -def event_year(event: dict[str, Any]) -> int: - raw = str(event.get("date") or event.get("date_start") or "") - return int(raw[:4]) - - -def extra_gochara_rules( - request: dict[str, Any], - event: dict[str, Any], - natal_chart: dict[str, Any], - natal_ascendant_index: int, - target_houses: tuple[int, ...], - relax: Relaxation, -) -> list[str]: - """Return only H1/H3 extras. Production occupancy rules stay on the baseline row.""" - precision = str(event.get("precision") or "year") - rules: list[str] = [] - occupancy_times: list[datetime] - if precision == "year" and relax.h3: - occupancy_times = [datetime(event_year(event), month, 15, 12, 0) for month in range(1, 13)] - seen_planets: set[str] = set() - for when in occupancy_times: - chart = transit_chart(request, when) - for planet in ("Jupiter", "Saturn"): - if planet in seen_planets: - continue - lon = planet_lon(chart, planet) - if lon is None: - continue - if _relative_house(int(lon // 30), natal_ascendant_index) in target_houses: - rules.append(f"h3_year_transit_{planet.lower()}_domain_house") - seen_planets.add(planet) - elif precision == "year": - occupancy_times = [_event_datetime(event)] - else: - occupancy_times = [_event_datetime(event)] - - if relax.h1: - lords = _house_lords(natal_ascendant_index, target_houses) - natal_longitudes = {lord: planet_lon(natal_chart, lord) for lord in lords} - seen: set[str] = set() - for when in occupancy_times: - chart = transit_chart(request, when) - for planet in ("Jupiter", "Saturn"): - transit_lon = planet_lon(chart, planet) - if transit_lon is None: - continue - for lord, natal in natal_longitudes.items(): - if natal is None: - continue - aspect = aspect_name(transit_lon, natal, relax.h1_orb) - if aspect is None: - continue - rule = f"h1_transit_{planet.lower()}_{aspect}_natal_{lord.lower()}" - if rule not in seen: - rules.append(rule) - seen.add(rule) - return rules - - -def h2_rules(event: dict[str, Any], context: dict[str, Any], relax: Relaxation) -> list[str]: - natal = context["chart"] - ascendant_index = int(context["ascendant_index"]) - rahu = planet_lon(natal, "Rahu") - ketu = planet_lon(natal, "Ketu") - target_houses = DOMAIN_CONFIG[event["domain"]][1] - lords = _house_lords(ascendant_index, target_houses) - hits: list[str] = [] - for node_name, node_lon in (("rahu", rahu), ("ketu", ketu)): - if node_lon is None: - continue - for lord in lords: - lord_lon = planet_lon(natal, lord) - if lord_lon is None: - continue - if circ_delta(node_lon, lord_lon) <= relax.h2_orb: - hits.append(f"h2_natal_{node_name}_{lord.lower()}_conjunction") - break - return hits - - -def dasha_timeline(birth_date: str, moon_longitude: float): - key = (birth_date, round(float(moon_longitude), 6)) - cached = _DASHA_CACHE.get(key) - if cached is not None: - return cached - nakshatra, progress, _ = dasha_analyzer.lon_to_nakshatra(moon_longitude) - timeline, *_rest = dasha_analyzer.build_dasha_timeline(birth_date, nakshatra, progress) - _DASHA_CACHE[key] = (timeline, moon_longitude) - return _DASHA_CACHE[key] - - -def year_overlaps(start: datetime, end: datetime, year: int) -> bool: - year_start = datetime(year, 1, 1) - year_end = datetime(year + 1, 1, 1) - return start < year_end and end > year_start - - -def h4_bonus( - request: dict[str, Any], - context: dict[str, Any], - relax: Relaxation, -) -> dict[str, Any]: - natal = context["chart"] - ascendant_index = int(context["ascendant_index"]) - moon = planet_lon(natal, "Moon") - hits: list[dict[str, Any]] = [] - points = 0.0 - if moon is None: - return {"points": 0.0, "hits": hits, "blocked": "moon_longitude_missing"} - timeline, _ = dasha_timeline(request["birth_date"], moon) - for event in request["events"]: - year = event_year(event) - target_houses = DOMAIN_CONFIG[event["domain"]][1] - lords = _house_lords(ascendant_index, target_houses) - md_hit = False - ad_hit = False - for major in timeline: - if not year_overlaps(major["start"], major["end"], year): - continue - if str(major["lord"]) in lords: - md_hit = True - for minor in dasha_analyzer.build_antardasha(major): - if str(minor["lord"]) in lords and year_overlaps(minor["start"], minor["end"], year): - ad_hit = True - h1_hit = False - sample = Relaxation(h1=True, h3=True, h1_orb=relax.h1_orb) - h1_rules = extra_gochara_rules( - request, event, natal, ascendant_index, target_houses, sample, - ) - h1_hit = any(rule.startswith("h1_") for rule in h1_rules) - kind = None - if md_hit: - kind = "md" - points += H4_MD_POINTS - elif ad_hit: - kind = "ad" - points += H4_AD_POINTS - if h1_hit and not relax.h1: - points += H4_H1_POINTS - kind = f"{kind}+h1" if kind else "h1" - if kind: - hits.append({ - "event_id": event["id"], - "domain": event["domain"], - "year": year, - "kind": kind, - "lords": sorted(lords), - }) - return {"points": round(points, 4), "hits": hits, "blocked": None} - - -def apply_extras( - rows: Sequence[dict[str, Any]], - request: dict[str, Any], - contexts_by_time: dict[str, dict[str, Any]], - relax: Relaxation, -) -> list[dict[str, Any]]: - events_by_id = {str(event["id"]): event for event in request["events"]} - cloned: list[dict[str, Any]] = [] - for row in rows: - context = contexts_by_time.get(str(row["time"])[:5]) - evidence_out = [] - for item in row.get("evidence") or []: - event = events_by_id.get(str(item.get("event_id") or "")) - extra: list[str] = [] - if event is not None and context is not None: - houses = DOMAIN_CONFIG[event["domain"]][1] - extra.extend(extra_gochara_rules( - request, event, context["chart"], int(context["ascendant_index"]), houses, relax, - )) - if relax.h2: - extra.extend(h2_rules(event, context, relax)) - points = round( - float(item.get("points") or 0.0) - + TRANSIT_POINTS * len(extra) * precision_weight(event["precision"] if event else "year"), - 4, - ) - evidence_out.append({ - **item, - "rule_ids": list(item.get("rule_ids") or []) + extra, - "points": points, - }) - cloned.append({ - **row, - "evidence": evidence_out, - "score": round(sum(float(item["points"]) for item in evidence_out), 4), - }) - return cloned - - -def true_center(case: dict[str, Any]) -> datetime: - birth = case["birth"] - return datetime.combine( - date.fromisoformat(str(birth["date"])), - datetime.strptime(str(birth["time"])[:5], "%H:%M").time(), - ) - - -def window_datetimes(center: datetime, radius: int, step: int) -> list[datetime]: - start = center - timedelta(minutes=radius) - end = center + timedelta(minutes=radius) - rows = [] - cursor = start - while cursor <= end: - rows.append(cursor) - cursor += timedelta(minutes=step) - if center not in rows: - rows.append(center) - rows.sort() - return rows - - -def engine_request_from_scoring( - scoring_request: dict[str, Any], - *, - start_time: str, - end_time: str, -) -> dict[str, Any]: - events = [] - for event in scoring_request["events"]: - precision = str(event["precision"]) - start = str(event["date_start"]) - if precision == "year": - event_date = start[:4] - elif precision == "month": - event_date = start[:7] - else: - event_date = start[:10] - precision = "day" - domain = str(event["domain"]) - if domain not in DOMAIN_CONFIG: - continue - events.append({ - "id": event["id"], - "domain": domain, - "event_kind": event.get("event_kind", domain), - "date": event_date, - "precision": precision, - "summary": event.get("summary", ""), - }) - payload = { - "birth_date": scoring_request["birth_date"], - "start_time": start_time, - "end_time": end_time, - "lat": scoring_request["lat"], - "lon": scoring_request["lon"], - "tz": scoring_request["tz"], - "events": events, - } - for key in ("ayanamsa", "node_mode"): - if key in scoring_request: - payload[key] = scoring_request[key] - return payload - - -def hhmm(value: datetime) -> str: - return value.strftime("%H:%M") - - -def sign_name(index: int) -> str: - return narayana_dasha.SIGNS[index] - - -def lagna_index_at(request: dict[str, Any], when: datetime) -> int: - chart = transit_chart(request, when) - lon = float(chart["ascendant"]["lon"]) - return int(lon // 30) - - -def lagna_representatives( - request: dict[str, Any], - center: datetime, -) -> list[dict[str, Any]]: - scanned = window_datetimes(center, BLOCK_RADIUS_MINUTES, LAGNA_SCAN_STEP) - groups: dict[int, list[datetime]] = {} - for when in scanned: - groups.setdefault(lagna_index_at(request, when), []).append(when) - rows = [] - for index, times in sorted(groups.items()): - mid = times[len(times) // 2] - rows.append({ - "ascendant_index": index, - "ascendant_sign": sign_name(index), - "representative_at": mid, - "member_count": len(times), - "first_at": times[0], - "last_at": times[-1], - }) - return rows - - -def unique_rank(scores: dict[int, float], true_index: int) -> dict[str, Any]: - if true_index not in scores: - return { - "rank": None, "top1": False, "top1_unique": False, "top2": False, - "tie_count": 0, "n": len(scores), - } - true_score = scores[true_index] - higher = sum(1 for value in scores.values() if value > true_score + 1e-9) - tied = [index for index, value in scores.items() if abs(value - true_score) <= 1e-9] - rank = higher + 1 - return { - "rank": rank, - "top1": rank == 1, - "top1_unique": rank == 1 and len(tied) == 1, - "top2": rank <= 2, - "tie_count": len(tied), - "n": len(scores), - "true_score": round(true_score, 4), - } - - -def block_variant( - *, - request: dict[str, Any], - reps: Sequence[dict[str, Any]], - contexts_by_time: dict[str, dict[str, Any]], - baseline_rows: Sequence[dict[str, Any]], - true_index: int, - relax: Relaxation, -) -> dict[str, Any]: - rows = apply_extras(baseline_rows, request, contexts_by_time, relax) - by_time = {row["time"]: row for row in rows} - scores: dict[int, float] = {} - detail = [] - for rep in reps: - stamp = hhmm(rep["representative_at"]) - row = by_time.get(stamp) - engine_score = float(row["score"]) if row else 0.0 - bonus = {"points": 0.0, "hits": [], "blocked": "row_missing" if row is None else None} - context = contexts_by_time.get(stamp) - if relax.h4 and context is not None: - bonus = h4_bonus(request, context, relax) - total = engine_score + float(bonus["points"]) - scores[int(rep["ascendant_index"])] = total - detail.append({ - "ascendant_sign": rep["ascendant_sign"], - "ascendant_index": rep["ascendant_index"], - "representative": stamp, - "engine_score": round(engine_score, 4), - "h4_points": bonus["points"], - "total": round(total, 4), - "h4_hits": bonus["hits"], - "rule_ids": sorted({ - rule - for evidence in (row or {}).get("evidence") or [] - for rule in evidence.get("rule_ids") or [] - if str(rule).startswith(("controlled_transit", "h1_", "h2_", "h3_")) - }), - }) - ranking = unique_rank(scores, true_index) - ranking["lagnas"] = detail - ranking["lagna_count"] = len(reps) - return ranking - - -def minute_metrics(rows: Sequence[dict[str, Any]], true_time: str) -> dict[str, Any]: - if not rows: - return {"top1_unique": False, "true_in_top_tie": False, "range_width": None, "score_range": 0.0, "n": 0} - best = max(float(row["score"]) for row in rows) - leaders = [str(row["time"])[:5] for row in rows if abs(float(row["score"]) - best) <= 1e-9] - values = [float(row["score"]) for row in rows] - return { - "top1_unique": leaders == [true_time], - "true_in_top_tie": true_time in leaders, - "leader_count": len(leaders), - "range_width": range_width(leaders), - "window_width": range_width([str(row["time"])[:5] for row in rows]), - "score_range": round(max(values) - min(values), 4) if values else 0.0, - "n": len(rows), - "lagna_leak_suspect": False, - } - - -def initial_probes( - *, - scoring_request: dict[str, Any], - built: dict[str, Any], - candidate_times: Sequence[str], - true_time: str, -) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - from scripts.research.probe_supply_after_six import _scan_for - scan = _scan_for(built) - initial = discriminating_event_probes( - {**scoring_request, "refresh_probes": False}, - built, - scan=scan, - candidate_times=list(candidate_times), - representative_time=true_time, - today=TODAY, - ) - return initial, initial[:ASK_COUNT] - - -def replay_after_six( - *, - built: dict[str, Any], - prior: dict[str, float], - true_time: str, - initial: Sequence[dict[str, Any]], - asked: Sequence[dict[str, Any]], -) -> dict[str, Any]: - all_times = list(prior) - contexts = _static_contexts(built) - clusters = cluster_contexts_by_signature(contexts) - scores = dict(prior) - conflicts = {time: 0 for time in all_times} - eliminated: set[str] = set() - for probe in asked: - answer = optimal_answer(probe, true_time) - if answer is None: - continue - scores, conflicts, eliminated = apply_answer( - scores, conflicts, eliminated, probe, answer, all_times, - ) - remaining, remaining_mode, true_alive = remaining_after_six( - all_times=all_times, - scores=scores, - eliminated=eliminated, - clusters=clusters, - true_time=true_time, - ) - return { - "asked_count": len(asked), - "initial_probe_count": len(initial), - "remaining_count": len(remaining), - "remaining_mode": remaining_mode, - "true_alive": true_alive, - "top1_hit": top1_hit(scores, remaining, true_time, clusters), - "range_width": range_width(remaining), - "asked_keys": [asked_key(probe) for probe in asked if asked_key(probe)], - } - - -def score_case(case: dict[str, Any], *, include_orb: bool) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - center = true_center(case) - scoring_request = request_from_case(case) - engine_request = engine_request_from_scoring( - scoring_request, - start_time=scoring_request["start_time"], - end_time=scoring_request["end_time"], - ) - true_lagna = lagna_index_at(engine_request, center) - reps = lagna_representatives(engine_request, center) - block_candidates = [rep["representative_at"] for rep in reps] - if center not in block_candidates: - block_candidates.append(center) - block_contexts = compute_candidate_static_contexts(engine_request, candidates=block_candidates) - block_by_time = {hhmm(item["candidate_at"]): item for item in block_contexts} - block_baseline_rows = compute_event_candidate_rows(engine_request, static_contexts=block_contexts) - - minute_candidates = window_datetimes(center, int(case.get("candidate_radius_minutes") or 10), 1) - minute_contexts = compute_candidate_static_contexts(engine_request, candidates=minute_candidates) - minute_by_time = {hhmm(item["candidate_at"]): item for item in minute_contexts} - minute_baseline_rows = compute_event_candidate_rows(engine_request, static_contexts=minute_contexts) - minute_lagnas = sorted({int(item["ascendant_index"]) for item in minute_contexts}) - - built = build_event_contribution_matrix(scoreable_request(scoring_request), static_contexts=minute_contexts) - minute_times = [hhmm(item["candidate_at"]) for item in minute_contexts] - initial, asked = initial_probes( - scoring_request=scoring_request, - built=built, - candidate_times=minute_times, - true_time=true_time, - ) - - variants: dict[str, Any] = {} - relaxations = all_relaxations() - if include_orb: - seen = {item.name for item in relaxations} - for item in orb_sensitivity_relaxations(): - if item.name not in seen: - relaxations.append(item) - seen.add(item.name) - - for relax in relaxations: - block = block_variant( - request=engine_request, - reps=reps, - contexts_by_time=block_by_time, - baseline_rows=block_baseline_rows, - true_index=true_lagna, - relax=relax, - ) - minute_rows = apply_extras( - minute_baseline_rows, - engine_request, - minute_by_time, - Relaxation( - h1=relax.h1, h2=relax.h2, h3=relax.h3, h4=False, - h1_orb=relax.h1_orb, h2_orb=relax.h2_orb, - ), - ) - minute = minute_metrics(minute_rows, true_time) - minute["lagna_count"] = len(minute_lagnas) - minute["lagna_leak_suspect"] = bool(minute["score_range"] > 0 and len(minute_lagnas) > 1) - minute_prior = {str(row["time"])[:5]: float(row["score"] or 0) for row in minute_rows} - replay = replay_after_six( - built=built, - prior=minute_prior, - true_time=true_time, - initial=initial, - asked=asked, - ) - variants[relax.name] = { - "block": block, - "minute_engine": minute, - "minute_replay": replay, - "h4_applied_to_minute": False, - } - - return { - "case_id": case["case_id"], - "true_time": true_time, - "true_lagna": sign_name(true_lagna), - "true_lagna_index": true_lagna, - "block_lagna_count": len(reps), - "block_lagnas": [rep["ascendant_sign"] for rep in reps], - "minute_lagna_count": len(minute_lagnas), - "minute_lagnas": [sign_name(index) for index in minute_lagnas], - "year_event_count": sum(1 for event in engine_request["events"] if event["precision"] == "year"), - "day_event_count": sum(1 for event in engine_request["events"] if event["precision"] == "day"), - "variants": variants, - } - - -def mean(values: Sequence[float | int | bool] | list[Any]) -> float | None: - numeric = [float(item) for item in values] - if not numeric: - return None - return round(statistics.mean(numeric), 4) - - -def summarize(cases: list[dict[str, Any]]) -> dict[str, Any]: - usable = [row for row in cases if not row.get("error")] - names: list[str] = [] - for row in usable: - for name in row.get("variants") or {}: - if name not in names: - names.append(name) - table: dict[str, Any] = {} - for name in names: - block_top1 = [bool(row["variants"][name]["block"]["top1_unique"]) for row in usable if name in row["variants"]] - block_top1_or_tie = [bool(row["variants"][name]["block"]["top1"]) for row in usable if name in row["variants"]] - block_top2 = [bool(row["variants"][name]["block"]["top2"]) for row in usable if name in row["variants"]] - block_rank = [ - int(row["variants"][name]["block"]["rank"]) - for row in usable - if name in row["variants"] and row["variants"][name]["block"].get("rank") is not None - ] - minute_top1 = [bool(row["variants"][name]["minute_engine"]["top1_unique"]) for row in usable if name in row["variants"]] - minute_width = [ - int(row["variants"][name]["minute_engine"]["range_width"]) - for row in usable - if name in row["variants"] and row["variants"][name]["minute_engine"].get("range_width") is not None - ] - minute_score_range = [ - float(row["variants"][name]["minute_engine"]["score_range"]) - for row in usable if name in row["variants"] - ] - replay_top1 = [bool(row["variants"][name]["minute_replay"]["top1_hit"]) for row in usable if name in row["variants"]] - replay_width = [ - int(row["variants"][name]["minute_replay"]["range_width"]) - for row in usable - if name in row["variants"] and row["variants"][name]["minute_replay"].get("range_width") is not None - ] - leak = sum( - 1 for row in usable - if name in row["variants"] and row["variants"][name]["minute_engine"].get("lagna_leak_suspect") - ) - table[name] = { - "n": len(block_top1), - "block_top1_unique": mean(block_top1), - "block_top1_or_tie": mean(block_top1_or_tie), - "block_top2": mean(block_top2), - "block_mean_rank": mean(block_rank), - "minute_top1_unique": mean(minute_top1), - "minute_mean_top_tie_width": mean(minute_width), - "minute_mean_score_range": mean(minute_score_range), - "replay_top1": mean(replay_top1), - "replay_mean_width": mean(replay_width), - "minute_lagna_leak_cases": leak, - } - baseline = table.get("baseline") or {} - for name, row in table.items(): - row["block_top1_delta"] = None if row["block_top1_unique"] is None or baseline.get("block_top1_unique") is None else round( - row["block_top1_unique"] - baseline["block_top1_unique"], 4, - ) - row["block_top2_delta"] = None if row["block_top2"] is None or baseline.get("block_top2") is None else round( - row["block_top2"] - baseline["block_top2"], 4, - ) - row["minute_top1_delta"] = None if row["minute_top1_unique"] is None or baseline.get("minute_top1_unique") is None else round( - row["minute_top1_unique"] - baseline["minute_top1_unique"], 4, - ) - row["replay_top1_delta"] = None if row["replay_top1"] is None or baseline.get("replay_top1") is None else round( - row["replay_top1"] - baseline["replay_top1"], 4, - ) - row["replay_width_delta"] = None if row["replay_mean_width"] is None or baseline.get("replay_mean_width") is None else round( - row["replay_mean_width"] - baseline["replay_mean_width"], 4, - ) - return { - "case_count": len(cases), - "usable_count": len(usable), - "errors": [row["case_id"] for row in cases if row.get("error")], - "multi_lagna_block_cases": sum(1 for row in usable if int(row.get("block_lagna_count") or 0) >= 2), - "minute_lagna_change_cases": sum(1 for row in usable if int(row.get("minute_lagna_count") or 0) > 1), - "variants": table, - } - - -def decide(summary: dict[str, Any]) -> dict[str, Any]: - usable = int(summary.get("usable_count") or 0) - if usable < 15: - return { - "verdict": "uncertain", - "reason": f"only {usable} public AA cases completed", - "implement": False, - } - winners: list[str] = [] - flagged: list[str] = [] - for name, row in summary["variants"].items(): - if name == "baseline" or "@" in name: - continue - block_delta = row.get("block_top1_delta") - minute_delta = row.get("minute_top1_delta") - replay_delta = row.get("replay_top1_delta") - if block_delta is None or minute_delta is None or replay_delta is None: - continue - minute_ok = minute_delta >= 0 and replay_delta >= 0 - if block_delta > 0 and minute_ok: - if row.get("minute_lagna_leak_cases") and minute_delta > 0: - flagged.append(name) - else: - winners.append(name) - if flagged and not winners: - return { - "verdict": "uncertain", - "reason": "block-layer lift appeared only with minute-layer lagna leak; do not treat as minute evidence", - "implement": False, - "variants": flagged, - } - if winners: - return { - "verdict": "benefit", - "reason": "block-layer unique top-1 rose versus production while minute top-1 and six-answer replay did not fall", - "implement": True, - "variants": winners, - } - return { - "verdict": "no_benefit", - "reason": "no H1–H4 combination raised block-layer unique top-1 without dropping minute-layer ranking", - "implement": False, - } - - -def git_sha() -> str: - try: - return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() - except Exception: - return "unknown" - - -def git_branch() -> str: - try: - return subprocess.check_output( - ["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=ROOT, text=True, - ).strip() - except Exception: - return "unknown" - - -def external_engine_status() -> dict[str, Any]: - rows: dict[str, Any] = {} - try: - from scripts.diagnose_external_engine_adapters import build_report - report = build_report() - rows["diagnostic"] = { - "status": report.get("status"), - "engines": { - name: (payload.get("status") or payload.get("availability") or payload) - for name, payload in (report.get("engines") or report.get("adapters") or {}).items() - } if isinstance(report, dict) else "unparsed", - } - except Exception as exc: - rows["diagnostic"] = {"status": "blocked", "reason": f"{type(exc).__name__}: {exc}"} - for label, module_name in ( - ("PyJHora", "pyjhora"), - ("jyotishganit", "jyotishganit"), - ("VedAstro", "vedastro"), - ): - try: - __import__(module_name) - rows[label] = "import_ok" - except Exception as exc: - rows[label] = f"blocked:{type(exc).__name__}" - return rows - - -def render_markdown(report: dict[str, Any]) -> str: - summary = report["summary"] - decision = report["decision"] - verdict_text = { - "benefit": "有收益,可另立实现单。", - "no_benefit": "无收益,关闭本方案。", - "uncertain": "不确定,还缺数据或分钟层疑似混入了上升量。", - }[decision["verdict"]] - lines = [ - "# 宫主触发与外行星过运分辨力测量(2026-09-13)", - "", - "- 任务:`docs/tasks/TASK-rectification-house-lord-gochara-research-20260913.md`", - f"- 代码基线:`{report['baseline']['sha']}`(`{report['baseline']['branch']}`)", - f"- 数据:`{report['baseline']['manifest']}`(20 例公开 AA,`source_audit_status=invalidated_after_replay`,只作开发集趋势,不是发布指标)", - "- 性质:离线测量。生产 `active_rectification_event_engine.py` / `scoring_service.py` 默认行为未改。", - "- **过运不得用于分钟级结论。** 本测量若看到分钟层变动,先查该例 ±10 分钟窗是否跨了上升星座。", - "", - "## 方法", - "", - "1. Block 层:真实出生时刻 ±2 小时,按 2 分钟步长扫上升星座,每个星座取代表时刻,用生产 `compute_event_candidate_rows` 打分;H1–H3 只在本脚本临时 patch 过运/合相规则,H4 只加在 block 层总分上。", - "2. Minute 层:沿用 `probe_supply_after_six.py` 的六题最优答案回放口径;先验改用 patch 后的引擎分钟分。H4 不进入分钟层。", - "3. 引擎原生路径对 `precision=year` 跳过受控过运;H3 才按事件年逐月扫描。生产 `scoring_service` 已把年份事件抽成 12 个 day 样本,那条路径不是本单 H3 的对照对象。", - "4. 放宽项只在研究脚本里组合,16 种全跑;H1/H2 另附 ±1°/默认/±5° 容许度。", - "", - "## 放宽项", - "", - "| 代号 | 改法 |", - "| --- | --- |", - "| H1 | 过运木星/土星与本命目标宫主合/冲/刑,默认容许度 ±3° |", - "| H2 | 本命罗睺/计都与目标宫主紧密合相,默认 ≤2° |", - "| H3 | `_controlled_transit_rules` 放宽到 year:事件年内逐月扫描,规则按 OR 去重 |", - "| H4 | 只用于选上升:事件年落在该上升下目标宫主的 Vimshottari 主限/副限,或(当 H1 未开时)H1 触发 |", - "", - f"完成例子:{summary['usable_count']}/{summary['case_count']};±2 小时窗内至少两个上升星座:{summary['multi_lagna_block_cases']};分钟窗跨上升:{summary['minute_lagna_change_cases']}。", - "", - "## Block 层", - "", - "| 方案 | 唯一头名 | 相对基线 | 头名或并列 | 前二 | 平均名次 |", - "| --- | ---: | ---: | ---: | ---: | ---: |", - ] - for name, row in summary["variants"].items(): - if "@" in name: - continue - lines.append( - f"| {name} | {row['block_top1_unique']} | {row['block_top1_delta']} | {row['block_top1_or_tie']} | {row['block_top2']} | {row['block_mean_rank']} |" - ) - lines.extend([ - "", - "## Minute 层", - "", - "| 方案 | 引擎唯一头名 | 相对基线 | 头名并列宽度 | 分差 | 六题回放头名 | 回放头名差 | 回放宽度 | 回放宽度差 | 分钟窗跨上升 |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", - ]) - for name, row in summary["variants"].items(): - if "@" in name: - continue - lines.append( - "| {name} | {minute_top1_unique} | {minute_top1_delta} | {minute_mean_top_tie_width} | {minute_mean_score_range} | {replay_top1} | {replay_top1_delta} | {replay_mean_width} | {replay_width_delta} | {minute_lagna_leak_cases} |".format( - name=name, **row, - ) - ) - lines.extend([ - "", - "## H1/H2 容许度", - "", - "| 方案 | Block 唯一头名 | 相对基线 | Minute 唯一头名 | 相对基线 |", - "| --- | ---: | ---: | ---: | ---: |", - ]) - orb_names = ["baseline", "H1", "H2", *[name for name in summary["variants"] if "@" in name]] - seen_orb: set[str] = set() - for name in orb_names: - if name in seen_orb or name not in summary["variants"]: - continue - seen_orb.add(name) - row = summary["variants"][name] - lines.append( - f"| {name} | {row['block_top1_unique']} | {row['block_top1_delta']} | {row['minute_top1_unique']} | {row['minute_top1_delta']} |" - ) - lines.extend([ - "", - "## 结论", - "", - f"**{verdict_text}**", - "", - f"- 判定:`{decision['verdict']}`", - f"- 原因:block 层唯一头名没有提升(H1/H2 持平,H3 只把前二 +0.05,H4 降到 0.15);分钟层头名与回放宽度均未变差,也没有变好。", - f"- 立实现单:{'是' if decision['implement'] else '否'}", - ]) - if decision.get("variants"): - lines.append(f"- 涉及组合:{', '.join(decision['variants'])}") - lines.extend([ - "", - "## 分例(block 层真实上升)", - "", - "| 例子 | 真实上升 | 窗内上升数 | baseline 名次 | 最好组合 | 该组合名次 | 分钟窗跨上升 |", - "| --- | --- | ---: | ---: | --- | ---: | --- |", - ]) - for row in report["cases"]: - if row.get("error"): - lines.append(f"| {row['case_id']} | error | | | | | {row.get('error')} |") - continue - baseline_rank = row["variants"]["baseline"]["block"]["rank"] - best_name = "baseline" - best_rank = baseline_rank - for name, variant in row["variants"].items(): - if "@" in name: - continue - rank = variant["block"].get("rank") - if rank is not None and (best_rank is None or rank < best_rank): - best_name = name - best_rank = rank - lines.append( - f"| {row['case_id']} | {row['true_lagna']} | {row['block_lagna_count']} | {baseline_rank} | {best_name} | {best_rank} | {row['minute_lagna_count'] > 1} |" - ) - engines = report.get("external_engines") or {} - diagnostic = (engines.get("diagnostic") or {}).get("engines") or {} - lines.extend([ - "", - "## 解读", - "", - "- 生产路径已经按上升算目标宫主,并给 Vimshottari 宫主/落宫加分;日/月精度事件还有木星/土星落目标宫的受控过运。本单量的是再放宽四条,不是从零引入宫主体系。", - "- **H1**:唯一头名、前二、平均名次均与基线相同。±1° / ±3° / ±5° 无差异。合冲刑会触发(例如 Obama 土星刑本命金星),但没把真实上升抬到唯一第一。", - "- **H2**:0 变化,≤1° / 2° / 5° 一样。罗睺计都与宫主的紧密合在这 20 例里几乎不提供上升分辨力。", - "- **H3**:唯一头名仍是 0.20;前二 0.75→0.80(Jolie 从第 3 升到第 2),平均名次 2.05→2.00。达不到任务书的「真实上升 top-1 提升」。", - "- **H4**:唯一头名 0.20→0.15,前二 0.75→0.65,平均名次变差。宫主大运落在事件年会给错误上升加分(Obama 双鱼代表时刻比摩羯多拿 2.0)。", - "- **Minute 层**:引擎唯一头名保持 0.05,六题回放头名 0.70、宽度 13.1,全部组合不升不降。4 例 ±10 分钟窗跨了上升,但没有因此出现分钟层收益,不需要当成好消息去排查。", - "- 过运不得用于分钟级结论。", - "", - "## Technique Audit / 边界", - "", - "- Functional Benefic/Malefic:生产 `_score_event` 已调用 `derive_functional_benefic_malefic`;本单未改该层。Used。", - "- MEVG / Global Web Evidence:古典 Gochara 主表从月亮计宫(BPHS / Raman *Hindu Predictive Astrology* ch.34),不是「过运木星/土星合本命宫主」。宫主身份随上升变。过运合冲刑宫主是现代解盘启发式,不是已关闭的官方公式。Used(来源冲突已记录)。", - "- Real Case Calibration:`minute_rectification_holdout_v3`,20 例公开 Rodden AA,`invalidated_after_replay`,只作开发集趋势。Used / not publication metrics。", - f"- 外部引擎诊断:VedAstro=`{diagnostic.get('VedAstro', engines.get('VedAstro'))}`,PyJHora=`{diagnostic.get('PyJHora/JHora', engines.get('PyJHora'))}`,jyotishganit=`{diagnostic.get('jyotishganit', engines.get('jyotishganit'))}`。本测量只走仓内 Swiss 引擎打分;未做三引擎同一盘对照,交叉验证 **blocked**。", - "- 过运不得用于分钟级结论;若以后另立实现单必须继承这一条。", - "- 未把研究脚本接到 API,未改 `SCORE_DELTA` / 确认门。", - "- 未写入任何私人出生资料。", - "", - ]) - return "\n".join(lines) + "\n" - - -def run(limit: int | None = None, case_id: str | None = None, include_orb: bool = True) -> dict[str, Any]: - payload = json.loads(HOLDOUT_MANIFEST.read_text(encoding="utf-8")) - cases = [item for item in payload.get("cases") or [] if isinstance(item, dict)] - if case_id: - cases = [item for item in cases if item.get("case_id") == case_id] - if limit is not None: - cases = cases[:limit] - rows: list[dict[str, Any]] = [] - for index, case in enumerate(cases, start=1): - label = str(case.get("case_id") or index) - print(f"[{index}/{len(cases)}] {label}", flush=True) - try: - rows.append(score_case(case, include_orb=include_orb)) - except Exception as exc: - rows.append({ - "case_id": str(case.get("case_id") or ""), - "error": f"{type(exc).__name__}: {exc}", - "traceback": traceback.format_exc(), - }) - print(rows[-1]["error"], flush=True) - summary = summarize(rows) - return { - "scope": "house_lord_gochara_supply", - "today": TODAY.isoformat(), - "baseline": { - "sha": git_sha(), - "branch": git_branch(), - "manifest": HOLDOUT_MANIFEST.relative_to(ROOT).as_posix(), - "benchmark_id": payload.get("benchmark_id"), - "source_audit_status": payload.get("source_audit_status"), - "h1_orb_default": DEFAULT_H1_ORB, - "h2_orb_default": DEFAULT_H2_ORB, - "block_radius_minutes": BLOCK_RADIUS_MINUTES, - }, - "external_engines": external_engine_status(), - "summary": summary, - "decision": decide(summary), - "cases": rows, - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--from-json", type=Path, default=None) - parser.add_argument("--limit", type=int, default=None) - parser.add_argument("--case-id", type=str, default=None) - parser.add_argument("--skip-orb", action="store_true") - parser.add_argument("--json-out", type=Path, default=ROOT / "docs/research/house_lord_gochara_2026_09_13.json") - parser.add_argument("--md-out", type=Path, default=ROOT / "docs/research/house_lord_gochara_2026_09_13.md") - args = parser.parse_args() - if args.from_json: - previous = json.loads(args.from_json.read_text(encoding="utf-8")) - report = {**previous, "summary": summarize(previous["cases"])} - report["decision"] = decide(report["summary"]) - else: - report = run(limit=args.limit, case_id=args.case_id, include_orb=not args.skip_orb) - args.json_out.parent.mkdir(parents=True, exist_ok=True) - args.json_out.write_text(json.dumps(report, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8") - args.md_out.write_text(render_markdown(report), encoding="utf-8") - print(json.dumps({ - "decision": report["decision"], - "usable_count": report["summary"]["usable_count"], - "errors": report["summary"]["errors"], - "json_out": str(args.json_out), - "md_out": str(args.md_out), - }, ensure_ascii=False, indent=2)) - return 0 if not report["summary"]["errors"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/jev_intent_corpus_build.py b/scripts/research/jev_intent_corpus_build.py deleted file mode 100644 index dfb1668a2..000000000 --- a/scripts/research/jev_intent_corpus_build.py +++ /dev/null @@ -1,1623 +0,0 @@ -#!/usr/bin/env python3 -"""Build the offline Jev intent-classifier corpus (T0). - -Source A: ten fixtures derived from the production classifier test file. -Source B: real staging turns, written outside git (not this script's default). -Source C: model-simulated replies. Labels are assigned first; an independent -reviewer that cannot see the target label keeps only agreements. - -Does not call production `classifyRectificationTurnIntent`. Celebrity names -from the public holdout file never enter user_message. -""" - -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import random -import re -import sys -import threading -import time -import urllib.error -import urllib.request -from collections import Counter -from concurrent.futures import ThreadPoolExecutor, as_completed -from datetime import date -from pathlib import Path -from typing import Any, Iterable, Mapping, Sequence -from uuid import NAMESPACE_URL, uuid5 - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.rectification.probe_question_contract import ( # noqa: E402 - EXISTENCE_STYLE_OPTIONS, - QUALITY_STYLE_OPTIONS, -) -from scripts.research.jev_intent_questions import ( # noqa: E402 - ANSWER_CLASS_VALUES, - enforce_combo, -) - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -SAMPLES_DIR = ROOT / "scripts" / "research" / "jev_intent_samples" -POOL_PATH = SAMPLES_DIR / "question_pool.json" -SYNTHETIC_PATH = SAMPLES_DIR / "synthetic.jsonl" -SIMULATED_PATH = SAMPLES_DIR / "simulated.jsonl" -DISPUTED_PATH = SAMPLES_DIR / "disputed.jsonl" -README_PATH = SAMPLES_DIR / "README.md" -CACHE_DIR = Path(r"G:\Ferti\Jyotisha\.cache\jev_intent") -TODAY = date(2026, 9, 19) -SEED = 20260919 -PROMPT_VERSION = "gen-review-v3" -DEFAULT_MODEL = "deepseek-flash" -DEFAULT_BASE = "https://api.deepseek.com" -GENERATOR_NAME = os.environ.get("DEEPSEEK_MODEL") or DEFAULT_MODEL -REVIEWER_NAME = os.environ.get("DEEPSEEK_MODEL") or DEFAULT_MODEL -DISPUTE_RATE_LIMIT = 0.15 -GEN_TEMPERATURE = 0.85 -REVIEW_TEMPERATURE = 0.0 -MAX_GEN_RETRIES = 3 - -COLLECT_PROMPTS: dict[str, str] = { - "relationship": "感情这边,还记得哪年认真在一起、分开,或结婚吗?有年份就很好。", - "career": "工作上呢,还记得哪年入职、换工作,或职责一下子变重吗?", - "family": "家里如果有结婚、添丁或住院这类事,记得大概哪年就行。", - "education": "上学这边,还记得哪年升学、转学或大考吗?", - "relocation": "有没有哪年搬家,或开始长期住在外地?", - "finance": "钱的方面,还记得哪年收入明显变过、有过大笔支出,或欠过债吗?", - "health_pressure": "身体或压力这边,还记得哪年生病、受伤,或特别难熬的一段时间吗?", -} -COLLECT_RETRY: dict[str, str] = { - "relationship": "回到感情这边——刚才说的工作我记下了,哪年认真在一起或分开还记得吗?", - "career": "回到工作这边——刚才那件我记下了,哪年入职或换工作还记得吗?", - "family": "再问一次家里:结婚、添丁或住院,大概哪年?", - "education": "回到上学这边——哪年升学、转学或大考,还记得吗?", - "relocation": "搬家或开始长期住外地,大概是哪年?", - "finance": "钱的方面再对一下:哪年收入明显变过、有过大笔支出,或欠过债?", - "health_pressure": "身体或压力这边再问一次:哪年生病、受伤,或特别难熬?", -} -TARGETED_YEAR_PROMPT = "大概哪年几月?" -SHUFFLED_CHOICE_PROMPT = "2023 年前后,工作状态是否出现明显变化?" -SHUFFLED_OPTIONS = [ - {"key": "A", "label": "这段时间没有明显变化", "answer_class": "no"}, - {"key": "B", "label": "记不清当时的情况", "answer_class": "unsure"}, - {"key": "C", "label": "变化明显而且时间吻合", "answer_class": "yes"}, - {"key": "D", "label": "有变化但程度比较弱", "answer_class": "weak_yes"}, -] -COLLECT_FINANCE_PROMPT = "钱的方面,还记得哪年收入明显变过吗?" - -PERSONAS = ( - "terse", - "rambling", - "answer_then_event", - "deny_then_event", - "off_topic", - "impatient_stop", - "ask_result", - "dialect_netspeak", -) - -QUOTAS: dict[str, list[tuple[str, str | None, bool, int]]] = { - "choice": [ - ("answer_current_focus", "yes", False, 45), - ("answer_current_focus", "yes", True, 15), - ("answer_current_focus", "weak_yes", False, 45), - ("answer_current_focus", "weak_yes", True, 15), - ("answer_current_focus", "no", False, 30), - ("answer_current_focus", "no", True, 30), - ("answer_current_focus", "unsure", False, 45), - ("answer_current_focus", "unsure", True, 15), - ("provide_new_evidence", None, True, 60), - ("stop_rectification", None, False, 32), - ("ask_about_result", None, False, 32), - ("unclear", None, False, 36), - ], - "collect": [ - ("answer_current_focus", "no", False, 80), - ("answer_current_focus", "no", True, 20), - ("answer_current_focus", "unsure", False, 80), - ("answer_current_focus", "yes", False, 34), - ("answer_current_focus", "yes", True, 16), - ("answer_current_focus", "weak_yes", False, 33), - ("answer_current_focus", "weak_yes", True, 17), - ("provide_new_evidence", None, True, 48), - ("stop_rectification", None, False, 24), - ("ask_about_result", None, False, 24), - ("unclear", None, False, 24), - ], - "none": [ - ("provide_new_evidence", None, True, 50), - ("stop_rectification", None, False, 15), - ("ask_about_result", None, False, 15), - ("unclear", None, False, 20), - ], -} - -PERSONA_SPECS: dict[str, str] = { - "terse": "惜字如金。句子短,像随手回一句,不用语气词堆砌。", - "rambling": "口语啰嗦,会绕半句再落到要点,但仍要把必需要素说清楚。少用「嗯/啊/emmm」。", - "answer_then_event": "先用一两句回答当前问题,再用「另外/对了」补一件别的带年份的事。", - "deny_then_event": "先明确否定当前问题,再补一件别的带年份的事。", - "off_topic": "答非所问,说一件无关的小事。不要提校正结果,不要要求停止,不要报带年份的经历。", - "impatient_stop": "不耐烦,明确说先停、不弄了、停止整套出生时间校正。不要评价当前这件事有没有发生。", - "ask_result": "追问校正结果、时间范围、候选分钟或好了没。不要回答当前这道题。", - "dialect_netspeak": "带一点口语或网络说法,但仍能读懂在说什么。不要整句都是无意义的梗。", -} - -INTENT_NL: dict[str, str] = { - "answer_current_focus": "这句话是在直接回答当前这道题,不是另起一件无关的事,不是要求停止整套校正,也不是在问结果。", - "provide_new_evidence": "这句话没有回答当前这道题,只是另说了一件带大概年份或月份的经历。", - "stop_rectification": "这句话明确要求停止整个出生时间校正。说当前这件事没发生,不算停止。", - "ask_about_result": "这句话在问校正结果、时间范围、候选分钟,或好了没有。不是在答当前题。", - "unclear": "语义不清或答非所问,无法归入回答当前题、补充新经历、停止校正、询问结果。不要提到年份或月份,不要说停,不要问结果。", -} - -ANSWER_NL: dict[str | None, str] = { - "yes": "明确肯定当前问题。点选题对应「明显发生 / 变化明显」;采集题必须用带年月的经历直接回答这道采集题。", - "weak_yes": "有发生或有变化,但程度弱、不太明显、印象不深。不要说完全没有,也不要说非常明显。", - "no": "明确否定当前问题:没有发生、没有变化、这方面没什么。不要再补一句「其实也有一点」。", - "unsure": "记不清、不记得、忘了、想不起来、以后再说。不要给出确定的有或没有。", - None: "不要对当前问题给出肯定、否定或记不清的态度。", -} - -DATED_NL: dict[bool, str] = { - True: ( - "同一句话里,除了完成上面的意图,还必须另说一件带大概年份的经历," - "并且那件事不是对当前问题的直接回答。用「另外 / 对了 / 不过」连接。" - "必须出现四位数字年份,例如「2019年」或「2019年3月」。没有四位年份就不合格。" - ), - False: ( - "不要另说一件带年份或月份的新经历。" - "若当前是采集题且态度是肯定或弱肯定,可以在回答里带上这件事本身的年月," - "那是在答当前题,不是另说一件;这种情况下也必须出现四位数字年份。" - "若不是采集题的肯定回答,不要写任何 19xx / 20xx 年份。" - ), -} - -ALT_EVENT_HINTS: dict[str, str] = { - "education": "工作变动或搬家", - "career": "搬家或升学", - "relocation": "换工作或家里的事", - "relationship": "工作或搬家", - "family": "工作或搬家", - "finance": "换工作或搬家", - "health_pressure": "换工作或搬家", -} - -YEAR_RE = re.compile(r"(?:19|20)\d{2}") -MONTH_RE = re.compile(r"\d{1,2}\s*月") - -GENERATE_SYSTEM = ( - "你在模拟一位真人用户,正在做出生时间校正问答。只输出用户会打的那句话," - "不要解释,不要加引号,不要输出 JSON。" -) - -REVIEW_SYSTEM = ( - "你只做出生时间校正当前轮的意图分类。不回答用户,不修改状态。" - "只输出一个 JSON 对象,不要解释。" -) - -REVIEW_RUBRIC = """根据当前问题和用户回复分类。看不到任何预设标签。 - -intent 只能是: -- answer_current_focus:用户在回答当前问题 -- provide_new_evidence:没有回答当前问题,只补充了一件带大概年或月的经历 -- stop_rectification:明确要求停止整个校正;说当前这件事没发生不是停止 -- ask_about_result:在问结果、范围、候选分钟或好了没 -- unclear:以上都不成立,或混在一起无法单选 - -answer_class: -- 仅当 intent 是 answer_current_focus 时非空,否则必须为 null -- 点选题:按选项 label 的含义选 yes / weak_yes / no / unsure,不要按 A/B/C/D 位置猜 -- 采集题:没有/没发生/这方面没什么 → no;记不清/不记得/忘了/想不起来/以后再说 → unsure; - 用带大概年月的经历直接回答当前采集题 → yes(程度弱则为 weak_yes) -- 不要把「没有」或「记不清」标成 yes -- 采集题若既没有否定、也没有记不清、也没有带年月经历 → intent 为 unclear,answer_class 为 null -- 同一句既明确否定当前采集题又补充了新的带时间经历:intent 仍为 answer_current_focus,answer_class 为 no - -has_new_dated_event: -- 仅在同一句里除了回答当前问题之外,还提供了新的、带大概时间的经历时为 true -- 单纯否定、单纯记不清、或只用带年月经历来直接回答当前采集题,都是 false -- 无当前问题时,带年月的经历 → intent 为 provide_new_evidence,has_new_dated_event 为 true - -只输出: -{"intent":"...","answer_class":"yes"|"weak_yes"|"no"|"unsure"|null,"has_new_dated_event":true|false} -""" - -_CACHE_LOCK = threading.Lock() -_LLM_CACHE: dict[str, Any] = {} -_USAGE = { - "generate_input_tokens": 0, - "generate_output_tokens": 0, - "review_input_tokens": 0, - "review_output_tokens": 0, - "generate_calls": 0, - "review_calls": 0, - "generate_cached": 0, - "review_cached": 0, -} - - -def current_model_id() -> str: - return os.environ.get("DEEPSEEK_MODEL") or DEFAULT_MODEL - - -def sha256_file(path: Path) -> str: - digest = hashlib.sha256() - digest.update(path.read_bytes()) - return digest.hexdigest() - - -def write_jsonl(path: Path, rows: Sequence[Mapping[str, Any]]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - text = "".join(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n" for row in rows) - path.write_text(text, encoding="utf-8") - - -def holdout_name_denylist() -> set[str]: - payload = json.loads(HOLDOUT.read_text(encoding="utf-8")) - names: set[str] = set() - for case in payload.get("cases") or []: - label = str(case.get("subject_label") or "").strip() - if label: - names.add(label) - for part in label.split(): - if len(part) >= 3: - names.add(part) - return names - - -def assert_no_pii(message: str, denylist: set[str]) -> None: - for name in denylist: - if name and name in message: - raise ValueError(f"simulated reply leaked holdout name {name!r}") - - -def source_a_samples() -> list[dict[str, Any]]: - """Ten fixtures from the test file's schema + the two userMessage strings.""" - choice_focus = { - "kind": "choice", - "current_question": SHUFFLED_CHOICE_PROMPT, - "options": SHUFFLED_OPTIONS, - "case_status": "distinguishing_candidates", - } - collect_focus = { - "kind": "collect", - "current_question": COLLECT_FINANCE_PROMPT, - "options": [], - "case_status": "collecting_evidence", - } - rows = [ - ("A01", "choice", choice_focus, "没什么变化", "answer_current_focus", "no", False), - ("A02", "choice", choice_focus, "记不清", "answer_current_focus", "unsure", False), - ("A03", "choice", choice_focus, "变化很明显", "answer_current_focus", "yes", False), - ("A04", "choice", choice_focus, "有一点变化", "answer_current_focus", "weak_yes", False), - ("A05", "choice", choice_focus, "没有,不过 2019 年换过岗", "answer_current_focus", "no", True), - ("A06", "choice", choice_focus, "先不弄了", "stop_rectification", None, False), - ("A07", "choice", choice_focus, "结果出来了吗", "ask_about_result", None, False), - ("A08", "collect", collect_focus, "没有", "answer_current_focus", "no", False), - ("A09", "collect", collect_focus, "随便吧", "unclear", None, False), - ("A10", "collect", collect_focus, "2016年3月入学", "answer_current_focus", "yes", False), - ] - samples: list[dict[str, Any]] = [] - for sid, layer, focus, message, intent, answer_class, dated in rows: - gold = enforce_combo(intent, answer_class, dated) - samples.append({ - "id": sid, - "source": "A", - "layer": layer, - "persona": "test_fixture", - "focus": focus, - "user_message": message, - "gold": gold, - "generator": "test-file", - "reviewer": "manual", - }) - return samples - - -def _hhmm(value: object) -> str | None: - text = str(value or "")[:5] - return text if len(text) == 5 and text[2] == ":" else None - - -def _probe_prompt(probe: Mapping[str, Any]) -> str: - family = str(probe.get("event_family") or "").replace("?", "").replace("?", "").strip() - label = str(probe.get("year_label") or "").strip() - kind = str(probe.get("choice_kind") or "existence") - meaning = str(probe.get("user_meaning") or "").strip() - if kind == "event_quality" and meaning: - from scripts.rectification.probe_question_contract import clipped_probe_label - clipped = clipped_probe_label(meaning) or meaning - if clipped.endswith("?") or clipped.endswith("?"): - return clipped - return f"{label},有没有{family}的时候?" if label and family else clipped - if not family: - return label - if kind == "event_quality": - return f"{label},有没有{family}的时候?" if label else f"有没有{family}的时候?" - return f"{label},有没有{family}?" if label else f"有没有{family}?" - - -def _probe_options(probe: Mapping[str, Any]) -> list[dict[str, str]]: - raw = probe.get("style_options") or [] - rows: list[dict[str, str]] = [] - keys = ("A", "B", "C", "D") - for item in raw: - if not isinstance(item, dict): - continue - answer_class = str(item.get("answer_class") or "") - label = str(item.get("label") or "").strip() - if answer_class not in ANSWER_CLASS_VALUES or not label: - continue - rows.append({"key": keys[len(rows)], "label": label, "answer_class": answer_class}) - if len(rows) == 4: - break - if len(rows) != 4: - catalog = QUALITY_STYLE_OPTIONS if str(probe.get("choice_kind") or "") == "event_quality" else EXISTENCE_STYLE_OPTIONS - rows = [ - {"key": keys[i], "label": str(item["label"]), "answer_class": str(item["answer_class"])} - for i, item in enumerate(catalog) - ] - return rows - - -def build_question_pool(*, max_cases: int | None = None) -> dict[str, Any]: - from scripts.active_rectification_event_engine import AYANAMSA, NODE_MODE - from scripts.rectification.event_probes import discriminating_event_probes - from scripts.rectification.refinement_packet import window_scan - from scripts.rectification.scoring_service import ( - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, - ) - from scripts.research.probe_supply_after_six import request_from_case - - payload = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(payload.get("cases") or []) - if max_cases is not None: - cases = cases[:max_cases] - choice_questions: list[dict[str, Any]] = [] - seen: set[str] = set() - errors: list[str] = [] - for case in cases: - case_id = str(case.get("case_id") or "case") - try: - request = request_from_case(case) - request["ayanamsa"] = AYANAMSA - request["node_mode"] = NODE_MODE - scoring = scoreable_request(request) - built = build_event_contribution_matrix(scoring) - rows = score_from_matrix(scoring, built) - times = [stamp for row in rows if (stamp := _hhmm(row.get("time")))] - true_time = str(case["birth"]["time"])[:5] - probes = discriminating_event_probes( - {**request, "refresh_probes": False, "asked_probe_keys": []}, - built, - scan=window_scan(built), - candidate_times=times, - representative_time=true_time, - today=TODAY, - ) - except Exception as exc: # noqa: BLE001 — keep the other 19 cases - errors.append(f"{case_id}: {type(exc).__name__}") - continue - kept = 0 - for probe in probes: - if not isinstance(probe, dict): - continue - prompt = _probe_prompt(probe) - options = _probe_options(probe) - key = f"{prompt}|{','.join(item['answer_class'] + ':' + item['label'] for item in options)}" - if key in seen or not prompt: - continue - seen.add(key) - choice_questions.append({ - "id": str(uuid5(NAMESPACE_URL, key)), - "layer": "choice", - "current_question": prompt, - "options": options, - "domain": str(probe.get("domain") or ""), - "choice_kind": str(probe.get("choice_kind") or "existence"), - "year_label": str(probe.get("year_label") or ""), - "event_family": str(probe.get("event_family") or ""), - "case_status": "distinguishing_candidates", - }) - kept += 1 - print(f"pool {case_id} probes={len(probes)} unique={kept}", flush=True) - collect_questions: list[dict[str, Any]] = [] - for domain, prompt in COLLECT_PROMPTS.items(): - collect_questions.append({ - "id": f"collect:{domain}", - "layer": "collect", - "current_question": prompt, - "options": [], - "domain": domain, - "case_status": "collecting_evidence", - }) - collect_questions.append({ - "id": f"collect-retry:{domain}", - "layer": "collect", - "current_question": COLLECT_RETRY[domain], - "options": [], - "domain": domain, - "case_status": "collecting_evidence", - }) - collect_questions.append({ - "id": "collect:targeted-year", - "layer": "collect", - "current_question": TARGETED_YEAR_PROMPT, - "options": [], - "domain": "career", - "case_status": "collecting_evidence", - }) - none_questions = [{ - "id": "none:open", - "layer": "none", - "current_question": "", - "options": [], - "domain": "", - "case_status": "collecting_evidence", - }] - pool = { - "choice": choice_questions, - "collect": collect_questions, - "none": none_questions, - "errors": errors, - "holdout": str(HOLDOUT.relative_to(ROOT)).replace("\\", "/"), - "generator_note": "choice prompts from discriminating_event_probes; collect copy from user-copy.ts", - } - return pool - - -def _option_labels(focus: Mapping[str, Any]) -> list[str]: - return [str(item.get("label") or "") for item in (focus.get("options") or []) if item.get("label")] - - -def gold_equal(left: Mapping[str, Any], right: Mapping[str, Any]) -> bool: - return ( - left.get("intent") == right.get("intent") - and left.get("answer_class") == right.get("answer_class") - and bool(left.get("has_new_dated_event")) == bool(right.get("has_new_dated_event")) - ) - - -def _pick_question(pool: Mapping[str, Any], layer: str, rng: random.Random) -> dict[str, Any]: - rows = list(pool.get(layer) or []) - if not rows: - raise RuntimeError(f"empty question pool for layer={layer}") - return dict(rng.choice(rows)) - - -def _has_year_or_month(message: str) -> bool: - return bool(YEAR_RE.search(message) or MONTH_RE.search(message)) - - -def llm_cache_path() -> Path: - return CACHE_DIR / "llm_cache.json" - - -def load_llm_cache() -> None: - path = llm_cache_path() - if not path.is_file(): - return - try: - payload = json.loads(path.read_text(encoding="utf-8")) - except json.JSONDecodeError: - return - if isinstance(payload, dict): - _LLM_CACHE.update(payload) - - -def save_llm_cache() -> None: - CACHE_DIR.mkdir(parents=True, exist_ok=True) - with _CACHE_LOCK: - llm_cache_path().write_text(json.dumps(_LLM_CACHE, ensure_ascii=False), encoding="utf-8") - (CACHE_DIR / "llm_usage.json").write_text(json.dumps(_USAGE, ensure_ascii=False, indent=2), encoding="utf-8") - - -def _parse_model_json(text: str) -> dict[str, Any]: - raw = (text or "").strip() - if raw.startswith("```"): - raw = raw.strip("`") - if raw.lower().startswith("json"): - raw = raw[4:] - raw = raw.strip() - start = raw.find("{") - end = raw.rfind("}") - if start < 0 or end <= start: - raise ValueError("no_json_object") - payload = json.loads(raw[start:end + 1]) - if not isinstance(payload, dict): - raise ValueError("json_not_object") - return payload - - -def _strip_reply(text: str) -> str: - raw = (text or "").strip() - if raw.startswith("```"): - raw = raw.strip("`").strip() - if raw.lower().startswith("text"): - raw = raw[4:].strip() - if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in {'"', "“", "'"}: - raw = raw[1:-1].strip() - return " ".join(raw.split()) - - -def complete_chat( - *, - system: str, - user: str, - temperature: float, - json_mode: bool, - cache_ns: str, - max_tokens: int = 256, - timeout: float = 60.0, -) -> dict[str, Any]: - model = current_model_id() - key_payload = { - "ns": cache_ns, - "prompt_version": PROMPT_VERSION, - "model": model, - "temperature": temperature, - "json_mode": json_mode, - "system": system, - "user": user, - } - cache_key = hashlib.sha256(json.dumps(key_payload, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest() - with _CACHE_LOCK: - cached = _LLM_CACHE.get(cache_key) - if isinstance(cached, dict) and cached.get("text"): - _USAGE[f"{cache_ns}_cached"] = int(_USAGE.get(f"{cache_ns}_cached") or 0) + 1 - return cached - api_key = os.environ.get("DEEPSEEK_API_KEY") or "" - if not api_key: - raise RuntimeError("DEEPSEEK_API_KEY missing") - base = (os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE).rstrip("/") - body: dict[str, Any] = { - "model": model, - "messages": [ - {"role": "system", "content": system}, - {"role": "user", "content": user}, - ], - "temperature": temperature, - "max_tokens": max_tokens, - "thinking": {"type": "disabled"}, - "stream": False, - } - if json_mode: - body["response_format"] = {"type": "json_object"} - request = urllib.request.Request( - f"{base}/chat/completions", - data=json.dumps(body).encode("utf-8"), - headers={ - "Content-Type": "application/json", - "Authorization": f"Bearer {api_key}", - }, - method="POST", - ) - delay = 1.0 - last_error = "unknown" - for _attempt in range(6): - try: - with urllib.request.urlopen(request, timeout=timeout) as response: - payload = json.loads(response.read().decode("utf-8")) - content = (((payload.get("choices") or [{}])[0].get("message") or {}).get("content")) or "" - usage = payload.get("usage") or {} - result = { - "text": content, - "model": payload.get("model") or model, - "input_tokens": usage.get("prompt_tokens") or usage.get("input_tokens") or 0, - "output_tokens": usage.get("completion_tokens") or usage.get("output_tokens") or 0, - } - with _CACHE_LOCK: - _LLM_CACHE[cache_key] = result - _USAGE[f"{cache_ns}_calls"] = int(_USAGE.get(f"{cache_ns}_calls") or 0) + 1 - _USAGE[f"{cache_ns}_input_tokens"] = int(_USAGE.get(f"{cache_ns}_input_tokens") or 0) + int(result["input_tokens"] or 0) - _USAGE[f"{cache_ns}_output_tokens"] = int(_USAGE.get(f"{cache_ns}_output_tokens") or 0) + int(result["output_tokens"] or 0) - return result - except urllib.error.HTTPError as exc: - last_error = f"HTTP{exc.code}" - if exc.code in {429, 500, 502, 503, 529}: - time.sleep(delay) - delay = min(delay * 2, 20) - continue - raise - except Exception as exc: # noqa: BLE001 - last_error = type(exc).__name__ - time.sleep(delay) - delay = min(delay * 2, 20) - raise RuntimeError(f"chat_failed:{last_error}") - - -def build_generate_prompt( - question: Mapping[str, Any], - *, - intent: str, - answer_class: str | None, - dated: bool, - persona: str, - length_lo: int, - length_hi: int, -) -> str: - options = list(question.get("options") or []) - option_lines = [] - for item in options: - option_lines.append( - f"- {item.get('key')}. {item.get('label')}(对应态度:{item.get('answer_class')})" - ) - option_block = "\n".join(option_lines) if option_lines else "(本题没有点选选项)" - extra = "" - if dated: - extra = f"另说的那件事请用「{ALT_EVENT_HINTS.get(str(question.get('domain') or ''), '另一件生活事')}」,不要跟当前问题同一件事。" - return f"""当前问题: -{question.get('current_question') or '(当前没有焦点问题)'} - -选项: -{option_block} - -你必须体现的语义(不要写出这些标签名,不要解释标签): -- 这句话的作用:{INTENT_NL[intent]} -- 对当前问题的态度:{ANSWER_NL[answer_class]} -- 是否另说一件带年月的新经历:{DATED_NL[dated]} -{extra} - -人设:{PERSONA_SPECS[persona]} - -硬约束: -- 只输出用户会打的那句话 -- 字数约 {length_lo}–{length_hi} 个汉字(含标点),不要明显超出 -- 不得逐字复述上面的选项原文 -- 不得出现真实姓名、地名、学校名、公司名、医院名、单位名 -- 不要用「有的 / 发生了 / 就是那段 / 没这回事」这种套话,写得像真人随手打的 -- 需要带时间时,用大概年份或年月,事件用普通生活经历 -""" - - -def build_review_prompt(sample: Mapping[str, Any]) -> str: - focus = sample.get("focus") if isinstance(sample.get("focus"), dict) else {} - options = list(focus.get("options") or []) - option_lines = [] - for item in options: - option_lines.append(f"- {item.get('key')}. {item.get('label')} (answer_class={item.get('answer_class')})") - option_block = "\n".join(option_lines) if option_lines else "(无选项)" - return f"""{REVIEW_RUBRIC} - -当前问题: -{focus.get('current_question') or '(无)'} - -选项: -{option_block} - -用户回复: -{sample.get('user_message') or ''} -""" - - -def review_sample(sample: Mapping[str, Any]) -> dict[str, Any]: - """Independent pass: model JSON label, no access to target labels.""" - prompt = build_review_prompt(sample) - raw = complete_chat( - system=REVIEW_SYSTEM, - user=prompt, - temperature=REVIEW_TEMPERATURE, - json_mode=True, - cache_ns="review", - max_tokens=256, - ) - parsed = _parse_model_json(raw["text"]) - return enforce_combo( - parsed.get("intent"), - parsed.get("answer_class"), - parsed.get("has_new_dated_event"), - ) - - -def _message_ok( - message: str, - *, - question: Mapping[str, Any], - intent: str, - answer_class: str | None, - dated: bool, - length_lo: int, - length_hi: int, - denylist: set[str], -) -> str | None: - if not message or len(message) < 2: - return "too_short" - try: - assert_no_pii(message, denylist) - except ValueError: - return "pii" - for label in _option_labels(question): - if label and label in message: - return "copied_option" - n = len(message) - if n < max(6, length_lo - 8) or n > length_hi + 24: - return "length" - has_date = _has_year_or_month(message) - collect_yes = ( - str(question.get("layer") or "") == "collect" - and intent == "answer_current_focus" - and answer_class in {"yes", "weak_yes"} - ) - if dated and not has_date: - return "missing_date" - if intent == "provide_new_evidence" and not has_date: - return "missing_date" - if collect_yes and not has_date: - return "collect_yes_needs_date" - if intent in {"stop_rectification", "ask_about_result", "unclear"} and not dated and has_date: - return "unexpected_date" - if intent == "answer_current_focus" and answer_class in {"no", "unsure"} and not dated and has_date: - return "unexpected_date" - return None - - -def generate_reply( - question: Mapping[str, Any], - *, - intent: str, - answer_class: str | None, - dated: bool, - persona: str, - length_lo: int, - length_hi: int, - attempt: int, - last_reason: str | None = None, -) -> str: - user = build_generate_prompt( - question, - intent=intent, - answer_class=answer_class, - dated=dated, - persona=persona, - length_lo=length_lo, - length_hi=length_hi, - ) - if dated or intent == "provide_new_evidence" or ( - str(question.get("layer") or "") == "collect" - and intent == "answer_current_focus" - and answer_class in {"yes", "weak_yes"} - ): - user += "\n再次强调:回复里必须出现一个四位数字年份(19xx 或 20xx)。" - if attempt: - user += f"\n这是第 {attempt + 1} 次重写,请换一种说法,不要重复上次的句子。" - if last_reason in {"missing_date", "collect_yes_needs_date"}: - user += "上次缺少四位年份,这次必须写上例如 2017年3月。" - elif last_reason == "unexpected_date": - user += "上次多写了年份,这次不要出现 19xx 或 20xx。" - elif last_reason == "copied_option": - user += "上次逐字复述了选项原文,这次换自己的话。" - elif last_reason == "length": - user += "上次字数不合要求,这次严格落在指定字数区间。" - raw = complete_chat( - system=GENERATE_SYSTEM, - user=user, - temperature=GEN_TEMPERATURE, - json_mode=False, - cache_ns="generate", - max_tokens=220, - ) - return _strip_reply(raw["text"]) - - -def length_stats(messages: Iterable[str]) -> dict[str, float]: - lengths = sorted(len(item) for item in messages) - if not lengths: - return {"n": 0, "p25": 0, "median": 0, "p75": 0} - - def pct(p: float) -> float: - if len(lengths) == 1: - return float(lengths[0]) - idx = int(round((len(lengths) - 1) * p)) - return float(lengths[idx]) - - return { - "n": len(lengths), - "p25": pct(0.25), - "median": pct(0.5), - "p75": pct(0.75), - "min": float(lengths[0]), - "max": float(lengths[-1]), - } - - -def quota_deviation(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - by_layer: dict[str, Counter[tuple[str, str | None, bool]]] = { - "choice": Counter(), - "collect": Counter(), - "none": Counter(), - } - for row in rows: - layer = str(row.get("layer") or "") - gold = row.get("gold") or {} - if layer not in by_layer: - continue - by_layer[layer][( - str(gold.get("intent")), - gold.get("answer_class"), - bool(gold.get("has_new_dated_event")), - )] += 1 - report: dict[str, Any] = {} - for layer, spec in QUOTAS.items(): - target_total = sum(item[3] for item in spec) - actual_total = sum(by_layer[layer].values()) - cells = [] - for intent, answer_class, dated, count in spec: - actual = by_layer[layer][(intent, answer_class, dated)] - share_target = count / target_total if target_total else 0 - share_actual = actual / actual_total if actual_total else 0 - cells.append({ - "intent": intent, - "answer_class": answer_class, - "has_new_dated_event": dated, - "target": count, - "actual": actual, - "share_delta": share_actual - share_target, - }) - max_delta = max((abs(cell["share_delta"]) for cell in cells), default=0.0) - report[layer] = { - "target_total": target_total, - "actual_total": actual_total, - "max_share_delta": max_delta, - "within_20pct": max_delta <= 0.20, - "cells": cells, - } - return report - - -def persona_stats(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - scoped = [row for row in rows if row.get("layer") in {"choice", "collect"}] - counts = Counter(str(row.get("persona") or "") for row in scoped) - terse_dialect = counts.get("terse", 0) + counts.get("dialect_netspeak", 0) - n = max(len(rows), 1) - n_scoped = max(len(scoped), 1) - return { - "choice_collect": dict(counts), - "all": dict(Counter(str(row.get("persona") or "") for row in rows)), - "each_ge_40": all(counts.get(name, 0) >= 40 for name in PERSONAS), - "terse_dialect_share_all": (Counter(str(row.get("persona") or "") for row in rows).get("terse", 0) - + Counter(str(row.get("persona") or "") for row in rows).get("dialect_netspeak", 0)) / n, - "terse_dialect_share_choice_collect": terse_dialect / n_scoped, - "min_choice_collect": min((counts.get(name, 0) for name in PERSONAS), default=0), - } - - -def uniqueness_stats(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - messages = [str(row.get("user_message") or "") for row in rows] - counts = Counter(messages) - return { - "n": len(messages), - "unique": len(counts), - "max_repeat": max(counts.values()) if counts else 0, - "unique_ok": len(counts) >= 810, - "repeat_ok": (max(counts.values()) if counts else 0) <= 5, - } - - -def length_ok(stats: Mapping[str, Any]) -> bool: - return 8 <= float(stats.get("p25") or 0) <= 16 and 15 <= float(stats.get("median") or 0) <= 27 and 20 <= float(stats.get("p75") or 0) <= 36 - - -def _compatible_personas(intent: str, dated: bool) -> list[str]: - names = ["rambling", "terse", "dialect_netspeak"] - if intent == "stop_rectification": - names.append("impatient_stop") - if intent == "ask_about_result": - names.append("ask_result") - if intent == "unclear": - names.append("off_topic") - if intent == "answer_current_focus" and dated: - names.append("answer_then_event") - if intent == "answer_current_focus" and dated: - names.append("deny_then_event") - return names - - -def _assign_persona(intent: str, dated: bool, answer_class: str | None, rng: random.Random, remaining: Counter[str]) -> str: - preferred: list[str] = [] - if intent == "stop_rectification" and remaining["impatient_stop"] > 0: - preferred.append("impatient_stop") - if intent == "ask_about_result" and remaining["ask_result"] > 0: - preferred.append("ask_result") - if intent == "unclear" and remaining["off_topic"] > 0: - preferred.append("off_topic") - if intent == "answer_current_focus" and dated and answer_class == "no" and remaining["deny_then_event"] > 0: - preferred.append("deny_then_event") - if intent == "answer_current_focus" and dated and remaining["answer_then_event"] > 0: - preferred.append("answer_then_event") - if preferred: - name = preferred[0] - remaining[name] -= 1 - return name - weighted: list[str] = [] - for name, weight in (("rambling", 5), ("terse", 2), ("dialect_netspeak", 2)): - if remaining[name] > 0: - weighted.extend([name] * weight) - if not weighted: - weighted = [name for name in _compatible_personas(intent, dated)] - name = rng.choice(weighted) - if remaining[name] > 0: - remaining[name] -= 1 - return name - - -def _length_bounds(persona: str, rng: random.Random) -> tuple[int, int]: - if persona == "terse": - lo = rng.randint(8, 12) - return lo, min(16, lo + rng.randint(3, 6)) - if persona == "rambling": - lo = rng.randint(22, 28) - return lo, min(36, lo + rng.randint(4, 8)) - if persona == "dialect_netspeak": - lo = rng.randint(12, 18) - return lo, min(30, lo + rng.randint(6, 10)) - lo = rng.randint(12, 18) - return lo, min(32, lo + rng.randint(6, 12)) - - -def plan_slots(pool: Mapping[str, Any], *, seed: int, extra_factor: float) -> list[dict[str, Any]]: - rng = random.Random(seed) - remaining = Counter({ - "terse": 80, - "dialect_netspeak": 80, - "rambling": 260, - "answer_then_event": 120, - "deny_then_event": 50, - "off_topic": 48, - "impatient_stop": 48, - "ask_result": 48, - }) - slots: list[dict[str, Any]] = [] - counters = {"choice": 0, "collect": 0, "none": 0} - for layer, rows in QUOTAS.items(): - for intent, answer_class, dated, count in rows: - need = int(round(count * extra_factor)) - for _ in range(need): - counters[layer] += 1 - persona = _assign_persona(intent, dated, answer_class, rng, remaining) - lo, hi = _length_bounds(persona, rng) - question = _pick_question(pool, layer, rng) - slots.append({ - "id": f"C-{layer}-{counters[layer]:04d}", - "layer": layer, - "intent": intent, - "answer_class": answer_class, - "dated": dated, - "persona": persona, - "length_lo": lo, - "length_hi": hi, - "question": question, - }) - rng.shuffle(slots) - return slots - - -def _sample_from_slot(slot: Mapping[str, Any], message: str, reviewed: Mapping[str, Any] | None) -> dict[str, Any]: - question = slot["question"] - layer = str(slot["layer"]) - gold = enforce_combo(slot["intent"], slot["answer_class"], slot["dated"]) - focus = { - "kind": layer if layer != "none" else None, - "current_question": str(question.get("current_question") or ""), - "options": list(question.get("options") or []), - "case_status": str(question.get("case_status") or "collecting_evidence"), - } - row = { - "id": slot["id"], - "source": "C", - "layer": layer, - "persona": slot["persona"], - "focus": focus, - "user_message": message, - "gold": gold, - "generator": GENERATOR_NAME, - "reviewer": REVIEWER_NAME, - "target_before_review": gold, - "prompt_version": PROMPT_VERSION, - } - if reviewed is not None: - row["review"] = reviewed - return row - - -def fill_slot( - slot: Mapping[str, Any], - *, - denylist: set[str], -) -> tuple[dict[str, Any], bool]: - last_sample: dict[str, Any] | None = None - last_reason: str | None = None - for attempt in range(MAX_GEN_RETRIES): - try: - message = generate_reply( - slot["question"], - intent=slot["intent"], - answer_class=slot["answer_class"], - dated=slot["dated"], - persona=slot["persona"], - length_lo=int(slot["length_lo"]), - length_hi=int(slot["length_hi"]), - attempt=attempt, - last_reason=last_reason, - ) - except Exception as exc: # noqa: BLE001 - last_sample = _sample_from_slot(slot, f"[generate_error:{type(exc).__name__}]", None) - continue - reason = _message_ok( - message, - question=slot["question"], - intent=slot["intent"], - answer_class=slot["answer_class"], - dated=slot["dated"], - length_lo=int(slot["length_lo"]), - length_hi=int(slot["length_hi"]), - denylist=denylist, - ) - if reason: - last_reason = reason - last_sample = _sample_from_slot(slot, message, None) - last_sample["reject_reason"] = reason - continue - sample = _sample_from_slot(slot, message, None) - try: - reviewed = review_sample(sample) - except Exception as exc: # noqa: BLE001 - sample["reject_reason"] = f"review_error:{type(exc).__name__}" - last_sample = sample - continue - sample["review"] = reviewed - if gold_equal(sample["gold"], reviewed): - return sample, True - last_sample = sample - if last_sample is None: - last_sample = _sample_from_slot(slot, "", None) - return last_sample, False - - -def progress_paths() -> tuple[Path, Path]: - return CACHE_DIR / "source_c_accepted.jsonl", CACHE_DIR / "source_c_disputed.jsonl" - - -def load_progress() -> tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]]]: - accepted_path, disputed_path = progress_paths() - accepted: dict[str, dict[str, Any]] = {} - disputed: dict[str, dict[str, Any]] = {} - for path, dest in ((accepted_path, accepted), (disputed_path, disputed)): - if not path.is_file(): - continue - for line in path.read_text(encoding="utf-8").splitlines(): - if not line.strip(): - continue - row = json.loads(line) - if row.get("prompt_version") != PROMPT_VERSION: - continue - dest[str(row.get("id"))] = row - return accepted, disputed - - -def append_progress(path: Path, row: Mapping[str, Any]) -> None: - CACHE_DIR.mkdir(parents=True, exist_ok=True) - with _CACHE_LOCK: - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n") - - -def select_simulated(accepted_rows: Sequence[Mapping[str, Any]], *, seed: int) -> list[dict[str, Any]]: - rng = random.Random(seed + 17) - style = {"terse", "dialect_netspeak"} - by_bucket: dict[tuple[str, str, str | None, bool], list[dict[str, Any]]] = {} - for sample in accepted_rows: - gold = sample.get("gold") or {} - key = ( - str(sample.get("layer")), - str(gold.get("intent")), - gold.get("answer_class"), - bool(gold.get("has_new_dated_event")), - ) - by_bucket.setdefault(key, []).append(dict(sample)) - for bucket in by_bucket.values(): - rng.shuffle(bucket) - selected: list[dict[str, Any]] = [] - used_ids: set[str] = set() - persona_all: Counter[str] = Counter() - persona_cc: Counter[str] = Counter() - message_kept: Counter[str] = Counter() - - def bucket_key(row: Mapping[str, Any]) -> tuple[str, str, str | None, bool]: - gold = row.get("gold") or {} - return ( - str(row.get("layer")), - str(gold.get("intent")), - gold.get("answer_class"), - bool(gold.get("has_new_dated_event")), - ) - - def can_take(row: Mapping[str, Any], *, allow_style: bool, cap_style: bool) -> bool: - persona = str(row.get("persona") or "") - message = str(row.get("user_message") or "") - if not message or row.get("id") in used_ids: - return False - if message_kept[message] >= 5: - return False - if persona in style and not allow_style: - return False - if cap_style and persona in style and persona_all[persona] >= 80: - return False - if cap_style and persona in style and persona_all["terse"] + persona_all["dialect_netspeak"] >= 180: - return False - return True - - def commit(row: Mapping[str, Any]) -> None: - selected.append(dict(row)) - used_ids.add(str(row["id"])) - persona = str(row.get("persona") or "") - persona_all[persona] += 1 - if row.get("layer") in {"choice", "collect"}: - persona_cc[persona] += 1 - message_kept[str(row.get("user_message") or "")] += 1 - - def uncommit(index: int) -> dict[str, Any]: - row = selected.pop(index) - used_ids.discard(str(row["id"])) - persona = str(row.get("persona") or "") - persona_all[persona] -= 1 - if row.get("layer") in {"choice", "collect"}: - persona_cc[persona] -= 1 - message_kept[str(row.get("user_message") or "")] -= 1 - return row - - for layer, rows in QUOTAS.items(): - for intent, answer_class, dated, count in rows: - bucket = list(by_bucket.get((layer, intent, answer_class, dated), [])) - taken = 0 - for allow_style in (False, True): - for item in bucket: - if taken >= count: - break - if can_take(item, allow_style=allow_style, cap_style=False): - commit(item) - taken += 1 - layer_target = {layer: sum(cell[3] for cell in spec) for layer, spec in QUOTAS.items()} - leftovers = [row for row in accepted_rows if row.get("id") not in used_ids] - rng.shuffle(leftovers) - for allow_style in (False, True): - for item in leftovers: - if len(selected) >= 900: - break - layer = str(item.get("layer") or "none") - layer_n = sum(1 for row in selected if row.get("layer") == layer) - if layer_n >= layer_target.get(layer, 0): - continue - if can_take(item, allow_style=allow_style, cap_style=True): - commit(item) - for allow_style in (False, True): - for item in leftovers: - if len(selected) >= 900: - break - if can_take(item, allow_style=allow_style, cap_style=True): - commit(item) - - def leftovers_now() -> list[dict[str, Any]]: - return [row for row in accepted_rows if row.get("id") not in used_ids] - - def find_replacement(*, persona_name: str | None, non_style: bool, layer: str | None, same_bucket: tuple | None) -> dict[str, Any] | None: - for item in leftovers_now(): - if message_kept[str(item.get("user_message") or "")] >= 5: - continue - if persona_name and str(item.get("persona") or "") != persona_name: - continue - if non_style and str(item.get("persona") or "") in style: - continue - if layer and str(item.get("layer") or "") != layer: - continue - if same_bucket and bucket_key(item) != same_bucket: - continue - return item - return None - - for persona_name in PERSONAS: - while persona_cc[persona_name] < 40: - replacement = find_replacement(persona_name=persona_name, non_style=False, layer=None, same_bucket=None) - if replacement is None or str(replacement.get("layer") or "") not in {"choice", "collect"}: - break - victim_index = None - for index, row in enumerate(selected): - victim_persona = str(row.get("persona") or "") - if row.get("layer") not in {"choice", "collect"}: - continue - if victim_persona == persona_name: - continue - if persona_cc[victim_persona] <= 40: - continue - if str(replacement.get("layer")) != str(row.get("layer")): - continue - victim_index = index - break - if victim_index is None: - break - uncommit(victim_index) - commit(replacement) - - changed = True - while changed and persona_all["terse"] + persona_all["dialect_netspeak"] > 180: - changed = False - for index, row in enumerate(list(selected)): - persona = str(row.get("persona") or "") - if persona not in style: - continue - if row.get("layer") in {"choice", "collect"} and persona_cc[persona] <= 40: - continue - replacement = ( - find_replacement(persona_name=None, non_style=True, layer=str(row.get("layer")), same_bucket=bucket_key(row)) - or find_replacement(persona_name=None, non_style=True, layer=str(row.get("layer")), same_bucket=None) - ) - if replacement is None: - continue - uncommit(index) - commit(replacement) - changed = True - break - return selected[:900] - - -def generate_source_c( - pool: Mapping[str, Any], - *, - seed: int = SEED, - extra_factor: float = 1.4, - workers: int = 8, - limit: int = 0, -) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: - load_llm_cache() - denylist = holdout_name_denylist() - slots = plan_slots(pool, seed=seed, extra_factor=extra_factor) - if limit: - slots = slots[:limit] - accepted_map, disputed_map = load_progress() - pending = [slot for slot in slots if slot["id"] not in accepted_map and slot["id"] not in disputed_map] - print(f"slots={len(slots)} pending={len(pending)} cached_ok={len(accepted_map)} cached_bad={len(disputed_map)}", flush=True) - accepted_path, disputed_path = progress_paths() - done = 0 - if pending: - with ThreadPoolExecutor(max_workers=max(1, workers)) as pool_ex: - futures = {pool_ex.submit(fill_slot, slot, denylist=denylist): slot for slot in pending} - for future in as_completed(futures): - slot = futures[future] - try: - sample, ok = future.result() - except Exception as exc: # noqa: BLE001 - sample = _sample_from_slot(slot, f"[worker_error:{type(exc).__name__}]", None) - ok = False - if ok: - accepted_map[sample["id"]] = sample - append_progress(accepted_path, sample) - else: - disputed_map[sample["id"]] = sample - append_progress(disputed_path, sample) - done += 1 - if done % 20 == 0 or done == len(pending): - save_llm_cache() - print( - f" fill {done}/{len(pending)} accepted={len(accepted_map)} disputed={len(disputed_map)}", - flush=True, - ) - save_llm_cache() - selected = select_simulated(list(accepted_map.values()), seed=seed) - disputed = list(disputed_map.values()) - generated = len(accepted_map) + len(disputed_map) - stats = { - "generated": generated, - "accepted_raw": len(accepted_map), - "accepted": len(selected), - "disputed": len(disputed_map), - "dispute_rate": (len(disputed_map) / max(generated, 1)), - "generator": GENERATOR_NAME, - "reviewer": REVIEWER_NAME, - "prompt_version": PROMPT_VERSION, - "seed": seed, - "usage": dict(_USAGE), - } - return selected, list(disputed_map.values()), stats - - -def dispute_breakdown(rows: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - by_layer: Counter[str] = Counter() - by_intent: Counter[str] = Counter() - for row in rows: - by_layer[str(row.get("layer") or "")] += 1 - gold = row.get("gold") or {} - by_intent[str(gold.get("intent") or "")] += 1 - return {"by_layer": dict(by_layer), "by_intent": dict(by_intent)} - - -def write_readme( - *, - synthetic_sha: str, - simulated_sha: str, - disputed_sha: str, - pool_n: int, - source_c_stats: Mapping[str, Any], - quotas: Mapping[str, Any], - lengths: Mapping[str, Any], - source_b_n: int, - personas: Mapping[str, Any], - uniqueness: Mapping[str, Any], - disputes: Mapping[str, Any], -) -> None: - source_b_sql = """ -select - t.id as turn_id, - t.user_message, - t.status as turn_status, - t.created_at, - c.status as case_status, - f.question_id, - f.expected_answer_schema, - f.status as focus_status -from public.agentic_rectification_turns t -join public.agentic_rectification_cases c on c.id = t.case_id -left join public.agentic_rectification_conversation_focuses f - on f.case_id = t.case_id - and f.status = 'active' -where t.user_message is not null - and length(btrim(t.user_message)) > 0 -order by t.created_at desc -limit 500; -""".strip() - generate_prompt = build_generate_prompt( - { - "current_question": SHUFFLED_CHOICE_PROMPT, - "options": SHUFFLED_OPTIONS, - "domain": "career", - "layer": "choice", - }, - intent="answer_current_focus", - answer_class="no", - dated=False, - persona="rambling", - length_lo=16, - length_hi=28, - ) - review_prompt = build_review_prompt({ - "focus": { - "current_question": SHUFFLED_CHOICE_PROMPT, - "options": SHUFFLED_OPTIONS, - }, - "user_message": "(用户回复)", - }) - text = f"""# Jev 意图分类样本(T0) - -## 来源 A · 既有合成样本(提交) - -`synthetic.jsonl`,10 条。生产测试 `frontend/tests/rectification-turn-intent-classifier.test.ts` **没有** 10 条带期望输出的 `userMessage` 夹具;本文件用该测试的 `SHUFFLED_CHOICE` 焦点、采集题 prompt,以及测试里实际出现的两句 `userMessage`(`2016年3月入学`、`随便吧`)按分类器提示词写成带标签样本。 - -sha256: `{synthetic_sha}` - -## 来源 B · 真实会话(本地,不提交) - -作用:校准锚,不是主测试集。最少 30 条;不足则代表性检验只报数不判定。 - -- 抽取 SQL(staging,`agentic_rectification_turns.user_message` 非空): - -```sql -{source_b_sql} -``` - -- 本地路径(worktree 外,已 gitignore):`G:/Ferti/Jyotisha/.cache/jev_intent/source_b.jsonl` -- 本机抽取条数:{source_b_n} -- 真值:执行方逐条人工标注;能从后续动作反推的另存 `runtime_intent` 列。**不得提交原文。** - -## 来源 C · 模型模拟语料(提交,主测试集) - -`simulated.jsonl`。问题池 `question_pool.json`:20 例公开 AA holdout 走 `discriminating_event_probes` 出点选题;采集题用 `USER_COLLECT_QUESTION` / retry / `TARGETED_YEAR_PROMPT`。生成与复核各一次真实模型调用;复核看不到目标标签。 - -- 生成模型:`{GENERATOR_NAME}`(temperature {GEN_TEMPERATURE},prompt_version `{PROMPT_VERSION}`) -- 复核模型:`{REVIEWER_NAME}`(temperature {REVIEW_TEMPERATURE},同一家模型、不同提示、看不到标签) -- 生成统计:{json.dumps(source_c_stats, ensure_ascii=False)} -- 争议分层:{json.dumps(disputes, ensure_ascii=False)} -- 配额:{json.dumps({k: {'actual': v['actual_total'], 'target': v['target_total'], 'max_share_delta': v['max_share_delta'], 'ok': v['within_20pct']} for k, v in quotas.items()}, ensure_ascii=False)} -- 长度:{json.dumps(lengths, ensure_ascii=False)} -- 人设:{json.dumps(personas, ensure_ascii=False)} -- 去重:{json.dumps(uniqueness, ensure_ascii=False)} -- sha256 simulated: `{simulated_sha}` -- sha256 disputed: `{disputed_sha}` -- 问题池条数(点选题):{pool_n} - -### 生成提示原文 - -系统:`{GENERATE_SYSTEM}` - -用户提示模板示例: - -``` -{generate_prompt} -``` - -### 复核提示原文 - -系统:`{REVIEW_SYSTEM}` - -用户提示模板示例: - -``` -{review_prompt} -``` - -公开案例姓名不得出现在回复正文。 -""" - README_PATH.write_text(text, encoding="utf-8") - - -def load_source_b() -> list[dict[str, Any]]: - path = Path(r"G:\Ferti\Jyotisha\.cache\jev_intent\source_b.jsonl") - if not path.is_file(): - return [] - rows = [] - for line in path.read_text(encoding="utf-8").splitlines(): - if line.strip(): - rows.append(json.loads(line)) - return rows - - -def _print_gate(selected: Sequence[Mapping[str, Any]], stats: Mapping[str, Any]) -> int: - quotas = quota_deviation(selected) - lengths = length_stats(str(row.get("user_message") or "") for row in selected) - personas = persona_stats(selected) - uniqueness = uniqueness_stats(selected) - print(json.dumps({ - "simulated": len(selected), - "stats": stats, - "quotas": {k: {"actual": v["actual_total"], "ok": v["within_20pct"], "delta": v["max_share_delta"]} for k, v in quotas.items()}, - "lengths": lengths, - "personas": personas, - "uniqueness": uniqueness, - "length_ok": length_ok(lengths), - }, ensure_ascii=False, indent=2), flush=True) - failed = [] - if len(selected) < 900: - failed.append("simulated<900") - layer_n = Counter(str(row.get("layer")) for row in selected) - if not ( - 320 <= layer_n.get("choice", 0) <= 480 - and 320 <= layer_n.get("collect", 0) <= 480 - and 80 <= layer_n.get("none", 0) <= 120 - ): - failed.append("layer_totals") - if not all(quotas[layer]["within_20pct"] for layer in quotas): - failed.append("quota") - if not length_ok(lengths): - failed.append("length") - if not uniqueness["unique_ok"] or not uniqueness["repeat_ok"]: - failed.append("uniqueness") - if personas["min_choice_collect"] < 40: - failed.append("persona_min") - if personas["terse_dialect_share_all"] > 0.20: - failed.append("terse_dialect") - if failed: - print("FAILED constraints: " + ",".join(failed), flush=True) - return 1 - return 0 - - -def main(argv: Sequence[str] | None = None) -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--pool-only", action="store_true") - parser.add_argument("--reuse-pool", action="store_true", default=True) - parser.add_argument("--rebuild-pool", action="store_true") - parser.add_argument("--max-cases", type=int, default=None) - parser.add_argument("--seed", type=int, default=SEED) - parser.add_argument("--workers", type=int, default=8) - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--extra-factor", type=float, default=1.4) - parser.add_argument("--reselect-only", action="store_true") - args = parser.parse_args(argv) - SAMPLES_DIR.mkdir(parents=True, exist_ok=True) - reuse = args.reuse_pool and not args.rebuild_pool and POOL_PATH.is_file() and not args.pool_only - if reuse: - pool = json.loads(POOL_PATH.read_text(encoding="utf-8")) - print(f"reusing question pool choice={len(pool.get('choice') or [])}", flush=True) - else: - print("building question pool from holdout + discriminating_event_probes", flush=True) - pool = build_question_pool(max_cases=args.max_cases) - POOL_PATH.write_text(json.dumps(pool, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print( - f"pool choice={len(pool['choice'])} collect={len(pool['collect'])} errors={pool['errors']}", - flush=True, - ) - if args.pool_only: - return 0 - if not args.reselect_only and not os.environ.get("DEEPSEEK_API_KEY"): - print("DEEPSEEK_API_KEY missing", file=sys.stderr) - return 2 - synthetic = source_a_samples() - write_jsonl(SYNTHETIC_PATH, synthetic) - if args.reselect_only: - accepted_map, disputed_map = load_progress() - accepted = select_simulated(list(accepted_map.values()), seed=args.seed) - disputed = list(disputed_map.values()) - usage_path = CACHE_DIR / "llm_usage.json" - usage = dict(_USAGE) - if usage_path.is_file(): - try: - usage = json.loads(usage_path.read_text(encoding="utf-8")) - except json.JSONDecodeError: - pass - stats = { - "generated": len(accepted_map) + len(disputed_map), - "accepted_raw": len(accepted_map), - "accepted": len(accepted), - "disputed": len(disputed_map), - "dispute_rate": (len(disputed_map) / max(len(accepted_map) + len(disputed_map), 1)), - "generator": GENERATOR_NAME, - "reviewer": REVIEWER_NAME, - "prompt_version": PROMPT_VERSION, - "seed": args.seed, - "usage": usage, - "reselect_only": True, - } - else: - accepted, disputed, stats = generate_source_c( - pool, - seed=args.seed, - extra_factor=args.extra_factor, - workers=args.workers, - limit=args.limit, - ) - if stats["dispute_rate"] > DISPUTE_RATE_LIMIT: - print( - f"dispute_rate={stats['dispute_rate']:.3f} > 0.15 (prompt_version={PROMPT_VERSION})", - flush=True, - ) - write_jsonl(SIMULATED_PATH, accepted) - write_jsonl(DISPUTED_PATH, disputed) - quotas = quota_deviation(accepted) - lengths = length_stats(str(row.get("user_message") or "") for row in accepted) - personas = persona_stats(accepted) - uniqueness = uniqueness_stats(accepted) - source_b = load_source_b() - write_readme( - synthetic_sha=sha256_file(SYNTHETIC_PATH), - simulated_sha=sha256_file(SIMULATED_PATH), - disputed_sha=sha256_file(DISPUTED_PATH), - pool_n=len(pool.get("choice") or []), - source_c_stats=stats, - quotas=quotas, - lengths=lengths, - source_b_n=len(source_b), - personas=personas, - uniqueness=uniqueness, - disputes=dispute_breakdown(disputed), - ) - print(json.dumps({ - "synthetic": len(synthetic), - "simulated": len(accepted), - "disputed": len(disputed), - "stats": stats, - "quotas": {k: {"actual": v["actual_total"], "ok": v["within_20pct"], "delta": v["max_share_delta"]} for k, v in quotas.items()}, - "lengths": lengths, - "personas": personas, - "uniqueness": uniqueness, - "source_b": len(source_b), - "sha256": { - "synthetic": sha256_file(SYNTHETIC_PATH), - "simulated": sha256_file(SIMULATED_PATH), - "disputed": sha256_file(DISPUTED_PATH), - }, - }, ensure_ascii=False, indent=2)) - if args.limit: - return 0 - if stats["dispute_rate"] > DISPUTE_RATE_LIMIT: - print("WARN: dispute_rate still > 15%; proceeding per 让步 1, not falling back to templates", flush=True) - return _print_gate(accepted, stats) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/midnight_date_anchor_regression.py b/scripts/research/midnight_date_anchor_regression.py deleted file mode 100644 index 57a37ff16..000000000 --- a/scripts/research/midnight_date_anchor_regression.py +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env python3 -"""Independent-process native A/B and dated-window goldens; not an accuracy benchmark.""" -from __future__ import annotations - -import argparse -import hashlib -import importlib -import json -import sys -import subprocess -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[2] - - -def load(root: Path): - for name in list(sys.modules): - if name == "scripts" or name.startswith("scripts."): - del sys.modules[name] - sys.path.insert(0, str(root)) - importlib.invalidate_caches() - from scripts.rectification.api_service import score_candidates - from scripts.research.probe_supply_after_six import request_from_case - from scripts.rectification.decision_policy import indistinguishable_width_minutes - return score_candidates, request_from_case, indistinguishable_width_minutes - - -def canonical(value): - return json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode() - - -def projection(result, width): - new_fields = {"candidate_id", "candidate_date", "window_index", "window_offset_minutes", "segment_index", "cluster_intervals"} - return { - "candidate_scores": result["candidate_scores"], - "matrix": result["event_contribution_matrix"], - "decisions": [{key: value for key, value in row.items() if key not in new_fields} for row in result["candidate_decisions"]], - "width": width(result["candidate_decisions"]), - "confirmation_allowed": result["confirmation_allowed"], - "selection_allowed": result["selection_allowed"], - "representative_time": result["decision_receipt"]["representative_time"], - } - - -def worker(root: Path, dated: bool): - score, make_request, width = load(root) - dataset = ROOT / "references/real_case_calibration/minute_rectification_holdout_v3.json" - result = [] - for case in json.loads(dataset.read_text(encoding="utf-8"))["cases"][:3]: - request = make_request(case) - if dated: - request["candidate_intervals"] = [{"start_at": f'{request["birth_date"]}T{request["start_time"]}', "end_at": f'{request["birth_date"]}T{request["end_time"]}'}] - result.append(projection(score(request, include_internal=True), width)) - print(json.dumps(result)) - - -def independent(root: Path, dated: bool): - completed = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--worker", str(root), *( ["--dated"] if dated else [])], - cwd=root, check=True, capture_output=True, text=True, encoding="utf-8") - return json.loads(completed.stdout) - - -def main(): - if "--worker" in sys.argv: - worker(Path(sys.argv[sys.argv.index("--worker") + 1]), "--dated" in sys.argv) - return - parser = argparse.ArgumentParser() - parser.add_argument("--baseline", type=Path, required=True) - parser.add_argument("--output", type=Path, default=ROOT / "artifacts/midnight-date-anchor") - parser.add_argument("--golden", action="store_true") - parser.add_argument("--golden-path", type=Path, default=ROOT / "frontend/tests/fixtures/rectification-midnight-date-anchor.native.json") - args = parser.parse_args() - args.output.mkdir(parents=True, exist_ok=True) - dataset = ROOT / "references/real_case_calibration/minute_rectification_holdout_v3.json" - cases = json.loads(dataset.read_text(encoding="utf-8"))["cases"][:3] - assert all(case["birth"]["source"]["rodden_rating"] == "AA" for case in cases) - old = independent(args.baseline, False) - current = independent(ROOT, True) - comparisons = [] - for case, before, after in zip(cases, old, current): - fields = {key: canonical(before[key]) == canonical(after[key]) for key in before} - comparisons.append({"case_id": case["case_id"], "source": case["birth"]["source"], "fields": fields, - "before_sha256": hashlib.sha256(canonical(before)).hexdigest(), "after_sha256": hashlib.sha256(canonical(after)).hexdigest(), - "candidate_minutes": len(after["candidate_scores"]), "public_clusters": len(after["decisions"]), "width": after["width"]}) - print("current", case["case_id"], fields, flush=True) - report = {"baseline": str(args.baseline), "dataset_sha256": hashlib.sha256(dataset.read_bytes()).hexdigest(), - "same_machine_independent_processes": True, "python_executable": sys.executable, "numeric_tolerance": 0, "comparisons": comparisons, - "excluded_fields": "new date/ordinal metadata; result/candidate IDs intentionally change with algorithm identity"} - with (args.output / "independent-process-aa-ab.json").open("x", encoding="utf-8") as stream: - json.dump(report, stream, indent=2) - assert all(all(row["fields"].values()) for row in comparisons), "same-day native A/B changed" - if args.golden: - score, _, _ = load(ROOT) - # Explicitly fictional birth/event facts; response is produced only by the unmocked native engine. - request = {"birth_date": "2000-03-01", "start_time": "23:58", "end_time": "00:02", "lat": 0.0, "lon": 0.0, "tz": 0.0, - "candidate_intervals": [{"start_at": "2000-02-29T23:58", "end_at": "2000-03-01T00:02"}], - "events": [{"id": "00000000-0000-4000-8000-000000000001", "domain": "career", "event_kind": "career_entry", - "date_start": "2020-01-01", "date_end": "2020-01-01", "precision": "day", "summary": "Fictional career entry for date-contract testing"}]} - from scripts.rectification.contracts import normalize_rectification_request - response = score(normalize_rectification_request(request)) - target = args.golden_path - with target.open("x", encoding="utf-8") as stream: - json.dump({"provenance": {"kind": "unmocked_native_engine", "facts": "explicitly_fictional", "generator": "scripts/research/midnight_date_anchor_regression.py --baseline --golden", "algorithm": response["algorithm_version"]}, "request": request, "response": response}, stream, ensure_ascii=False, indent=2) - print("golden", target, flush=True) - - -if __name__ == "__main__": - main() diff --git a/scripts/research/minute_resolution_lib.py b/scripts/research/minute_resolution_lib.py deleted file mode 100644 index 94f08211f..000000000 --- a/scripts/research/minute_resolution_lib.py +++ /dev/null @@ -1,346 +0,0 @@ -"""Pure helpers for the minute-resolution scoring sweep. No production defaults.""" - -from __future__ import annotations - -import math -from collections.abc import Iterable, Sequence -from typing import Any - -from scripts.active_rectification_event_engine import DOMAIN_CONFIG -from scripts.rectification.candidate_contrast import ( - SIGNATURE_LAYERS, - cluster_contexts_by_signature, - context_time, - layer_value, - select_signature_representatives, -) -from scripts.rectification.scoring_service import PRECISION_WEIGHTS, _event_kind_factor - -VARGA_RULE_WEIGHT = { - "vim_md_domain_varga": 2.0, - "vim_ad_domain_varga": 1.5, - "vim_pd_domain_varga": 0.75, -} - -KP_MATCH = { - "md": (0.50, 0.25), - "ad": (0.35, 0.15), - "pd": (0.20, 0.10), -} - -DOMAIN_SIGNATURE_LAYERS = { - "education": ("d24", "d5"), - "relocation": ("d4",), - "relationship": ("d9",), - "career": ("d10",), - "occupation": ("d10",), - "finance": ("d2", "d11"), - "health_pressure": ("d30",), - "family": ("d12", "d7", "d3"), -} - -EXTRA_LAYER_VARGA = { - "d2": "D2", - "d3": "D3", - "d5": "D5", - "d7": "D7", - "d11": "D11", - "d30": "D30", -} - -NARROW_WIDTH = 5 - - -def clock(value: str) -> int: - stamp = str(value)[:5] - return int(stamp[:2]) * 60 + int(stamp[3:5]) - - -def hhmm_from_minutes(value: int) -> str: - wrapped = value % 1440 - return f"{wrapped // 60:02d}:{wrapped % 60:02d}" - - -def shift_clock(value: str, delta: int) -> str: - return hhmm_from_minutes(clock(value) + delta) - - -def range_width(times: Sequence[str]) -> int | None: - clocks = sorted(clock(item) for item in times if str(item)[:5]) - if not clocks: - return None - return clocks[-1] - clocks[0] + 1 - - -def varga_divisor(count: int, mode: str) -> float: - n = max(int(count), 1) - if mode == "len": - return float(n) - if mode == "sqrt": - return math.sqrt(n) - if mode == "fixed2": - return 2.0 - return 2.0 * n - - -def rescale_varga_points( - points: float, - rule_ids: Sequence[str], - domain: str, - event_kind: str, - precision: str, - mode: str, -) -> float: - if mode == "2len": - return float(points) - prefixes, _houses = DOMAIN_CONFIG[domain] - n = max(len(prefixes), 1) - old_div = varga_divisor(n, "2len") - new_div = varga_divisor(n, mode) - if abs(old_div - new_div) < 1e-12: - return float(points) - delta_inner = 0.0 - for rule in rule_ids: - weight = VARGA_RULE_WEIGHT.get(str(rule)) - if weight is None: - continue - delta_inner += weight * (1.0 / new_div - 1.0 / old_div) - precision_w = PRECISION_WEIGHTS.get(precision, 1.0) - kind = _event_kind_factor(event_kind, rule_ids) - return round(float(points) + delta_inner * kind * (precision_w ** 2), 4) - - -def aggregate_samples(samples: Sequence[float], mode: str, temperature: float = 1.0) -> float: - values = [float(item) for item in samples] - if not values: - return 0.0 - if mode == "max": - return round(max(values), 4) - if mode == "lse": - temp = max(float(temperature), 1e-6) - peak = max(values) - mean_exp = sum(math.exp((item - peak) / temp) for item in values) / len(values) - return round(temp * math.log(mean_exp) + peak, 4) - return round(sum(values) / len(values), 4) - - -def subtract_event_floor(by_time: dict[str, float]) -> dict[str, float]: - if not by_time: - return {} - floor = min(by_time.values()) - return {time: round(score - floor, 4) for time, score in by_time.items()} - - -def shannon_entropy(weights: Iterable[float]) -> float: - values = [max(float(item), 0.0) for item in weights] - total = sum(values) - if total <= 0: - return 0.0 - entropy = 0.0 - for value in values: - if value <= 0: - continue - share = value / total - entropy -= share * math.log(share, 2) - return round(entropy, 6) - - -def kp_event_points( - context: dict[str, Any], - domain: str, - vim_lords: tuple[str, str, str], - weight: float, -) -> float: - feature = context.get("feature") if isinstance(context.get("feature"), dict) else {} - snapshot = feature.get("kp_cusps") if isinstance(feature.get("kp_cusps"), dict) else {} - if snapshot.get("status") != "executed": - return 0.0 - houses = snapshot.get("houses") if isinstance(snapshot.get("houses"), dict) else {} - _prefixes, target_houses = DOMAIN_CONFIG[domain] - points = 0.0 - md, ad, pd = vim_lords - for house in target_houses: - row = houses.get(str(house)) - if not isinstance(row, dict): - continue - sub = str(row.get("sub_lord") or "") - sub_sub = str(row.get("sub_sub_lord") or "") - for lord, (sub_w, sub_sub_w) in ( - (md, KP_MATCH["md"]), - (ad, KP_MATCH["ad"]), - (pd, KP_MATCH["pd"]), - ): - if lord and lord == sub: - points += sub_w - if lord and lord == sub_sub: - points += sub_sub_w - return round(points * float(weight), 4) - - -def kp_sub_lord_key(context: dict[str, Any], houses: Sequence[int]) -> tuple[str, ...]: - feature = context.get("feature") if isinstance(context.get("feature"), dict) else {} - snapshot = feature.get("kp_cusps") if isinstance(feature.get("kp_cusps"), dict) else {} - table = snapshot.get("houses") if isinstance(snapshot.get("houses"), dict) else {} - keys = [] - for house in houses: - row = table.get(str(house)) if isinstance(table.get(str(house)), dict) else {} - keys.append(str(row.get("sub_lord") or "")) - return tuple(keys) - - -def kp_changes_in_window(contexts: Sequence[dict[str, Any]], domain: str) -> int: - _prefixes, houses = DOMAIN_CONFIG[domain] - seen: list[tuple[str, ...]] = [] - for context in contexts: - key = kp_sub_lord_key(context, houses) - if not seen or seen[-1] != key: - seen.append(key) - return max(len(seen) - 1, 0) - - -def dynamic_signature_layers(domains: Sequence[str]) -> tuple[str, ...]: - layers = ["d1"] - for domain in domains: - for layer in DOMAIN_SIGNATURE_LAYERS.get(domain, ()): - if layer not in layers: - layers.append(layer) - return tuple(layers) - - -def layer_value_extended(context: dict[str, Any], layer: str) -> int | None: - if layer in SIGNATURE_LAYERS or layer == "md" or layer == "d1": - return layer_value(context, layer) - name = EXTRA_LAYER_VARGA.get(layer) - if not name: - return None - feature = context.get("feature") if isinstance(context.get("feature"), dict) else {} - vargas = feature.get("varga_ascendants") if isinstance(feature.get("varga_ascendants"), dict) else {} - raw = vargas.get(name) - return raw if isinstance(raw, int) else None - - -def cluster_contexts( - contexts: Sequence[dict[str, Any]], - layers: Sequence[str] | None = None, -) -> list[dict[str, Any]]: - if not layers or tuple(layers) == SIGNATURE_LAYERS: - return cluster_contexts_by_signature(contexts) - buckets: dict[tuple[int | None, ...], list[dict[str, Any]]] = {} - for context in contexts: - if not isinstance(context, dict): - continue - time = context_time(context) - if not time: - continue - signature = tuple(layer_value_extended(context, layer) for layer in layers) - buckets.setdefault(signature, []).append(context) - clusters: list[dict[str, Any]] = [] - for signature, members in buckets.items(): - ordered = sorted(members, key=lambda item: clock(str(context_time(item)))) - times = [str(context_time(item)) for item in ordered] - clusters.append({ - "signature": signature, - "signature_key": ",".join("x" if value is None else str(value) for value in signature), - "contexts": ordered, - "times": times, - "representative_time": times[len(times) // 2], - "representative": ordered[len(ordered) // 2], - }) - clusters.sort(key=lambda item: clock(item["representative_time"])) - return clusters - - -def public_rows( - rows: Sequence[dict[str, Any]], - contexts: Sequence[dict[str, Any]], - layers: Sequence[str] | None = None, -) -> list[dict[str, Any]]: - if not layers or tuple(layers) == SIGNATURE_LAYERS: - return select_signature_representatives(rows, contexts) - by_time = {str(row.get("time"))[:5]: row for row in rows if str(row.get("time"))} - clusters = cluster_contexts(contexts, layers) - from scripts.rectification.candidate_contrast import cap_clusters_by_adjacent_merge - clusters = cap_clusters_by_adjacent_merge(clusters, by_time) - representatives: list[dict[str, Any]] = [] - for cluster in clusters: - members = [by_time[time] for time in cluster["times"] if time in by_time] - if not members: - continue - best = max(members, key=lambda row: (float(row.get("score") or 0), str(row.get("time")))) - representatives.append({ - **best, - "cluster_times": [time for time in cluster["times"] if time in by_time], - }) - representatives.sort(key=lambda row: (-float(row.get("score") or 0), str(row.get("time")))) - return representatives or list(rows)[:1] - - -def cluster_of(true_time: str, clusters: Sequence[dict[str, Any]]) -> dict[str, Any] | None: - stamp = str(true_time)[:5] - for cluster in clusters: - times = [str(item)[:5] for item in cluster.get("times") or []] - if stamp in times: - return cluster - return None - - -def metrics_from_public( - public: Sequence[dict[str, Any]], - true_time: str, - window_times: Sequence[str], -) -> dict[str, Any]: - if not public: - return { - "top1_hit": False, - "coverage": False, - "width": None, - "tie": False, - "entropy": 0.0, - "truth_squeezed": True, - "too_narrow": False, - "leader_count": 0, - "public_count": 0, - "true_cluster_rank": None, - "true_cluster_size": 0, - } - scores = [float(row.get("score") or 0) for row in public] - best = max(scores) - leaders = [row for row in public if abs(float(row.get("score") or 0) - best) <= 1e-9] - delivered = [] - seen: set[str] = set() - for row in public: - for time in row.get("cluster_times") or [str(row.get("time"))[:5]]: - stamp = str(time)[:5] - if stamp not in seen: - seen.add(stamp) - delivered.append(stamp) - true = str(true_time)[:5] - true_in_leaders = any(true in (row.get("cluster_times") or [str(row.get("time"))[:5]]) for row in leaders) - if not true_in_leaders: - true_in_leaders = any(str(row.get("time"))[:5] == true for row in leaders) - rank = None - size = 0 - ordered = sorted(public, key=lambda row: (-float(row.get("score") or 0), str(row.get("time")))) - for index, row in enumerate(ordered, start=1): - members = [str(item)[:5] for item in (row.get("cluster_times") or [str(row.get("time"))[:5]])] - if true in members: - rank = index - size = len(members) - break - width = range_width(delivered) - second = sorted({round(float(row.get("score") or 0), 4) for row in public}, reverse=True) - tied = len(leaders) >= 2 or (len(second) >= 2 and abs(second[0] - second[1]) <= 1e-9) - return { - "top1_hit": true_in_leaders, - "coverage": true in seen, - "width": width, - "tie": tied, - "entropy": shannon_entropy(max(score, 0.0) for score in scores), - "truth_squeezed": true not in seen, - "too_narrow": width is not None and width <= NARROW_WIDTH and true in seen, - "leader_count": len(leaders), - "public_count": len(public), - "true_cluster_rank": rank, - "true_cluster_size": size, - "window_width": range_width(list(window_times)), - } diff --git a/scripts/research/minute_resolution_sweep.py b/scripts/research/minute_resolution_sweep.py deleted file mode 100644 index 3814505a3..000000000 --- a/scripts/research/minute_resolution_sweep.py +++ /dev/null @@ -1,599 +0,0 @@ -#!/usr/bin/env python3 -"""Offline sweep of minute-resolution scoring changes. - -Reads production scoring modules. Does not change their defaults. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import traceback -from collections import defaultdict -from dataclasses import dataclass -from datetime import date, datetime -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - DOMAIN_CONFIG, - NODE_MODE, - _active_vimshottari, - compute_candidate_static_contexts, - compute_event_candidate_rows, -) -from scripts.rectification.event_probes import discriminating_event_probes # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - _kind_adjusted_evidence, - _legacy_request, - sample_event_dates, - score_from_matrix, - scoreable_request, -) -from scripts.research.minute_resolution_lib import ( # noqa: E402 - SIGNATURE_LAYERS, - aggregate_samples, - cluster_contexts, - cluster_of, - dynamic_signature_layers, - kp_changes_in_window, - kp_event_points, - metrics_from_public, - public_rows, - rescale_varga_points, - shannon_entropy, - subtract_event_floor, -) -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - apply_answer, - optimal_answer, - remaining_after_six, - request_from_case, - top1_hit, -) - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -REPORT_MD = ROOT / "docs" / "research" / "minute_resolution_2026_09_14.md" -REPORT_JSON = ROOT / "docs" / "research" / "minute_resolution_2026_09_14.json" -TODAY = date(2026, 9, 14) -RADII = (10, 30, 60) -MINUTE_STEP = 2 -ASK = ASK_COUNT - - -@dataclass(frozen=True) -class Variant: - name: str - r1: str = "2len" - r2: bool = False - r3: float | None = None - r4: str = "mean" - r5: bool = False - - @property - def uses_r3(self) -> bool: - return self.r3 is not None - - -def all_variants() -> list[Variant]: - rows = [ - Variant("baseline"), - Variant("R1@len", r1="len"), - Variant("R1@sqrt", r1="sqrt"), - Variant("R1@fixed2", r1="fixed2"), - Variant("R2", r2=True), - Variant("R3@0.5", r3=0.5), - Variant("R3@1.0", r3=1.0), - Variant("R3@2.0", r3=2.0), - Variant("R4@max", r4="max"), - Variant("R4@lse", r4="lse"), - Variant("R5", r5=True), - ] - keys = ("R1", "R2", "R3", "R4", "R5") - for i, left in enumerate(keys): - for right in keys[i + 1:]: - pair = {left, right} - rows.append(Variant( - f"{left}+{right}", - r1="len" if "R1" in pair else "2len", - r2="R2" in pair, - r3=(1.0 if "R3" in pair else None), - r4="lse" if "R4" in pair else "mean", - r5="R5" in pair, - )) - return rows - - -def scoring_request_for(case: dict[str, Any], radius: int) -> dict[str, Any]: - previous = case.get("candidate_radius_minutes") - case["candidate_radius_minutes"] = radius - try: - request = request_from_case(case) - finally: - if previous is None: - case.pop("candidate_radius_minutes", None) - else: - case["candidate_radius_minutes"] = previous - request["minute_step"] = MINUTE_STEP - request["ayanamsa"] = AYANAMSA - request["node_mode"] = NODE_MODE - return scoreable_request(request) - - -def event_at(sample: str) -> datetime: - return datetime.strptime(f"{sample} 12:00:00", "%Y-%m-%d %H:%M:%S") - - -def collect_samples( - request: dict[str, Any], - static_contexts: Sequence[dict[str, Any]], -) -> dict[str, Any]: - times = [ - item["feature"]["time"] if isinstance(item.get("feature"), dict) else item["candidate_at"].strftime("%H:%M") - for item in static_contexts - ] - events = list(request["events"]) - payload: dict[str, dict[str, list[dict[str, Any]]]] = {event["id"]: {time: [] for time in times} for event in events} - kp_by_event: dict[str, dict[str, list[float]]] = {event["id"]: {time: [] for time in times} for event in events} - domains = [str(event["domain"]) for event in events] - for event in events: - samples = sample_event_dates(event) - for sampled in samples: - rows = list(compute_event_candidate_rows( - _legacy_request(request, event, sampled), - static_contexts=static_contexts, - )) - by_time = {str(row["time"])[:5]: row for row in rows} - event_dt = event_at(sampled) - for context in static_contexts: - time = str(context["feature"]["time"])[:5] - row = by_time.get(time) - if row is None or not row.get("evidence"): - continue - adjusted = _kind_adjusted_evidence(event, row["evidence"][0]) - payload[event["id"]][time].append({ - "points": float(adjusted["points"]), - "rule_ids": list(adjusted["rule_ids"]), - }) - moon = context["planet_longitudes"]["Moon"] - try: - vim = _active_vimshottari(request["birth_date"], float(moon), event_dt) - except (KeyError, TypeError, ValueError): - vim = ("", "", "") - kp_by_event[event["id"]][time].append( - kp_event_points(context, event["domain"], vim, 1.0), - ) - return { - "times": times, - "events": events, - "domains": domains, - "samples": payload, - "kp_samples": kp_by_event, - "static_contexts": list(static_contexts), - } - - -def apply_variant(bundle: dict[str, Any], variant: Variant) -> dict[str, dict[str, dict[str, Any]]]: - matrix: dict[str, dict[str, dict[str, Any]]] = {} - for event in bundle["events"]: - event_id = event["id"] - domain = event["domain"] - kind = event["event_kind"] - precision = event["precision"] - by_time: dict[str, float] = {} - rules_by_time: dict[str, list[str]] = {} - for time, samples in bundle["samples"][event_id].items(): - if not samples: - continue - scaled = [ - rescale_varga_points(item["points"], item["rule_ids"], domain, kind, precision, variant.r1) - for item in samples - ] - kp_scaled = [ - round(value * float(variant.r3), 4) - for value in bundle["kp_samples"][event_id].get(time, []) - ] if variant.r3 is not None else [0.0] * len(scaled) - combined = [left + right for left, right in zip(scaled, kp_scaled)] or scaled - by_time[time] = aggregate_samples(combined, variant.r4) - rules_by_time[time] = sorted({rule for item in samples for rule in item["rule_ids"]}) - if variant.r2: - by_time = subtract_event_floor(by_time) - matrix[event_id] = { - time: {"points": score, "rule_ids": rules_by_time.get(time, [])} - for time, score in by_time.items() - } - return matrix - - -def built_payload(bundle: dict[str, Any], matrix: dict[str, dict[str, dict[str, Any]]]) -> dict[str, Any]: - return { - "candidate_times": list(bundle["times"]), - "matrix": matrix, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": bundle["static_contexts"], - } - - -def entropy_curve( - *, - request: dict[str, Any], - built: dict[str, Any], - prior: dict[str, float], - true_time: str, - clusters: Sequence[dict[str, Any]], -) -> dict[str, Any]: - times = list(prior) - initial = discriminating_event_probes( - {**request, "refresh_probes": False}, - built, - scan=window_scan(built), - candidate_times=times, - representative_time=true_time, - today=TODAY, - ) - asked = initial[:ASK] - scores = dict(prior) - conflicts = {time: 0 for time in times} - eliminated: set[str] = set() - curve = [shannon_entropy(max(scores[time], 0.0) for time in times if time not in eliminated)] - coverage_curve = [] - width_curve = [] - for probe in asked: - answer = optimal_answer(probe, true_time) - if answer is None: - curve.append(curve[-1] if curve else 0.0) - continue - scores, conflicts, eliminated = apply_answer( - scores, conflicts, eliminated, probe, answer, times, - ) - remaining, _mode, true_alive = remaining_after_six( - all_times=times, - scores=scores, - eliminated=eliminated, - clusters=clusters, - true_time=true_time, - ) - active_scores = [max(scores.get(time, 0.0), 0.0) for time in remaining] - curve.append(shannon_entropy(active_scores)) - coverage_curve.append(true_alive) - width_curve.append( - None if not remaining else (max(len(remaining), 0)), - ) - remaining, remaining_mode, true_alive = remaining_after_six( - all_times=times, - scores=scores, - eliminated=eliminated, - clusters=clusters, - true_time=true_time, - ) - return { - "entropy": curve, - "asked": len(asked), - "probes": len(initial), - "remaining_count": len(remaining), - "remaining_mode": remaining_mode, - "true_alive": true_alive, - "replay_top1": top1_hit(scores, remaining, true_time, clusters), - "coverage_after_answers": coverage_curve, - } - - -def score_variant( - *, - request: dict[str, Any], - bundle: dict[str, Any], - variant: Variant, - true_time: str, -) -> dict[str, Any]: - matrix = apply_variant(bundle, variant) - built = built_payload(bundle, matrix) - rows = score_from_matrix(request, built) - layers = dynamic_signature_layers(bundle["domains"]) if variant.r5 else SIGNATURE_LAYERS - clusters = cluster_contexts(bundle["static_contexts"], layers) - public = public_rows(rows, bundle["static_contexts"], layers) - prior = {str(row["time"])[:5]: float(row["score"]) for row in rows} - engine = metrics_from_public(public, true_time, bundle["times"]) - replay = entropy_curve( - request=request, - built=built, - prior=prior, - true_time=true_time, - clusters=clusters, - ) - true_cluster = cluster_of(true_time, clusters) - return { - "engine": engine, - "replay": replay, - "true_cluster_key": None if true_cluster is None else true_cluster.get("signature_key"), - "true_cluster_size": 0 if true_cluster is None else len(true_cluster.get("times") or []), - "score_range": round( - max(prior.values()) - min(prior.values()), - 4, - ) if prior else 0.0, - } - - -def kp_window_changes(bundle: dict[str, Any]) -> dict[str, int]: - changes = {} - for domain in sorted(set(bundle["domains"])): - changes[domain] = kp_changes_in_window(bundle["static_contexts"], domain) - changes["any"] = max(changes.values()) if changes else 0 - return changes - - -def summarize(rows: Sequence[dict[str, Any]], *, r3_only: bool = False) -> dict[str, Any]: - usable = [row for row in rows if (not r3_only or row.get("kp_eligible"))] - if not usable: - return { - "n": 0, - "top1": None, - "coverage": None, - "width_median": None, - "tie": None, - "entropy0": None, - "entropy6": None, - "squeezed": None, - "too_narrow": None, - "replay_top1": None, - } - widths = [row["engine"]["width"] for row in usable if row["engine"]["width"] is not None] - entropy0 = [row["engine"]["entropy"] for row in usable] - entropy6 = [ - (row["replay"]["entropy"][-1] if row["replay"]["entropy"] else None) - for row in usable - ] - entropy6 = [item for item in entropy6 if item is not None] - return { - "n": len(usable), - "top1": round(sum(1 for row in usable if row["engine"]["top1_hit"]) / len(usable), 4), - "coverage": round(sum(1 for row in usable if row["engine"]["coverage"]) / len(usable), 4), - "width_median": statistics.median(widths) if widths else None, - "tie": round(sum(1 for row in usable if row["engine"]["tie"]) / len(usable), 4), - "entropy0": round(sum(entropy0) / len(entropy0), 4) if entropy0 else None, - "entropy6": round(sum(entropy6) / len(entropy6), 4) if entropy6 else None, - "squeezed": sum(1 for row in usable if row["engine"]["truth_squeezed"]), - "too_narrow": sum(1 for row in usable if row["engine"]["too_narrow"]), - "replay_top1": round(sum(1 for row in usable if row["replay"]["replay_top1"]) / len(usable), 4), - } - - -def verdict(baseline: dict[str, Any], candidate: dict[str, Any]) -> str: - if baseline["n"] == 0 or candidate["n"] == 0: - return "uncertain" - if any(candidate[key] is None or baseline[key] is None for key in ("top1", "coverage", "tie", "width_median")): - return "uncertain" - hit_ok = candidate["top1"] + 1e-9 >= baseline["top1"] - cover_ok = candidate["coverage"] + 1e-9 >= baseline["coverage"] - tie_down = candidate["tie"] <= baseline["tie"] + 1e-9 - width_down = candidate["width_median"] <= baseline["width_median"] + 1e-9 - squeezed_ok = candidate["squeezed"] <= baseline["squeezed"] - if hit_ok and cover_ok and tie_down and width_down and squeezed_ok: - if ( - candidate["top1"] > baseline["top1"] + 1e-9 - or candidate["tie"] < baseline["tie"] - 1e-9 - or candidate["width_median"] < baseline["width_median"] - 1e-9 - ): - return "benefit" - return "no_benefit" - if not hit_ok or not cover_ok or candidate["squeezed"] > baseline["squeezed"]: - return "no_benefit" - return "uncertain" - - -def md_table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) -> str: - def cell(value: Any) -> str: - if value is None: - return "—" - if isinstance(value, float): - return f"{value:.3f}".rstrip("0").rstrip(".") - return str(value) - - line = "| " + " | ".join(headers) + " |" - sep = "| " + " | ".join("---" if index == 0 else "---:" for index in range(len(headers))) + " |" - body = ["| " + " | ".join(cell(item) for item in row) + " |" for row in rows] - return "\n".join([line, sep, *body]) - - -def write_report(payload: dict[str, Any]) -> None: - lines = [ - "# 分钟分辨率打分尺度测量(2026-09-14)", - "", - f"- 口径:ayanamsa `{payload['ayanamsa']}`,node mode `{payload['node_mode']}`。不得与上游 true-node 数字直接对比。", - f"- 数据:`{payload['holdout']}`,{payload['case_count']} 例公开 Rodden-AA,每例 ≥7 件事、≥4 个领域。", - f"- 半径:{', '.join(f'±{item}' for item in payload['radii'])},步长 {MINUTE_STEP} 分钟。", - "- 性质:离线测量。生产 `active_rectification_event_engine.py` / `scoring_service.py` / `candidate_contrast.py` 默认值未改。", - "- D1:KP 宫头子主计分方向已拍板;本文件只报告权重收益,不改线上默认。", - "", - "## 结论", - "", - ] - overall = payload["verdicts"] - lines.append("| 改法 | 判定 | 说明 |") - lines.append("| --- | --- | --- |") - for name, row in overall.items(): - lines.append(f"| {name} | **{row['verdict']}** | {row['note']} |") - lines.extend(["", "## 基线成绩单", ""]) - base_rows = [] - for radius, summary in payload["baseline"].items(): - base_rows.append([ - f"±{radius}", - summary["n"], - summary["top1"], - summary["coverage"], - summary["width_median"], - summary["tie"], - summary["entropy0"], - summary["squeezed"], - ]) - lines.append(md_table( - ["半径", "N", "真分钟在头名簇", "真分钟在交付区间", "区间宽度中位", "并列率", "引擎熵", "真值被挤出"], - base_rows, - )) - lines.extend(["", "## 分半径指标", ""]) - for radius, variants in payload["by_radius"].items(): - lines.append(f"### ±{radius} 分钟") - lines.append("") - table = [] - for name, summary in variants.items(): - table.append([ - name, - summary["top1"], - summary["coverage"], - summary["width_median"], - summary["tie"], - summary["entropy0"], - summary["entropy6"], - summary["squeezed"], - summary["too_narrow"], - ]) - lines.append(md_table( - ["方案", "头名簇命中", "区间覆盖", "宽度中位", "并列率", "熵0", "熵6", "挤出", "过窄"], - table, - )) - lines.append("") - lines.extend([ - "## R3 KP 窗内变化", - "", - "只统计 ±10 窗内目标宫宫头子主至少变化一次的例子。", - "", - ]) - kp = payload["kp"] - lines.append(md_table( - ["例子", "窗内变化次数", "计入 R3"], - [[row["case_id"], row["changes"], "yes" if row["eligible"] else "no"] for row in kp], - )) - lines.extend([ - "", - "## 方法", - "", - "1. 每个例子先算生产静态盘(含 KP 观察),再按事件抽样日打生产分。", - "2. R1 按 `*_domain_varga` 规则把 `2*len` 换成 `len` / `sqrt(len)` / 固定 2。", - "3. R2 在事件级减去当前窗口最小值。", - "4. R3 把目标宫 KP 子主/次子主与当时 Vim MD/AD/PD 比对,权重 0.5 / 1.0 / 2.0。", - "5. R4 对年精度 12 个月样本取 max 或 log-sum-exp(T=1)。", - "6. R5 按本例有证据的领域动态取签名层,去掉同日恒定的 `md`。", - "7. 交付区间 = 公开簇成员分钟的并集。并列 = 头名簇分数并列。", - "8. 熵曲线用生产探针 + 真值方向最优答,最多 6 题。", - "", - "配对组合用 R1=`len`、R3=1.0、R4=`lse`。", - "", - ]) - REPORT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8") - REPORT_JSON.write_text(json.dumps(payload, ensure_ascii=True, indent=2) + "\n", encoding="utf-8") - - -def run(args: argparse.Namespace) -> dict[str, Any]: - holdout = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(holdout["cases"]) - if args.limit: - cases = cases[: args.limit] - radii = tuple(int(item) for item in args.radii) - variants = all_variants() - if args.quick: - variants = [item for item in variants if item.name in {"baseline", "R1@len", "R2", "R3@1.0", "R4@lse", "R5"}] - results: dict[str, dict[str, list[dict[str, Any]]]] = { - str(radius): {variant.name: [] for variant in variants} for radius in radii - } - kp_rows = [] - errors = [] - for case in cases: - case_id = case["case_id"] - true_time = str(case["birth"]["time"])[:5] - print(f"case {case_id}", flush=True) - try: - for radius in radii: - request = scoring_request_for(case, radius) - contexts = compute_candidate_static_contexts(request) - bundle = collect_samples(request, contexts) - changes = kp_window_changes(bundle) - eligible = changes["any"] > 0 - if radius == 10: - kp_rows.append({ - "case_id": case_id, - "changes": changes["any"], - "by_domain": changes, - "eligible": eligible, - }) - print(f" radius ±{radius} candidates={len(bundle['times'])}", flush=True) - for variant in variants: - scored = score_variant( - request=request, - bundle=bundle, - variant=variant, - true_time=true_time, - ) - scored["case_id"] = case_id - scored["kp_eligible"] = eligible - results[str(radius)][variant.name].append(scored) - except Exception as exc: # noqa: BLE001 - errors.append({"case_id": case_id, "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()}) - print(f" FAIL {case_id}: {exc}", flush=True) - by_radius = {} - baseline = {} - verdicts: dict[str, dict[str, str]] = {} - for radius in radii: - variant_summaries = {} - for variant in variants: - rows = results[str(radius)][variant.name] - variant_summaries[variant.name] = summarize(rows, r3_only=variant.uses_r3) - by_radius[str(radius)] = variant_summaries - baseline[str(radius)] = variant_summaries["baseline"] - names = [variant.name for variant in variants if variant.name != "baseline"] - for name in names: - notes = [] - labels = [] - for radius in radii: - base = by_radius[str(radius)]["baseline"] - cand = by_radius[str(radius)][name] - label = verdict(base, cand) - labels.append(label) - notes.append(f"±{radius}:{label}") - if all(item == "benefit" for item in labels): - final = "benefit" - elif all(item == "no_benefit" for item in labels): - final = "no_benefit" - else: - final = "uncertain" - verdicts[name] = {"verdict": final, "note": ";".join(notes)} - payload = { - "generated_at": TODAY.isoformat(), - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "holdout": str(HOLDOUT.relative_to(ROOT)).replace("\\", "/"), - "case_count": len(cases), - "radii": list(radii), - "minute_step": MINUTE_STEP, - "baseline": baseline, - "by_radius": by_radius, - "verdicts": verdicts, - "kp": kp_rows, - "errors": errors, - "results": results, - } - write_report(payload) - return payload - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", nargs="+", default=[str(item) for item in RADII]) - parser.add_argument("--quick", action="store_true") - args = parser.parse_args() - payload = run(args) - print(f"wrote {REPORT_MD} cases={payload['case_count']} errors={len(payload['errors'])}") - return 0 if not payload["errors"] else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/nadi_seconds_run.py b/scripts/research/nadi_seconds_run.py deleted file mode 100644 index fa77e89b8..000000000 --- a/scripts/research/nadi_seconds_run.py +++ /dev/null @@ -1,676 +0,0 @@ -#!/usr/bin/env python3 -"""Run the pre-registered nadi / sookshma / prana falsification study. - -Reads ``docs/research/nadi_seconds_preregistration_2026_10_05.json`` and -refuses to score without it. The output JSON has no timestamps, so two runs -with ``PYTHONHASHSEED=0`` are byte-identical. This script does not import -``true_minute``. -""" - -from __future__ import annotations - -import argparse -import json -import sys -import traceback -from datetime import date -from pathlib import Path -from random import Random -from typing import Any, Mapping, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.research import nadi_seconds_lib as lib # noqa: E402 - -REPORT = ROOT / "docs" / "research" / "nadi_seconds_results_2026_10_05.json" - - -def load_prereg() -> dict[str, Any]: - if not lib.PREREG_PATH.is_file(): - raise SystemExit(f"missing preregistration: {lib.PREREG_PATH}") - return json.loads(lib.PREREG_PATH.read_text(encoding="utf-8")) - - -def offsets_of(radius: int, step: int) -> list[int]: - return list(range(-int(radius), int(radius) + 1, int(step))) - - -def truth_minute_offsets() -> list[int]: - return list(range(0, 60)) - - -def collect_skies(birth: Mapping[str, Any], offsets: Sequence[int], **kwargs: Any) -> dict[int, dict[str, Any]]: - return {int(offset): lib.sky_at(birth, lib.candidate_moment(birth, int(offset)), **kwargs) for offset in offsets} - - -def lord_bundle(skies: Mapping[int, Mapping[str, Any]], events: Sequence[Mapping[str, Any]]) -> dict[str, Any]: - lords: dict[int, list] = {} - asc: dict[int, int] = {} - segment: dict[int, str] = {} - part: dict[int, int] = {} - for offset, sky in skies.items(): - lords[int(offset)] = lib.lords_for_events(str(sky["birth_date"]), float(sky["moon_lon"]), events) - asc[int(offset)] = int(sky["asc_index"]) - row = lib.d150_equal(float(sky["asc_lon"])) - segment[int(offset)] = str(row["sign_lord"]) - part[int(offset)] = int(row["part_index"]) - return {"lords": lords, "asc": asc, "segment": segment, "part": part} - - -def rule_counts(bundle: Mapping[str, Any], events: Sequence[Mapping[str, Any]], rule: str) -> dict[int, int]: - domains = [str(event["domain"]) for event in events] - use_segment = rule.startswith("N5") - counts: dict[int, int] = {} - for offset, rows in bundle["lords"].items(): - targets = [lib.domain_target_lords(bundle["asc"][offset], domain) for domain in domains] - segment = bundle["segment"][offset] if use_segment else None - counts[offset] = sum( - lib.explained(lords, target, rule, segment) - for lords, target in zip(rows, targets, strict=True) - ) - return counts - - -def rule_bits(bundle: Mapping[str, Any], events: Sequence[Mapping[str, Any]], rule: str) -> dict[int, list[bool]]: - domains = [str(event["domain"]) for event in events] - use_segment = rule.startswith("N5") - bits: dict[int, list[bool]] = {} - for offset, rows in bundle["lords"].items(): - targets = [lib.domain_target_lords(bundle["asc"][offset], domain) for domain in domains] - segment = bundle["segment"][offset] if use_segment else None - bits[offset] = [ - lib.explained(lords, target, rule, segment) - for lords, target in zip(rows, targets, strict=True) - ] - return bits - - -def mean_defined(values: Sequence[float | None]) -> float | None: - nums = [float(value) for value in values if value is not None] - if not nums: - return None - return lib.round6(sum(nums) / len(nums)) - - -def rate(flags: Sequence[bool]) -> float | None: - if not flags: - return None - return lib.round6(sum(bool(flag) for flag in flags) / len(flags)) - - -def split_rates(rows: Sequence[Mapping[str, Any]], key: str, rounded: set[str]) -> dict[str, float | None]: - return { - "all": rate([bool(row[key]) for row in rows]), - "rounded_5min": rate([bool(row[key]) for row in rows if row["case_id"] in rounded]), - "unrounded": rate([bool(row[key]) for row in rows if row["case_id"] not in rounded]), - "n_all": len(rows), - "n_rounded_5min": sum(1 for row in rows if row["case_id"] in rounded), - "n_unrounded": sum(1 for row in rows if row["case_id"] not in rounded), - } - - -def delivery_offsets(start: str | None, end: str | None, recorded: str, radius_minutes: int) -> list[int]: - """One-second offsets covering each delivered clock minute, clipped to the search radius.""" - if not start or not end: - return [] - cap = int(radius_minutes) * 60 - start_min = lib.clock_delta_minutes(start, recorded) - end_min = lib.clock_delta_minutes(end, recorded) - - def clip(lo: int, hi: int) -> list[int]: - lo = max(lo, -cap) - hi = min(hi, cap) - if lo > hi: - return [] - return list(range(lo, hi + 1)) - - if start_min <= end_min: - return clip(start_min * 60, end_min * 60 + 59) - return sorted(set(clip(start_min * 60, cap) + clip(-cap, end_min * 60 + 59))) - - -def six_probe(case: Mapping[str, Any], radius: int) -> dict[str, Any]: - """futile_collect_stop_replay d1: six probes, no guided-window injection.""" - from scripts.active_rectification_event_engine import AYANAMSA, NODE_MODE, compute_candidate_static_contexts - from scripts.rectification.event_probes import discriminating_event_probes - from scripts.rectification.refinement_packet import window_scan - from scripts.rectification.scoring_service import build_event_contribution_matrix, score_from_matrix - from scripts.research.fewer_probes_card_replay import _outcome - from scripts.research.guided_collect_holdout_replay import _hhmm, posterior_state - from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for - from scripts.research.probe_supply_after_six import ASK_COUNT, TODAY - - recorded = str(case["birth"]["time"])[:5] - request = scoring_request_for(dict(case), radius) - request["ayanamsa"] = AYANAMSA - request["node_mode"] = NODE_MODE - request["minute_step"] = MINUTE_STEP - static_contexts = compute_candidate_static_contexts(request) - built = build_event_contribution_matrix(request, static_contexts=static_contexts) - rows = score_from_matrix(request, built) - times = [stamp for row in rows if (stamp := _hhmm(row.get("time")))] - probes = discriminating_event_probes( - {**request, "refresh_probes": False, "asked_probe_keys": []}, - built, - scan=window_scan(built), - candidate_times=times, - representative_time=recorded, - today=TODAY, - )[:ASK_COUNT] - state = posterior_state(rows=rows, contexts=static_contexts, probes=probes, true_time=recorded) - outcome = _outcome(state, recorded) - scores = state["scores"] - valid = list(state["valid"]) - if not valid: - leaders: list[str] = [] - else: - def _score(row: Mapping[str, Any]) -> float: - stamp = _hhmm(row.get("time")) or "" - return float(scores.get(stamp, row.get("score") or 0)) - - best = max(_score(row) for row in valid) - leaders = sorted({ - str(row.get("time"))[:5] - for row in valid - if abs(_score(row) - best) <= 1e-9 and str(row.get("time") or "")[:5] - }) - deltas = [lib.clock_delta_minutes(stamp, recorded) for stamp in leaders] - return { - "start": outcome["start"], - "end": outcome["end"], - "width": outcome["width"], - "truth_in_range": bool(outcome["truth_in_range"]), - "leader_times": leaders, - "all_within_1min": bool(deltas) and all(abs(delta) <= 1 for delta in deltas), - "any_exact": recorded in leaders, - "error": None, - } - - -def gate_p(result: Mapping[str, Any]) -> bool: - if result.get("mean") is None or result.get("extreme") is None: - return False - exact = (int(result["extreme"]) + 1) / (int(result["permutations"]) + 1) - return bool(result["mean"] > 0 and exact < 0.05) - - -def summarize_rule( - rows: Sequence[Mapping[str, Any]], - *, - seed: int, - permutations: int, -) -> dict[str, Any]: - diffs = [float(row["diff"]) for row in rows] - test = lib.paired_sign_flip_p(diffs, seed=seed, permutations=permutations) - return { - **test, - "pass": gate_p(test), - "truth_mean": mean_defined([row["truth"] for row in rows]), - "placebo_mean": mean_defined([row["placebo"] for row in rows]), - "window_mean": mean_defined([row["window"] for row in rows]), - "fraction_grid_explains_all_mean": mean_defined([row["fraction_all"] for row in rows]), - } - - -def n2_case( - bits: Mapping[int, Sequence[bool]], - coarse: Sequence[int], - events: Sequence[Mapping[str, Any]], - placebo_bits: Mapping[int, Sequence[bool]], - *, - case_id: str, - seed: str, -) -> dict[str, Any]: - deltas_random = [] - deltas_placebo = [] - held_rates = [] - for index, event in enumerate(events): - counts = { - offset: sum(flag for event_index, flag in enumerate(flags) if event_index != index) - for offset, flags in bits.items() - if offset in coarse - } - leaders = [offset for offset in lib.rank_offsets(counts) if offset in set(coarse)] - if not leaders: - continue - held = sum(1 for offset in leaders if bits[offset][index]) / len(leaders) - rng = Random(f"{seed}:{case_id}:{event['id']}") - if len(leaders) >= len(coarse): - sample = list(coarse) - else: - sample = rng.sample(list(coarse), len(leaders)) - random_rate = sum(1 for offset in sample if bits[offset][index]) / len(sample) - placebo_rate = sum(1 for offset in leaders if placebo_bits[offset][index]) / len(leaders) - held_rates.append(held) - deltas_random.append(held - random_rate) - deltas_placebo.append(held - placebo_rate) - return { - "held_rate": mean_defined(held_rates), - "delta_random": mean_defined(deltas_random), - "delta_placebo": mean_defined(deltas_placebo), - } - - -def level_change(base: Sequence[Sequence[str]], other: Sequence[Sequence[str]], index: int) -> float | None: - if not base or len(base) != len(other): - return None - changed = sum(left[index] != right[index] for left, right in zip(base, other, strict=True)) - return lib.round6(changed / len(base)) - - -def build(prereg: Mapping[str, Any], *, limit: int, radii: Sequence[int]) -> dict[str, Any]: - cases = [lib.public_fields(case) for case in lib.load_cases()] - if limit: - cases = cases[:limit] - grids = prereg["grids"] - coarse = offsets_of(grids["coarse_radius_seconds"], grids["coarse_step_seconds"]) - fine = offsets_of(grids["fine_radius_seconds"], grids["fine_step_seconds"]) - truth_offsets = truth_minute_offsets() - union = sorted(set(coarse) | set(fine) | set(truth_offsets)) - rules = list(prereg["rules"]["computed"]) - primary = list(prereg["rules"]["n1_primary"]) - n1_min = int(prereg["samples"]["n1_min_day_events"]) - n2_min = int(prereg["samples"]["n2_min_day_events"]) - permutations = int(prereg["tests"]["permutations"]) - resamples = int(prereg["tests"]["bootstrap_resamples"]) - shift_low = int(prereg["placebo"]["shift_low_days"]) - shift_high = int(prereg["placebo"]["shift_high_days"]) - swap = lib.placebo_swap_dates(cases, seed=int(prereg["placebo"]["swap_seed"])) - rounded = {case_id for case_id in lib.truth_audit(cases)["rounded_5min_case_ids"]} - audit = lib.truth_audit(cases) - recon = [lib.reconcile_case(case) for case in cases] - - n1_rows: dict[str, list[dict[str, Any]]] = {rule: [] for rule in primary} - n1_placebos = ("P1", "P2") - n5_rows: dict[str, list[dict[str, Any]]] = {rule: [] for rule in prereg["rules"]["n5_primary"]} - n2_rows = [] - n3a_rows = [] - n4_rows = [] - fraction_rows: dict[str, list[float]] = {rule: [] for rule in ("A4", "A5", "B1", "B2")} - case_fit: list[dict[str, Any]] = [] - - for index, case in enumerate(cases, start=1): - events = lib.day_events(case) - birth = case["birth"] - print(f"nadi {index}/{len(cases)} {case['case_id']} day_events={len(events)}", flush=True) - skies = collect_skies(birth, union) - real = lord_bundle(skies, events) if events else None - shifted = lib.placebo_shift_dates( - events, - birth["date"], - seed=prereg["placebo"]["shift_seed_template"].format(case_id=case["case_id"]), - low_days=shift_low, - high_days=shift_high, - ) if events else [] - p1 = lord_bundle(skies, shifted) if shifted else None - swapped = swap.get(case["case_id"], []) - p2 = lord_bundle(skies, swapped) if swapped else None - fit_row: dict[str, Any] = { - "case_id": case["case_id"], - "day_events": len(events), - "rounded_5min": case["case_id"] in rounded, - } - if real is not None: - for rule in rules: - if rule.startswith("N5") and rule not in prereg["rules"]["n5_primary"] and rule not in primary: - continue - counts = rule_counts(real, events, rule) - truth = lib.mean_rate(counts, truth_offsets, len(events)) - window = lib.mean_rate(counts, coarse, len(events)) - fraction = lib.fraction_explaining_all(counts, coarse, len(events)) - fit_row[rule] = { - "truth": None if truth is None else lib.round6(truth), - "window": None if window is None else lib.round6(window), - "fraction_all": None if fraction is None else lib.round6(fraction), - } - if rule in fraction_rows and fraction is not None and len(events) >= n1_min: - fraction_rows[rule].append(fraction) - if rule in primary and len(events) >= n1_min and p1 is not None and p2 is not None: - for label, bundle in (("P1", p1), ("P2", p2)): - placebo_rate = lib.mean_rate(rule_counts(bundle, shifted if label == "P1" else swapped, rule), truth_offsets, len(events)) - n1_rows[rule].append({ - "case_id": case["case_id"], - "placebo": label, - "truth": lib.round6(truth or 0.0), - "placebo_rate": None if placebo_rate is None else lib.round6(placebo_rate), - "diff": None if placebo_rate is None else lib.round6((truth or 0.0) - placebo_rate), - "window": None if window is None else lib.round6(window), - "fraction_all": None if fraction is None else lib.round6(fraction), - }) - if rule in n5_rows and len(events) >= n1_min and p1 is not None and p2 is not None: - for label, bundle in (("P1", p1), ("P2", p2)): - placebo_rate = lib.mean_rate(rule_counts(bundle, shifted if label == "P1" else swapped, rule), truth_offsets, len(events)) - n5_rows[rule].append({ - "case_id": case["case_id"], - "placebo": label, - "truth": lib.round6(truth or 0.0), - "placebo_rate": None if placebo_rate is None else lib.round6(placebo_rate), - "diff": None if placebo_rate is None else lib.round6((truth or 0.0) - placebo_rate), - "window": None if window is None else lib.round6(window), - "fraction_all": None if fraction is None else lib.round6(fraction), - }) - if len(events) >= n2_min and p1 is not None: - real_bits = rule_bits(real, events, prereg["rules"]["n2_primary"]) - p1_bits = rule_bits(p1, shifted, prereg["rules"]["n2_primary"]) - # P1 bits are aligned to shifted events, same index as real events. - n2_rows.append({ - "case_id": case["case_id"], - "rounded_5min": case["case_id"] in rounded, - **n2_case( - real_bits, coarse, events, p1_bits, - case_id=case["case_id"], seed=str(prereg["tests"]["n2_random_second_seed"]), - ), - }) - a5_counts = rule_counts(real, events, prereg["rules"]["n3_primary"]) if events else {} - leaders = lib.rank_offsets({offset: a5_counts.get(offset, 0) for offset in coarse}) if events else [] - n3a_rows.append({ - "case_id": case["case_id"], - "rounded_5min": case["case_id"] in rounded, - "day_events": len(events), - "hit_60s": lib.leaders_within(leaders, 60) if events else False, - "hit_120s": lib.leaders_within(leaders, 120) if events else False, - "tied_leaders": len(leaders), - }) - else: - n3a_rows.append({ - "case_id": case["case_id"], - "rounded_5min": case["case_id"] in rounded, - "day_events": 0, - "hit_60s": False, - "hit_120s": False, - "tied_leaders": len(coarse), - }) - case_fit.append(fit_row) - - # N4 at the recorded second only. - if events: - base_sky = skies[0] - base_lords = lib.lords_for_events(base_sky["birth_date"], base_sky["moon_lon"], events) - base_part = int(lib.d150_equal(base_sky["asc_lon"])["part_index"]) - perturbations: dict[str, Any] = {} - for name in prereg["n4"]["ayanamsas"]: - if name == prereg["ayanamsa"]: - continue - sky = lib.sky_at(birth, lib.candidate_moment(birth, 0), ayanamsa=name) - other = lib.lords_for_events(sky["birth_date"], sky["moon_lon"], events) - perturbations[f"ayanamsa:{name}"] = { - "level4": level_change(base_lords, other, 3), - "level5": level_change(base_lords, other, 4), - "d150_changed": int(lib.d150_equal(sky["asc_lon"])["part_index"]) != base_part, - } - for seconds in prereg["n4"]["time_offsets_seconds"]: - sky = skies.get(int(seconds)) or lib.sky_at(birth, lib.candidate_moment(birth, int(seconds))) - other = lib.lords_for_events(sky["birth_date"], sky["moon_lon"], events) - perturbations[f"time:{int(seconds)}"] = { - "level4": level_change(base_lords, other, 3), - "level5": level_change(base_lords, other, 4), - "d150_changed": int(lib.d150_equal(sky["asc_lon"])["part_index"]) != base_part, - } - for km in prereg["n4"]["longitude_shifts_km"]: - try: - moved = lib.shift_longitude_km(float(birth["longitude"]), float(birth["latitude"]), float(km)) - sky = lib.sky_at(birth, lib.candidate_moment(birth, 0), longitude=moved) - other = lib.lords_for_events(sky["birth_date"], sky["moon_lon"], events) - perturbations[f"east_km:{km}"] = { - "level4": level_change(base_lords, other, 3), - "level5": level_change(base_lords, other, 4), - "d150_changed": int(lib.d150_equal(sky["asc_lon"])["part_index"]) != base_part, - "blocked": False, - } - except ValueError: - perturbations[f"east_km:{km}"] = {"blocked": True} - node_sky = lib.sky_at(birth, lib.candidate_moment(birth, 0), node_mode="true") - perturbations["node:true"] = { - "moon_changed": abs(float(node_sky["moon_lon"]) - float(base_sky["moon_lon"])) > 1e-6, - "asc_changed": abs(float(node_sky["asc_lon"]) - float(base_sky["asc_lon"])) > 1e-6, - "rahu_changed": node_sky["rahu_lon"] != base_sky["rahu_lon"], - "level5": level_change(base_lords, lib.lords_for_events(node_sky["birth_date"], node_sky["moon_lon"], events), 4), - } - n4_rows.append({"case_id": case["case_id"], "day_events": len(events), "perturbations": perturbations}) - - def pack_comparisons(bucket: Mapping[str, list[dict[str, Any]]], seed_base: int) -> dict[str, Any]: - packed = {} - cursor = 0 - for rule, rows in bucket.items(): - packed[rule] = {} - for label in n1_placebos: - subset = [ - { - "diff": row["diff"], - "truth": row["truth"], - "placebo": row["placebo_rate"], - "window": row["window"], - "fraction_all": row["fraction_all"], - } - for row in rows - if row["placebo"] == label and row["diff"] is not None - ] - packed[rule][label] = summarize_rule(subset, seed=seed_base + cursor, permutations=permutations) - cursor += 1 - return packed - - n1 = pack_comparisons(n1_rows, int(prereg["tests"]["n1_permutation_seed_base"])) - n5 = pack_comparisons(n5_rows, int(prereg["tests"]["n5_permutation_seed_base"])) - n1_pass = all(item["pass"] for rule in n1.values() for item in rule.values()) - n5_pass = all(item["pass"] for rule in n5.values() for item in rule.values()) - n2_values = [float(row["delta_random"]) for row in n2_rows if row["delta_random"] is not None] - n2_placebo_values = [float(row["delta_placebo"]) for row in n2_rows if row["delta_placebo"] is not None] - n2_ci = lib.bootstrap_mean_ci(n2_values, seed=int(prereg["tests"]["n2_bootstrap_seed"]), resamples=resamples) - n2_placebo_ci = lib.bootstrap_mean_ci( - n2_placebo_values, seed=int(prereg["tests"]["n2_bootstrap_seed"]) + 1, resamples=resamples, - ) - uniform_60 = lib.round6(sum(1 for offset in coarse if abs(offset) <= 60) / len(coarse)) - uniform_120 = lib.round6(sum(1 for offset in coarse if abs(offset) <= 120) / len(coarse)) - - # N3b. Separate from the fit loop so a replay failure does not drop N1. - n3b_rows = [] - gate_radius = int(prereg["n3_protocol"]["radius_gate"]) - for index, case in enumerate(cases, start=1): - print(f"replay {index}/{len(cases)} {case['case_id']}", flush=True) - by_radius = {} - for radius in radii: - try: - snapshot = six_probe(case, radius) - except Exception as exc: # noqa: BLE001 — recorded as a miss, message dropped - snapshot = { - "start": None, - "end": None, - "width": None, - "truth_in_range": False, - "leader_times": [], - "all_within_1min": False, - "any_exact": False, - "error": type(exc).__name__, - } - traceback.print_exc(limit=2) - events = lib.day_events(case) - span = delivery_offsets(snapshot["start"], snapshot["end"], case["birth"]["time"], radius) - if events and span: - skies = collect_skies(case["birth"], span) - bundle = lord_bundle(skies, events) - counts = rule_counts(bundle, events, prereg["rules"]["n3_primary"]) - leaders = lib.rank_offsets(counts) - nadi_hit = lib.leaders_within(leaders, int(prereg["n3_protocol"]["nadi_limit_seconds"])) - tied = len(leaders) - else: - nadi_hit = False - tied = 0 - by_radius[str(radius)] = { - "truth_in_range": snapshot["truth_in_range"], - "width": snapshot["width"], - "baseline_all_within_1min": snapshot["all_within_1min"], - "baseline_any_exact": snapshot["any_exact"], - "nadi_all_within_60s": nadi_hit, - "nadi_tied_leaders": tied, - "improvement": int(nadi_hit) - int(snapshot["all_within_1min"]), - "error": snapshot["error"], - } - n3b_rows.append({ - "case_id": case["case_id"], - "rounded_5min": case["case_id"] in rounded, - "radii": by_radius, - }) - - def n3b_summary(radius: int) -> dict[str, Any]: - key = str(radius) - improvements = [int(row["radii"][key]["improvement"]) for row in n3b_rows] - inside = sum(1 for row in n3b_rows if row["radii"][key]["truth_in_range"]) - ci = lib.bootstrap_mean_ci(improvements, seed=int(prereg["tests"]["n3_bootstrap_seed"]) + radius, resamples=resamples) - return { - "radius": radius, - "truth_in_range": f"{inside}/{len(n3b_rows)}", - "truth_in_range_count": inside, - "truth_in_range_pass": inside >= 76 if len(n3b_rows) == 77 else None, - "baseline_all_within_1min": split_rates( - [{"case_id": row["case_id"], "hit": row["radii"][key]["baseline_all_within_1min"]} for row in n3b_rows], - "hit", rounded, - ), - "baseline_any_exact": rate([row["radii"][key]["baseline_any_exact"] for row in n3b_rows]), - "nadi_all_within_60s": split_rates( - [{"case_id": row["case_id"], "hit": row["radii"][key]["nadi_all_within_60s"]} for row in n3b_rows], - "hit", rounded, - ), - "improvement_ci": ci, - "pass": bool(ci["excludes_zero_positive"] and len(n3b_rows) == 77 and inside >= 76), - } - - def n4_aggregate(label: str, field: str) -> dict[str, Any]: - values = [] - d150_flags = [] - weights = [] - for row in n4_rows: - item = row["perturbations"].get(label) or {} - if item.get("blocked") or item.get(field) is None: - continue - values.append(float(item[field])) - weights.append(int(row["day_events"])) - if "d150_changed" in item: - d150_flags.append(bool(item["d150_changed"])) - event_rate = None - if weights and sum(weights): - event_rate = lib.round6(sum(value * weight for value, weight in zip(values, weights, strict=True)) / sum(weights)) - return { - "event_rate": event_rate, - "case_rate": rate(d150_flags) if field == "level5" else None, - "d150_case_rate": rate(d150_flags), - "cases": len(values), - } - - wording_hits = [] - for name in prereg["n4"]["ayanamsas"]: - if name == prereg["ayanamsa"]: - continue - label = f"ayanamsa:{name}" - level5 = n4_aggregate(label, "level5") - wording_hits.append({ - "switch": f"{prereg['ayanamsa']}->{name}", - "level5_event_rate": level5["event_rate"], - "d150_case_rate": level5["d150_case_rate"], - "over_20pct": bool( - (level5["event_rate"] is not None and level5["event_rate"] > 0.20) - or (level5["d150_case_rate"] is not None and level5["d150_case_rate"] > 0.20) - ), - }) - wording_ban = any(item["over_20pct"] for item in wording_hits) - - n3a = { - "grid": "coarse", - "uniform_within_60s": uniform_60, - "uniform_within_120s": uniform_120, - "published_engine_prior_top1_pm10": 0.18, - "hit_60s": split_rates( - [{"case_id": row["case_id"], "hit": row["hit_60s"]} for row in n3a_rows], "hit", rounded, - ), - "hit_120s": split_rates( - [{"case_id": row["case_id"], "hit": row["hit_120s"]} for row in n3a_rows], "hit", rounded, - ), - } - n3b = {str(radius): n3b_summary(radius) for radius in radii} - n3_pass = bool(n3b.get(str(gate_radius), {}).get("pass")) - - return { - "prereg_sha256": lib.file_sha256(lib.PREREG_PATH), - "library_sha256": lib.file_sha256(Path(__file__).with_name("nadi_seconds_lib.py")), - "runner_sha256": lib.file_sha256(Path(__file__)), - "dataset_sha256": lib.file_sha256(lib.HOLDOUT_V5), - "swisseph": __import__("swisseph").version, - "limit": limit, - "n0": { - "audit": {key: value for key, value in audit.items() if key != "per_case"}, - "per_case_day_events": audit["per_case"], - "reconciliation_mismatch_cases": [row["case_id"] for row in recon if row["mismatches"]], - "reconciliation_events": sum(row["events"] for row in recon), - }, - "n1": { - "pass": n1_pass and not limit, - "comparisons": n1, - "fraction_grid_explains_all_mean": {rule: mean_defined(values) for rule, values in fraction_rows.items()}, - "cases": case_fit, - }, - "n2": { - "pass": bool(n2_ci["excludes_zero_positive"]) and not limit, - "versus_random": n2_ci, - "versus_placebo_date": n2_placebo_ci, - "cases": n2_rows, - }, - "n3": { - "pass": n3_pass and not limit, - "n3a": n3a, - "n3b": n3b, - "cases_n3a": n3a_rows, - "cases_n3b": n3b_rows, - }, - "n4": { - "wording_ban_second_scale": wording_ban, - "ayanamsa_switches": wording_hits, - "time": {str(seconds): n4_aggregate(f"time:{int(seconds)}", "level5") for seconds in prereg["n4"]["time_offsets_seconds"]}, - "time_level4": {str(seconds): n4_aggregate(f"time:{int(seconds)}", "level4") for seconds in prereg["n4"]["time_offsets_seconds"]}, - "longitude_km": {str(km): n4_aggregate(f"east_km:{km}", "level5") for km in prereg["n4"]["longitude_shifts_km"]}, - "longitude_km_d150": {str(km): n4_aggregate(f"east_km:{km}", "level5")["d150_case_rate"] for km in prereg["n4"]["longitude_shifts_km"]}, - "node_mean_to_true": { - "moon_changed_cases": sum(1 for row in n4_rows if row["perturbations"]["node:true"]["moon_changed"]), - "asc_changed_cases": sum(1 for row in n4_rows if row["perturbations"]["node:true"]["asc_changed"]), - "rahu_changed_cases": sum(1 for row in n4_rows if row["perturbations"]["node:true"]["rahu_changed"]), - "level5_event_rate": n4_aggregate("node:true", "level5")["event_rate"], - }, - "cases": n4_rows, - }, - "n5": { - "pass": n5_pass and not limit, - "named_text": "blocked", - "named_text_reason": "no legal Chandra Kala Nadi source in the repository", - "classical_index_status": lib.CLASSICAL_NADI_STATUS, - "comparisons": n5, - }, - "gates": { - "n1": n1_pass and not limit, - "n2": bool(n2_ci["excludes_zero_positive"]) and not limit, - "n3": n3_pass and not limit, - "n4_blocks_second_scale_wording": wording_ban, - "n5": n5_pass and not limit, - }, - } - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", default="10,30,60") - parser.add_argument("--out", default=str(REPORT)) - args = parser.parse_args() - prereg = load_prereg() - radii = tuple(int(item) for item in str(args.radii).split(",") if item.strip()) - payload = build(prereg, limit=int(args.limit), radii=radii) - text = json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n" - out = Path(args.out) - out.parent.mkdir(parents=True, exist_ok=True) - out.write_text(text, encoding="utf-8") - print(json.dumps(payload["gates"], ensure_ascii=False, sort_keys=True), flush=True) - print(f"wrote {out}", flush=True) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/precision_gate_sweep.py b/scripts/research/precision_gate_sweep.py deleted file mode 100644 index 2b927a8ec..000000000 --- a/scripts/research/precision_gate_sweep.py +++ /dev/null @@ -1,967 +0,0 @@ -#!/usr/bin/env python3 -"""Offline sweep: precision-adaptive probe gates and varga sensitivity weights. - -Does not change production defaults. Writes docs/research/precision_gate_2026_09_14.md. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import traceback -from datetime import date -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - NODE_MODE, - compute_candidate_static_contexts, -) -from scripts.rectification.event_probes import discriminating_event_probes # noqa: E402 -import scripts.rectification.event_probes as event_probes # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) -from scripts.research.cluster_width_lib import ( # noqa: E402 - SEPARATION_LEAD, - delivery_from_public, - merge_adjacent_traced, - metrics_bundle, - public_from_clusters, - raw_signature_clusters, - still_valid_public, -) -from scripts.research.cluster_width_probe import replay_public # noqa: E402 -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.precision_gate_lib import ( # noqa: E402 - GATES, - JITTER_SPANS, - PRODUCTION_VARGA_PREFIXES, - TREATMENTS, - VargaPolicy, - ablate_top1, - attach_d60, - changing_vargas, - count_precision, - finest_precision, - gate_verdict, - jitter_day_events, - make_row_provider, - patched_boundary_gate, - threshold_for, - treat_events, - window_minutes_for_radius, -) -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - asked_key, - remaining_after_six, - separates_true, -) - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -REPORT_MD = ROOT / "docs" / "research" / "precision_gate_2026_09_14.md" -REPORT_JSON = ROOT / "docs" / "research" / "precision_gate_2026_09_14.json" -TODAY = date(2026, 9, 14) -RADII = (10, 30, 60) -ASK = ASK_COUNT -VARGA_NAMES = ("V0", "V1", "V2", "V3") - - -def holdout_precision_counts(cases: Sequence[dict[str, Any]]) -> dict[str, int]: - events = [event for case in cases for event in case.get("events") or []] - return count_precision(events) - - -def score_bundle( - case: dict[str, Any], - radius: int, - events: list[dict[str, Any]], - static_contexts: Sequence[dict[str, Any]], - policy: VargaPolicy | None, -) -> dict[str, Any]: - clone = {**case, "events": events, "candidate_radius_minutes": radius} - request = scoring_request_for(clone, radius) - if policy is None: - built = build_event_contribution_matrix(request, static_contexts=static_contexts) - else: - built = build_event_contribution_matrix( - request, - row_provider=make_row_provider(static_contexts, policy), - static_contexts=static_contexts, - ) - rows = score_from_matrix(request, built) - return {"request": scoreable_request(request), "built": built, "rows": rows} - - -def generate_probes( - request: dict[str, Any], - built: dict[str, Any], - times: Sequence[str], - true_time: str, - *, - gate: str, - precision: str, - refresh: bool, - asked_keys: Sequence[str] = (), -) -> list[dict[str, Any]]: - payload = { - **request, - "refresh_probes": refresh, - "asked_probe_keys": list(asked_keys), - } - initial = threshold_for(gate, precision, refresh=False) - refresh_days = threshold_for(gate, precision, refresh=True) - with patched_boundary_gate(initial=initial, refresh=refresh_days): - return discriminating_event_probes( - payload, - built, - scan=window_scan(built), - candidate_times=list(times), - representative_time=true_time, - today=TODAY, - ) - - -def evaluate_delivery( - *, - rows: Sequence[dict[str, Any]], - contexts: Sequence[dict[str, Any]], - probes: Sequence[dict[str, Any]], - true_time: str, -) -> dict[str, Any]: - window_times = [str(row["time"])[:5] for row in rows] - raw = raw_signature_clusters(contexts) - by_time = {str(row["time"])[:5]: row for row in rows if str(row.get("time"))} - merged, _trace = merge_adjacent_traced(raw, by_time) - public = public_from_clusters(merged, rows) - prior = {str(row["time"])[:5]: float(row.get("score") or 0) for row in public} - replay = replay_public(probes=probes, public=public, prior=prior, true_time=true_time) - posterior = [] - eliminated = set(replay["eliminated"]) - for row in public: - stamp = str(row["time"])[:5] - posterior.append({**row, "score": replay["scores"].get(stamp, row["score"])}) - valid = still_valid_public(posterior, replay["scores"], eliminated, lead=SEPARATION_LEAD) - delivery = delivery_from_public(valid) - metrics = metrics_bundle( - public=[row for row in posterior if str(row["time"])[:5] not in eliminated], - true_time=true_time, - window_times=window_times, - delivery_times=delivery["times"], - delivery_width=delivery["width"], - independent=True, - entropy_scores=[ - replay["scores"].get(str(row["time"])[:5], 0.0) - for row in posterior - if str(row["time"])[:5] not in eliminated - ], - ) - reps = [str(row["time"])[:5] for row in public] - remaining, remaining_mode, true_alive = remaining_after_six( - all_times=reps, - scores=replay["scores"], - eliminated=eliminated, - clusters=merged, - true_time=true_time, - ) - asked = list(probes)[:ASK] - return { - "metrics": metrics, - "asked": len(asked), - "probes": len(probes), - "entropy0": (replay["entropy"] or [None])[0], - "entropy6": (replay["entropy"] or [None])[-1], - "eliminated": len(eliminated), - "true_alive": replay["true_alive"], - "remaining": remaining, - "remaining_mode": remaining_mode, - "remaining_alive": true_alive, - "asked_keys": [asked_key(item) for item in asked if asked_key(item)], - "width": delivery["width"], - "coverage": metrics["coverage"], - "top1": metrics["top1_hit"], - "tie": metrics["tie"], - "squeezed": metrics["truth_squeezed"], - } - - -def refresh_stats( - *, - request: dict[str, Any], - built: dict[str, Any], - remaining: Sequence[str], - true_time: str, - gate: str, - precision: str, - asked_keys: Sequence[str], - clusters: Sequence[dict[str, Any]], -) -> dict[str, Any]: - if len(remaining) < 2: - return { - "refresh": 0, "discriminative": 0, "unique": 0, - "mean_gain": None, - } - probes = generate_probes( - request, built, remaining, true_time, - gate=gate, precision=precision, refresh=True, asked_keys=asked_keys, - ) - new_probes = [item for item in probes if asked_key(item) and asked_key(item) not in set(asked_keys)] - discriminative = [ - item for item in new_probes - if separates_true(item, true_time, remaining, clusters) - ] - splits = set() - for probe in discriminative: - yes = tuple(sorted(str(time)[:5] for row in probe.get("expected_outcomes") or [] - for time in (row.get("supports") or []) - if str(row.get("answer_class") or "") in {"yes", "weak_yes"})) - no = tuple(sorted(str(time)[:5] for row in probe.get("expected_outcomes") or [] - for time in (row.get("supports") or []) - if str(row.get("answer_class") or "") == "no")) - splits.add((yes, no)) - gains = [float(item.get("information_gain") or 0) for item in discriminative] - return { - "refresh": len(new_probes), - "discriminative": len(discriminative), - "unique": len(splits), - "mean_gain": round(sum(gains) / len(gains), 4) if gains else None, - } - - -def varga_policy_for( - name: str, - radius: int, - contexts: Sequence[dict[str, Any]], -) -> VargaPolicy: - window = window_minutes_for_radius(radius) - use_d60 = name == "V3" and radius <= 10 - if use_d60: - attach_d60(contexts) - prefixes = PRODUCTION_VARGA_PREFIXES + (("D60",) if use_d60 else ()) - changing = changing_vargas(contexts, prefixes) - return VargaPolicy( - name=name, - window_minutes=window, - changing=changing, - use_d60=use_d60, - ) - - -def run_variant( - *, - request: dict[str, Any], - built: dict[str, Any], - rows: Sequence[dict[str, Any]], - true_time: str, - gate: str, - precision: str, -) -> dict[str, Any]: - contexts = list(built.get("static_contexts") or []) - times = [str(row["time"])[:5] for row in rows] - probes = generate_probes( - request, built, times, true_time, - gate=gate, precision=precision, refresh=False, - ) - delivery = evaluate_delivery( - rows=rows, contexts=contexts, probes=probes, true_time=true_time, - ) - clusters = raw_signature_clusters(contexts) - extra = refresh_stats( - request=request, - built=built, - remaining=delivery["remaining"], - true_time=true_time, - gate=gate, - precision=precision, - asked_keys=delivery["asked_keys"], - clusters=clusters, - ) - return { - "top1": delivery["top1"], - "coverage": delivery["coverage"], - "width": delivery["width"], - "tie": delivery["tie"], - "squeezed": delivery["squeezed"], - "entropy0": delivery["entropy0"], - "entropy6": delivery["entropy6"], - "probes": delivery["probes"], - "asked": delivery["asked"], - "refresh": extra["refresh"], - "discriminative": extra["discriminative"], - "unique": extra["unique"], - "mean_gain": extra["mean_gain"], - "remaining_mode": delivery["remaining_mode"], - "true_alive": delivery["true_alive"], - } - - -def summarize(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: - if not rows: - return { - "n": 0, "top1": None, "coverage": None, "width_median": None, "tie": None, - "squeezed": 0, "entropy0": None, "entropy6": None, "probes_mean": None, - "refresh_mean": None, "discriminative_mean": None, "unique_mean": None, - } - widths = [row["width"] for row in rows if row.get("width") is not None] - entropy0 = [row["entropy0"] for row in rows if row.get("entropy0") is not None] - entropy6 = [row["entropy6"] for row in rows if row.get("entropy6") is not None] - return { - "n": len(rows), - "top1": round(sum(1 for row in rows if row.get("top1")) / len(rows), 4), - "coverage": round(sum(1 for row in rows if row.get("coverage")) / len(rows), 4), - "width_median": statistics.median(widths) if widths else None, - "tie": round(sum(1 for row in rows if row.get("tie")) / len(rows), 4), - "squeezed": sum(1 for row in rows if row.get("squeezed")), - "entropy0": round(sum(entropy0) / len(entropy0), 4) if entropy0 else None, - "entropy6": round(sum(entropy6) / len(entropy6), 4) if entropy6 else None, - "probes_mean": round(sum(int(row.get("probes") or 0) for row in rows) / len(rows), 4), - "refresh_mean": round(sum(int(row.get("refresh") or 0) for row in rows) / len(rows), 4), - "discriminative_mean": round(sum(int(row.get("discriminative") or 0) for row in rows) / len(rows), 4), - "unique_mean": round(sum(int(row.get("unique") or 0) for row in rows) / len(rows), 4), - "alive": sum(1 for row in rows if row.get("true_alive")), - } - - -def md_table(headers: Sequence[str], rows: Sequence[Sequence[Any]]) -> str: - def cell(value: Any) -> str: - if value is None: - return "—" - if isinstance(value, float): - return f"{value:.3f}".rstrip("0").rstrip(".") - return str(value) - - line = "| " + " | ".join(headers) + " |" - sep = "| " + " | ".join("---" if index == 0 else "---:" for index in range(len(headers))) + " |" - body = ["| " + " | ".join(cell(item) for item in row) + " |" for row in rows] - return "\n".join([line, sep, *body]) - - -def decide( - radii: Sequence[int], - m1: dict[str, Any], - m1b: dict[str, Any], - m2: dict[str, Any], - v3_jitter7: dict[str, Any], - combos: dict[str, Any], -) -> tuple[dict[str, dict[str, str]], str, str]: - verdicts: dict[str, dict[str, str]] = {} - for gate in GATES: - if gate == "G0": - continue - labels = [] - notes = [] - for radius in radii: - base = m1[str(radius)]["G0"] - cand = m1[str(radius)][gate] - jitter_row = (m2.get("7") or {}).get(str(radius), {}).get(gate) or {} - squeezed7 = jitter_row.get("squeezed") if jitter_row.get("n") else None - label = gate_verdict(base, cand, jitter7_squeezed=squeezed7) - labels.append(label) - notes.append(f"±{radius}:{label} squeezed7={squeezed7}") - verdicts[gate] = {"verdict": overall_verdict(labels), "note": ";".join(notes)} - for name in ("V1", "V2", "V3"): - labels = [] - notes = [] - for radius in radii: - base = m1b[str(radius)]["V0"] - cand = m1b[str(radius)][name] - jitter_row = v3_jitter7.get(str(radius)) or {} - squeezed7 = jitter_row.get("squeezed") if name == "V3" and jitter_row.get("n") else None - label = gate_verdict(base, cand, jitter7_squeezed=squeezed7) - labels.append(label) - notes.append(f"±{radius}:{label}") - verdicts[name] = {"verdict": overall_verdict(labels), "note": ";".join(notes)} - for radius in radii: - for name, summary in combos.get(str(radius), {}).items(): - base = m1[str(radius)]["G0"] - verdicts[f"{name}@±{radius}"] = { - "verdict": gate_verdict(base, summary, jitter7_squeezed=None), - "note": f"combo vs G0 V0 at ±{radius}", - } - gate_labels = [verdicts[name]["verdict"] for name in GATES if name != "G0"] - varga_labels = [verdicts[name]["verdict"] for name in ("V1", "V2", "V3")] - if any(item == "benefit" for item in gate_labels + varga_labels): - recommended = [ - name for name, row in verdicts.items() - if row["verdict"] == "benefit" and name in {*GATES, "V1", "V2", "V3"} - ] - headline = f"**有收益。** 可另立实现单,推荐:{', '.join(recommended) or '见分表'}。" - decision = "benefit" - elif all(item == "no_benefit" for item in gate_labels + varga_labels): - headline = ( - "**无收益,不立实现单。** 线上 `MIN_BOUNDARY_DAYS=45` / 刷新 30 与等权分盘保持不动。" - "真机卡住的 ±10 窗上,放宽闸门能把宽度从 15 收到 11,但头名从 0.80 掉到 0.75;" - "宽窗上宽度反而变大。V1/V2 与基线相同,V3(D60)在 ±10 把头名降到 0.70。" - "唯一看起来像过门的格子是 G1+V3 在 ±10(命中仍 0.80、宽度 15→11)," - "宽窗上不成立,也没有对该组合做 ±7 记错,不够立实现单。" - ) - decision = "no_benefit" - else: - headline = "**不确定,不立实现单。** 分半径或分档结果不一致,见下表。" - decision = "uncertain" - return verdicts, headline, decision - - -def overall_verdict(labels: Sequence[str]) -> str: - if not labels: - return "uncertain" - if all(item == "benefit" for item in labels): - return "benefit" - if all(item == "no_benefit" for item in labels): - return "no_benefit" - return "uncertain" - - -def write_report(payload: dict[str, Any]) -> None: - m0 = payload.get("m0") or {} - m1 = payload.get("m1") or {} - m1b = payload.get("m1b") or {} - m2 = payload.get("m2") or {} - m3 = payload.get("m3") or {} - verdicts = payload.get("verdicts") or {} - headline = payload.get("headline") or "**不确定**" - counts = payload.get("precision_counts") or {} - main_verdicts = { - name: row for name, row in verdicts.items() - if name in {"G1", "G2", "G3", "G4", "V1", "V2", "V3"} - } - lines = [ - "# 出题闸门按证据精度分档测量(2026-09-14)", - "", - f"- 口径:ayanamsa `{payload['ayanamsa']}`,node mode `{payload['node_mode']}`。不得与上游 true-node 数字直接对比。", - f"- 数据:`{payload['holdout']}`,{payload['case_count']} 例公开 Rodden-AA。" - f"精度 日 {counts.get('day', 0)} / 月 {counts.get('month', 0)} / 年 {counts.get('year', 0)}。", - f"- 半径:{', '.join(f'±{item}' for item in payload['radii'])},步长 {payload['minute_step']} 分钟。", - "- 性质:离线测量。生产 `event_probes.py` 的 `MIN_BOUNDARY_DAYS=45` / `REFRESH_MIN_BOUNDARY_DAYS=30` 未改;计分引擎等权分盘未改。", - "- 线上对照:`unionStillValidRange` = 未淘汰且落后头名不足 8 分的簇覆盖并集。", - "", - "## 结论", - "", - headline, - "", - "判定口径:命中不降 **且** 宽度下降才算有收益;只多出题而宽度变宽不算。" - "±7 天记错挤出真值的档位一律不推荐。本网格覆盖率始终 20/20,M2 挤出全是 0。", - "", - md_table( - ["方案", "判定", "说明"], - [[name, row.get("verdict"), row.get("note")] for name, row in main_verdicts.items()], - ), - "", - "过运与三大外部引擎未参与本单(纯出题闸门 / 分盘配权,不解释运势)。", - "", - "## M0 · 精度处理三组(生产闸门)", - "", - "同一批例子、生产 45/30 闸。A 原样,B 日→月,C 全部→年。用来隔离精度本身,而不是闸门。", - "", - ] - for radius in payload["radii"]: - lines.append(f"### ±{radius}") - lines.append("") - table = [] - for treatment in TREATMENTS: - summary = ((m0.get(str(radius)) or {}).get(treatment) or {}) - table.append([ - treatment, - summary.get("top1"), - summary.get("coverage"), - summary.get("width_median"), - summary.get("tie"), - summary.get("squeezed"), - summary.get("probes_mean"), - summary.get("refresh_mean"), - ]) - lines.append(md_table( - ["组", "头名命中", "区间覆盖", "宽度中位", "并列率", "挤出", "首轮出题均", "六题后再出"], - table, - )) - lines.append("") - lines.append( - "对 BUG-689 邀请文案:组 A 与把日精度降成月的组 B 在 ±10 上命中/宽度完全一样(0.80 / 15)。" - "全部降成年精度的组 C 命中只掉到 0.75。v4 没有原生月精度事件," - "**不能**把「记得到天比记得到月有用得多」写成已证实,更不能承诺能定到分钟。" - ) - lines.append("") - lines.extend(["## M1 · 闸门分档(组 A)", ""]) - for radius in payload["radii"]: - lines.append(f"### ±{radius}") - lines.append("") - table = [] - for gate in GATES: - summary = ((m1.get(str(radius)) or {}).get(gate) or {}) - table.append([ - gate, - summary.get("top1"), - summary.get("coverage"), - summary.get("width_median"), - summary.get("tie"), - summary.get("squeezed"), - summary.get("probes_mean"), - summary.get("refresh_mean"), - summary.get("discriminative_mean"), - ]) - lines.append(md_table( - ["档", "头名命中", "区间覆盖", "宽度中位", "并列率", "挤出", "首轮出题均", "六题后再出", "有分辨力"], - table, - )) - lines.append("") - lines.extend([ - "## M1b · 分盘按分钟敏感度配权", - "", - "V0 生产等权;V1 `min(window/varga_minutes, 1)` 再除以 `2n`;V2 只计窗内至少变一次的盘;V3 = V2 + D60(仅 ±10)。", - "未出现在上游表里的 D2/D3/D5/D7/D11 用 `120/n` 分钟。" - "按盘贡献表本轮是空的:V0 采集误走了生产计分、没有打上分盘标签;" - "但 V1/V2 三档半径都与 V0 数字相同,V3 只在 ±10 把命中从 0.80 降到 0.70,已经够判断这三档不能上线。", - "", - ]) - for radius in payload["radii"]: - lines.append(f"### ±{radius}") - lines.append("") - table = [] - for name in VARGA_NAMES: - summary = ((m1b.get(str(radius)) or {}).get(name) or {}) - table.append([ - name, - summary.get("top1"), - summary.get("coverage"), - summary.get("width_median"), - summary.get("tie"), - summary.get("squeezed"), - ]) - lines.append(md_table( - ["改法", "头名命中", "区间覆盖", "宽度中位", "并列率", "挤出"], - table, - )) - lines.append("") - combos = payload.get("combos") or {} - if combos: - lines.extend(["### 闸门 × 分盘组合(组 A)", ""]) - for radius in payload["radii"]: - table = [] - for name, summary in (combos.get(str(radius)) or {}).items(): - table.append([ - name, - summary.get("top1"), - summary.get("coverage"), - summary.get("width_median"), - summary.get("squeezed"), - summary.get("refresh_mean"), - ]) - if table: - lines.append(f"±{radius}") - lines.append("") - lines.append(md_table( - ["组合", "头名命中", "区间覆盖", "宽度中位", "挤出", "六题后再出"], - table, - )) - lines.append("") - contrib = payload.get("varga_contribution") or {} - if contrib: - lines.extend(["### 各分盘触发与头名贡献", ""]) - table = [] - for prefix, row in contrib.items(): - table.append([ - prefix, - row.get("hits"), - row.get("top1_flips"), - row.get("flip_rate"), - ]) - lines.append(md_table(["分盘", "触发次数", "去掉后头名变化例数", "变化率"], table)) - lines.append("") - lines.extend([ - "## M2 · 答错容忍度(日精度事件日期偏移)", - "", - "组 A 的日精度事件按例、按事件独立随机偏移(种子 20260914,排除 0)。±7 天出现真值挤出的档位不得推荐。", - "", - ]) - for span in JITTER_SPANS: - lines.append(f"### ±{span} 天") - lines.append("") - table = [] - for radius in payload["radii"]: - for gate in GATES: - summary = (((m2.get(str(span)) or {}).get(str(radius)) or {}).get(gate) or {}) - table.append([ - f"±{radius} {gate}", - summary.get("top1"), - summary.get("coverage"), - summary.get("squeezed"), - summary.get("width_median"), - ]) - lines.append(md_table(["格子", "头名命中", "区间覆盖", "挤出", "宽度中位"], table)) - lines.append("") - v3_jitter = payload.get("v3_jitter7") or {} - if v3_jitter: - lines.append("V3 在 ±7 天偏移下:") - lines.append("") - table = [] - for radius in payload["radii"]: - summary = v3_jitter.get(str(radius)) or {} - table.append([ - f"±{radius}", - summary.get("top1"), - summary.get("coverage"), - summary.get("squeezed"), - ]) - lines.append(md_table(["半径", "头名命中", "区间覆盖", "挤出"], table)) - lines.append("") - lines.extend([ - "## M3 · 六题之后还能再出几道", - "", - "数字见 M1 表的「六题后再出」与「有分辨力」。若新增 ≥8 道而宽度只收 1–2 分钟,判定里记为问答成本高于收益。", - "", - md_table( - ["半径", "档", "再出均", "有分辨力均", "宽度中位"], - m3.get("rows") or [], - ), - "", - "## 方法", - "", - "1. 每例先算一次静态盘(与事件无关),再按精度处理 / 偏移 / 分盘政策套 `build_event_contribution_matrix`。", - "2. 闸门只通过研究脚本临时改 `MIN_BOUNDARY_DAYS` / `REFRESH_MIN_BOUNDARY_DAYS`,函数返回后立刻恢复。", - "3. 参与该题的证据精度取该例事件包里最细的一档(有日用日,否则月,否则年)。", - "4. 六题回放用真值簇最优 yes/no(上界,不是真人会怎么答)。交付口径与簇宽度研究相同:lead 8 未淘汰并集。", - "5. 刷新出题走生产 `refresh_probes=true`(含已落地的 R3/R4),只换边界天数闸。", - "", - f"错误 {len(payload.get('errors') or [])} 例。{payload.get('case_count', 0)} 例跑完。", - "", - ]) - if payload.get("errors"): - lines.append("失败例子:") - for row in payload["errors"]: - lines.append(f"- `{row.get('case_id')}` {row.get('error')}") - lines.append("") - REPORT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8") - slim = dict(payload) - slim.pop("case_rows", None) - REPORT_JSON.write_text(json.dumps(slim, ensure_ascii=True, indent=2) + "\n", encoding="utf-8") - - -CHECKPOINT = ROOT / "scratch" / "precision_gate_checkpoint.json" - - -def _log(message: str) -> None: - print(message, flush=True) - path = ROOT / "scratch" / "precision_gate_sweep.log" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(message + "\n") - - -def _empty_state(radii: Sequence[int]) -> dict[str, Any]: - return { - "done": [], - "m0_rows": {str(radius): {name: [] for name in TREATMENTS} for radius in radii}, - "m1_rows": {str(radius): {name: [] for name in GATES} for radius in radii}, - "m1b_rows": {str(radius): {name: [] for name in VARGA_NAMES} for radius in radii}, - "combo_rows": {str(radius): {} for radius in radii}, - "m2_rows": { - str(span): {str(radius): {name: [] for name in GATES} for radius in radii} - for span in JITTER_SPANS - }, - "v3_jitter_rows": {str(radius): [] for radius in radii}, - "ablations": [], - "errors": [], - } - - -def _save_checkpoint(state: dict[str, Any]) -> None: - CHECKPOINT.parent.mkdir(parents=True, exist_ok=True) - CHECKPOINT.write_text(json.dumps(state, ensure_ascii=True), encoding="utf-8") - - -def _load_checkpoint(radii: Sequence[int]) -> dict[str, Any]: - if not CHECKPOINT.exists(): - return _empty_state(radii) - payload = json.loads(CHECKPOINT.read_text(encoding="utf-8")) - empty = _empty_state(radii) - for key in empty: - if key in payload: - empty[key] = payload[key] - return empty - - -def run(args: argparse.Namespace) -> dict[str, Any]: - holdout = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(holdout["cases"]) - if args.limit: - cases = cases[: args.limit] - radii = tuple(int(item) for item in args.radii) - precision_counts = holdout_precision_counts(holdout["cases"]) - state = _load_checkpoint(radii) if args.resume else _empty_state(radii) - m0_rows = state["m0_rows"] - m1_rows = state["m1_rows"] - m1b_rows = state["m1b_rows"] - combo_rows = state["combo_rows"] - m2_rows = state["m2_rows"] - v3_jitter_rows = state["v3_jitter_rows"] - ablations = state["ablations"] - errors = state["errors"] - done = set(state.get("done") or []) - assert event_probes.MIN_BOUNDARY_DAYS == 45 - assert event_probes.REFRESH_MIN_BOUNDARY_DAYS == 30 - - for case in cases: - case_id = case["case_id"] - true_time = str(case["birth"]["time"])[:5] - if case_id in done: - _log(f"skip {case_id}") - continue - _log(f"case {case_id}") - try: - for radius in radii: - base_request = scoring_request_for({**case, "candidate_radius_minutes": radius}, radius) - contexts = compute_candidate_static_contexts(base_request) - original_events = list(case.get("events") or []) - scored: dict[str, dict[str, Any]] = {} - for treatment in TREATMENTS: - events = treat_events(original_events, treatment) - scored[treatment] = score_bundle(case, radius, events, contexts, None) - precision = finest_precision(events) - measured = run_variant( - request=scored[treatment]["request"], - built=scored[treatment]["built"], - rows=scored[treatment]["rows"], - true_time=true_time, - gate="G0", - precision=precision, - ) - measured["case_id"] = case_id - m0_rows[str(radius)][treatment].append(measured) - a_precision = finest_precision(original_events) - for gate in GATES: - if gate == "G0": - measured = dict(m0_rows[str(radius)]["A"][-1]) - else: - measured = run_variant( - request=scored["A"]["request"], - built=scored["A"]["built"], - rows=scored["A"]["rows"], - true_time=true_time, - gate=gate, - precision=a_precision, - ) - measured["case_id"] = case_id - m1_rows[str(radius)][gate].append(measured) - scores_a = { - str(row["time"])[:5]: float(row.get("score") or 0) - for row in scored["A"]["rows"] - } - v0_policy = varga_policy_for("V0", radius, contexts) - v0_row = candidate_ablation = None - _log(f" radius ±{radius} varga") - for v_name in VARGA_NAMES: - policy = varga_policy_for(v_name, radius, contexts) - if v_name == "V0": - bundle = scored["A"] - v0_policy = policy - else: - bundle = score_bundle(case, radius, original_events, contexts, policy) - measured = run_variant( - request=bundle["request"], - built=bundle["built"], - rows=bundle["rows"], - true_time=true_time, - gate="G0", - precision=a_precision, - ) - measured["case_id"] = case_id - measured["changing"] = sorted(policy.changing) - m1b_rows[str(radius)][v_name].append(measured) - if v_name == "V0": - v0_row = bundle - scored[v_name] = bundle - if v_name != "V0": - for gate in GATES: - if gate == "G0": - continue - combo = run_variant( - request=bundle["request"], - built=bundle["built"], - rows=bundle["rows"], - true_time=true_time, - gate=gate, - precision=a_precision, - ) - combo["case_id"] = case_id - combo_rows[str(radius)].setdefault(f"{gate}+{v_name}", []).append(combo) - if v0_row is not None: - # Re-score V0 through the policy scorer only to collect per-varga points. - collector = varga_policy_for("V0", radius, contexts) - score_bundle(case, radius, original_events, contexts, collector) - candidate_ablation = ablate_top1(scores_a, collector.points_by_time, true_time) - candidate_ablation["case_id"] = case_id - candidate_ablation["radius"] = radius - candidate_ablation["hits"] = dict(collector.hits) - ablations.append(candidate_ablation) - if not args.skip_m2: - _log(f" radius ±{radius} jitter") - for span in JITTER_SPANS: - jittered = jitter_day_events(original_events, span, case_id=case_id) - bundle = score_bundle(case, radius, jittered, contexts, None) - jitter_precision = finest_precision(jittered) - for gate in GATES: - measured = run_variant( - request=bundle["request"], - built=bundle["built"], - rows=bundle["rows"], - true_time=true_time, - gate=gate, - precision=jitter_precision, - ) - measured["case_id"] = case_id - m2_rows[str(span)][str(radius)][gate].append(measured) - _log(f" radius ±{radius} V3±7") - jitter7 = jitter_day_events(original_events, 7, case_id=case_id) - v3_policy = varga_policy_for("V3", radius, contexts) - bundle = score_bundle(case, radius, jitter7, contexts, v3_policy) - measured = run_variant( - request=bundle["request"], - built=bundle["built"], - rows=bundle["rows"], - true_time=true_time, - gate="G0", - precision=finest_precision(jitter7), - ) - measured["case_id"] = case_id - v3_jitter_rows[str(radius)].append(measured) - _log( - f" radius ±{radius} A_probes={m1_rows[str(radius)]['G0'][-1]['probes']} " - f"G3_probes={m1_rows[str(radius)]['G3'][-1]['probes']}", - ) - except Exception as exc: # noqa: BLE001 - errors.append({ - "case_id": case_id, - "error": f"{type(exc).__name__}: {exc}", - "trace": traceback.format_exc(), - }) - _log(f" FAIL {case_id}: {exc}") - done.add(case_id) - state = { - "done": sorted(done), - "m0_rows": m0_rows, - "m1_rows": m1_rows, - "m1b_rows": m1b_rows, - "combo_rows": combo_rows, - "m2_rows": m2_rows, - "v3_jitter_rows": v3_jitter_rows, - "ablations": ablations, - "errors": errors, - } - _save_checkpoint(state) - _log(f" checkpoint {len(done)}/{len(cases)}") - assert event_probes.MIN_BOUNDARY_DAYS == 45 - assert event_probes.REFRESH_MIN_BOUNDARY_DAYS == 30 - - m0 = {radius: {name: summarize(rows) for name, rows in treatments.items()} for radius, treatments in m0_rows.items()} - m1 = {radius: {name: summarize(rows) for name, rows in gates.items()} for radius, gates in m1_rows.items()} - m1b = {radius: {name: summarize(rows) for name, rows in variants.items()} for radius, variants in m1b_rows.items()} - combos = { - radius: {name: summarize(rows) for name, rows in variants.items()} - for radius, variants in combo_rows.items() - } - m2 = { - span: { - radius: {gate: summarize(rows) for gate, rows in gates.items()} - for radius, gates in radii_map.items() - } - for span, radii_map in m2_rows.items() - } - v3_jitter7 = {radius: summarize(rows) for radius, rows in v3_jitter_rows.items()} - contribution: dict[str, dict[str, Any]] = {} - prefixes = sorted({prefix for row in ablations for prefix in (row.get("hits") or {})}) - n_ablate = max(len(ablations), 1) - for prefix in prefixes: - hits = sum(int((row.get("hits") or {}).get(prefix) or 0) for row in ablations) - flips = sum(int((row.get("flips") or {}).get(prefix) or 0) for row in ablations) - contribution[prefix] = { - "hits": hits, - "top1_flips": flips, - "flip_rate": round(flips / n_ablate, 4), - } - verdicts, headline, decision = decide(radii, m1, m1b, m2, v3_jitter7, combos) - m3_rows = [] - for radius in radii: - for gate in GATES: - summary = m1[str(radius)][gate] - m3_rows.append([ - f"±{radius}", gate, - summary.get("refresh_mean"), - summary.get("discriminative_mean"), - summary.get("width_median"), - ]) - payload = { - "generated_at": TODAY.isoformat(), - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "holdout": str(HOLDOUT.relative_to(ROOT)).replace("\\", "/"), - "case_count": len(cases), - "radii": list(radii), - "minute_step": MINUTE_STEP, - "precision_counts": precision_counts, - "headline": headline, - "decision": decision, - "m0": m0, - "m1": m1, - "m1b": m1b, - "combos": combos, - "m2": m2, - "v3_jitter7": v3_jitter7, - "m3": {"rows": m3_rows}, - "varga_contribution": contribution, - "verdicts": verdicts, - "errors": errors, - "production_gate": { - "MIN_BOUNDARY_DAYS": event_probes.MIN_BOUNDARY_DAYS, - "REFRESH_MIN_BOUNDARY_DAYS": event_probes.REFRESH_MIN_BOUNDARY_DAYS, - }, - } - write_report(payload) - return payload - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", nargs="+", default=[str(item) for item in RADII]) - parser.add_argument("--skip-m2", action="store_true") - parser.add_argument("--resume", action="store_true") - parser.add_argument("--from-json", action="store_true") - args = parser.parse_args() - if args.from_json: - payload = json.loads(REPORT_JSON.read_text(encoding="utf-8")) - radii = tuple(int(item) for item in payload["radii"]) - verdicts, headline, decision = decide( - radii, - payload["m1"], - payload["m1b"], - payload.get("m2") or {}, - payload.get("v3_jitter7") or {}, - payload.get("combos") or {}, - ) - payload["verdicts"] = verdicts - payload["headline"] = headline - payload["decision"] = decision - write_report(payload) - else: - payload = run(args) - print( - f"wrote {REPORT_MD} cases={payload['case_count']} errors={len(payload['errors'])} " - f"decision={payload['decision']}", - flush=True, - ) - return 0 if not payload["errors"] else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/probe_supply_after_six.py b/scripts/research/probe_supply_after_six.py deleted file mode 100644 index 70725c69a..000000000 --- a/scripts/research/probe_supply_after_six.py +++ /dev/null @@ -1,1224 +0,0 @@ -#!/usr/bin/env python3 -"""Offline measurement: can refresh emit more dated probes after six answers? - -Does not change production `event_probes.py` defaults. Relaxations are applied -only inside this script via temporary module patches. -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import traceback -from calendar import monthrange -from contextlib import contextmanager, nullcontext -from dataclasses import dataclass -from datetime import date -from pathlib import Path -from typing import Any, Iterator, Sequence -from uuid import NAMESPACE_URL, uuid5 - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.rectification.candidate_contrast import ( # noqa: E402 - cluster_contexts_by_signature, - distinguish_contract_errors, -) -from scripts.rectification.contracts import normalize_rectification_request # noqa: E402 -from scripts.rectification.event_probes import ( # noqa: E402 - DOMAIN_CATALOG, - EXISTENCE_NEARBY_YEARS, - MAX_BOUNDARY_CANDIDATES_PER_DOMAIN, - MIN_BOUNDARY_DAYS, - PROBE_PHASE_CANDIDATE_DISCRIMINATOR, - _annotate_nearby_ledger, - _answer_priors_for, - _apply_prior_ranking, - _best_probe_per_year, - _boundary_windows, - _differing_layers, - _dominant_existence_prior, - _evaluation_order, - _event_years, - _existence_blocked_years, - _layer_value, - _narayana_cache_key, - _narayana_start_dates, - _partition_ranked_probes, - _probe_caps, - _probe_domains, - _probe_sort_key, - _quality_distinguish_probes, - _remaining_contexts, - _representative_pairs, - _scoreable, - _static_contexts, - _try_activation_probe, - _vim_cache_key, - _vim_start_dates, - asked_years_for_domain, - discriminating_event_probes, -) -from scripts.rectification.case_holdout import holdout_domain_years, holdout_event_ids # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) - -HOLDOUT_MANIFEST = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v3.json" -TODAY = date(2026, 9, 13) -ASK_COUNT = 6 -REMAINING_CAP = 5 -STRONG_CONFLICT_ELIMINATION_COUNT = 3 -SCORE_DELTA = { - "support": 2.0, - "weak_support": 1.0, - "neutral": 0.0, - "weak_conflict": -1.0, - "conflict": -2.0, -} -KIND_BY_DOMAIN = { - "education": "education_milestone", - "career": "career_change", - "relationship": "relationship_commitment", - "relocation": "relocation", - "health_pressure": "self_health_event", - "health": "self_health_event", - "finance": "finance_change", - "family": "family_event", -} -EXTRA_FAMILIES: dict[str, tuple[tuple[str, str], ...]] = { - "career": ( - ("career_entry", "入职"), - ("promotion", "升职"), - ("career_exit", "离职"), - ), - "relationship": ( - ("relationship_commitment", "结婚"), - ("relationship_separation", "分手"), - ), -} - - -@dataclass(frozen=True) -class Relaxation: - r1: bool = False - r2: bool = False - r3: bool = False - r4: bool = False - - @property - def name(self) -> str: - labels = [ - label - for label, on in (("R1", self.r1), ("R2", self.r2), ("R3", self.r3), ("R4", self.r4)) - if on - ] - return "+".join(labels) if labels else "baseline" - - -def all_relaxations() -> list[Relaxation]: - rows: list[Relaxation] = [] - for mask in range(16): - rows.append(Relaxation( - r1=bool(mask & 1), - r2=bool(mask & 2), - r3=bool(mask & 4), - r4=bool(mask & 8), - )) - return rows - - -def _clock(value: str) -> int: - return int(value[:2]) * 60 + int(value[3:5]) - - -def _hhmm_from_minutes(value: int) -> str: - wrapped = value % 1440 - return f"{wrapped // 60:02d}:{wrapped % 60:02d}" - - -def _shift_clock(value: str, delta: int) -> str: - return _hhmm_from_minutes(_clock(value) + delta) - - -def _expand_date(raw: str, precision: str) -> tuple[str, str]: - text = str(raw or "").strip() - if precision == "day": - day = date.fromisoformat(text) - return day.isoformat(), day.isoformat() - if precision == "month": - month = date.fromisoformat(f"{text}-01") if len(text) == 7 else date.fromisoformat(text[:10]).replace(day=1) - last = monthrange(month.year, month.month)[1] - return month.isoformat(), month.replace(day=last).isoformat() - year = int(text[:4]) - return f"{year}-01-01", f"{year}-12-31" - - -def _event_kind(event: dict[str, Any]) -> str: - domain = str(event.get("domain") or "") - description = str(event.get("description") or "").lower() - if domain == "relationship" and not any( - token in description for token in ("married", "wedding", "wife", "husband") - ): - return "relationship_start" - return KIND_BY_DOMAIN[domain] - - -def request_from_case(case: dict[str, Any]) -> dict[str, Any]: - birth = case["birth"] - true_time = str(birth["time"])[:5] - radius = int(case.get("candidate_radius_minutes") or 10) - events = [] - for event in case.get("events") or []: - precision = str(event.get("precision") or "year") - start, end = _expand_date(str(event.get("date") or ""), precision) - domain = str(event.get("domain") or "") - events.append({ - "id": str(uuid5(NAMESPACE_URL, str(event.get("id") or ""))), - "domain": domain, - "event_kind": _event_kind(event), - "date_start": start, - "date_end": end, - "precision": precision, - "summary": str(event.get("description") or event.get("id") or domain)[:200], - }) - return normalize_rectification_request({ - "birth_date": str(birth["date"]), - "start_time": _shift_clock(true_time, -radius), - "end_time": _shift_clock(true_time, radius), - "lat": float(birth["latitude"]), - "lon": float(birth["longitude"]), - "tz": float(birth["timezone_offset"]), - "events": events, - }, today=TODAY) - - -def _scan_for(built: dict[str, Any]) -> dict[str, Any]: - return window_scan(built) - - -def family_slug(kind: str) -> str: - return kind.replace("_", "-") - - -@contextmanager -def patched_boundary_days(days: int) -> Iterator[None]: - import scripts.rectification.event_probes as ep - previous = ep.MIN_BOUNDARY_DAYS - ep.MIN_BOUNDARY_DAYS = days - try: - yield - finally: - ep.MIN_BOUNDARY_DAYS = previous - - -@contextmanager -def catalog_family(domain: str, kind: str, family: str) -> Iterator[None]: - original = DOMAIN_CATALOG[domain] - DOMAIN_CATALOG[domain] = {**original, "kind": kind, "event_family": family} - try: - yield - finally: - DOMAIN_CATALOG[domain] = original - - -def union_boundary_dates( - reps: Sequence[dict[str, Any]], - *, - birth_date: str, - lo: int, - hi: int, - include_pratyantar: bool, - varga_narayana: bool, -) -> list[date]: - vim_cache: dict[tuple[Any, ...], list[date]] = {} - narayana_cache: dict[tuple[Any, ...], list[date] | None] = {} - dates_by_key: dict[tuple[int, int], date] = {} - for left, right in _representative_pairs(reps): - left_moon = float(left["planet_longitudes"]["Moon"]) - right_moon = float(right["planet_longitudes"]["Moon"]) - left_vim_key = (*_vim_cache_key(birth_date, left_moon, lo, hi), include_pratyantar) - right_vim_key = (*_vim_cache_key(birth_date, right_moon, lo, hi), include_pratyantar) - if left_vim_key not in vim_cache: - vim_cache[left_vim_key] = _vim_start_dates( - birth_date, left_moon, lo, hi, include_pratyantar=include_pratyantar, - ) - if right_vim_key not in vim_cache: - vim_cache[right_vim_key] = _vim_start_dates( - birth_date, right_moon, lo, hi, include_pratyantar=include_pratyantar, - ) - windows = list(_boundary_windows(vim_cache[left_vim_key], vim_cache[right_vim_key])) - layers: list[str | None] = [None] - if varga_narayana: - layers.extend(["d9", "d10"]) - for layer in layers: - if layer is None: - left_asc = int(left["ascendant_index"]) - right_asc = int(right["ascendant_index"]) - else: - left_raw = _layer_value(left, layer) - right_raw = _layer_value(right, layer) - if not isinstance(left_raw, int) or not isinstance(right_raw, int): - continue - left_asc = left_raw - right_asc = right_raw - left_nara_key = (*_narayana_cache_key( - left_asc, left["planet_longitudes"], birth_date, lo, hi, - ), layer) - right_nara_key = (*_narayana_cache_key( - right_asc, right["planet_longitudes"], birth_date, lo, hi, - ), layer) - if left_nara_key not in narayana_cache: - narayana_cache[left_nara_key] = _narayana_start_dates( - left_asc, left["planet_longitudes"], birth_date, lo, hi, - ) - if right_nara_key not in narayana_cache: - narayana_cache[right_nara_key] = _narayana_start_dates( - right_asc, right["planet_longitudes"], birth_date, lo, hi, - ) - left_narayana = narayana_cache[left_nara_key] - right_narayana = narayana_cache[right_nara_key] - if left_narayana is not None and right_narayana is not None: - windows.extend(_boundary_windows(left_narayana, right_narayana)) - for item in windows: - dates_by_key.setdefault((item.year, item.month), item) - return sorted(dates_by_key.values(), key=lambda item: (item.year, item.month)) - - -def best_probe_per_year_family(rows: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: - by_key: dict[tuple[int, str], dict[str, Any]] = {} - for row in sorted(rows, key=_probe_sort_key): - key = (int(row["year"]), str(row.get("event_family") or "")) - if key not in by_key: - by_key[key] = row - return list(by_key.values()) - - -def partition_probes( - probes: Sequence[dict[str, Any]], - *, - max_probes: int, - include_family: bool, -) -> list[dict[str, Any]]: - if not include_family: - public, _dropped = _partition_ranked_probes(probes, max_probes=max_probes) - return public - public: list[dict[str, Any]] = [] - seen: set[tuple[str, int, int, str, str]] = set() - for row in probes: - if row.get("source") == "known_event_quality" and not ( - row.get("role") == "distinguish" and row.get("target_evidence_id") - ): - continue - if row.get("phase") != PROBE_PHASE_CANDIDATE_DISCRIMINATOR: - continue - if distinguish_contract_errors(row): - continue - ranked = row if "raw_split_gain" in row else _apply_prior_ranking(dict(row)) - priors = ranked.get("answer_priors") or _answer_priors_for(ranked) - if _dominant_existence_prior(ranked, priors): - continue - if not isinstance(ranked.get("year"), int) or int(ranked["year"]) <= 0: - continue - key = ( - str(ranked["domain"]), - int(ranked["year"]), - int(ranked.get("month") or 0), - str(ranked["source"]), - str(ranked.get("event_family") or ""), - ) - if key in seen or "points" in str(ranked): - continue - seen.add(key) - public.append(ranked) - if len(public) >= max_probes: - break - public.sort(key=_probe_sort_key) - return public - - -def annotate_family(row: dict[str, Any], *, kind: str, family: str) -> dict[str, Any]: - payload = dict(row) - payload["event_family"] = family - payload["event_kind"] = kind - month = payload.get("month") - source = str(payload.get("source") or "dasha_boundary") - domain = str(payload.get("domain") or "") - year = int(payload["year"]) - slug = family_slug(kind) - if isinstance(month, int) and 1 <= month <= 12: - payload["semantic_key"] = f"{domain}.{year}.{month:02d}.{source}.{slug}" - else: - payload["semantic_key"] = f"{domain}.{year}.{source}.{slug}" - return payload - - -def generate_refresh_probes( - request: dict[str, Any], - built: dict[str, Any], - *, - remaining_times: Sequence[str], - relax: Relaxation, - today: date, -) -> list[dict[str, Any]]: - birth_date = str(request.get("birth_date") or "").strip() - birth_year = int(birth_date[:4]) - events = [item for item in (request.get("events") or []) if isinstance(item, dict)] - asked_probe_keys = [ - str(item).strip() - for item in (request.get("asked_probe_keys") or []) - if isinstance(item, str) and str(item).strip() - ] - holdout_keys = holdout_domain_years(events) - remaining = _remaining_contexts(built, remaining_times) - if len(remaining) < 2: - return [] - clusters = cluster_contexts_by_signature(remaining) - if len(clusters) < 2: - return [] - reps = [cluster["representative"] for cluster in clusters if _scoreable(cluster["representative"])] - if len(reps) < 2: - reps = [item for item in remaining if _scoreable(item)] - if len(reps) < 2: - return [] - max_probes, max_per_domain = _probe_caps(refresh=True, remaining_count=len(remaining)) - from scripts.rectification.candidate_contrast import candidate_set_version - set_version = candidate_set_version([cluster["times"] for cluster in clusters]) - remaining_layers = _differing_layers(remaining) - scan = _scan_for(built) - if not remaining_layers: - remaining_layers = { - layer for layer in ( - "d1", "d9", "d10", "d4", "d5", "d24", "d7", "d12", "d2", "d11", "d30", - ) - if scan.get(f"{layer}_candidates_differ") - } - domains = _probe_domains( - remaining_layers, - events, - d1_differs="d1" in remaining_layers or bool(scan.get("d1_candidates_differ")), - ) - lo, hi = birth_year + 5, min(today.year, birth_year + 80) - with patched_boundary_days(30 if relax.r3 else MIN_BOUNDARY_DAYS): - boundary_dates = union_boundary_dates( - reps, - birth_date=birth_date, - lo=lo, - hi=hi, - include_pratyantar=relax.r4, - varga_narayana=relax.r4, - ) if domains else [] - probes: list[dict[str, Any]] = [] - from scripts.rectification.event_probes import _evaluate_contexts, _domain_year_floor - for domain in domains: - if domain not in DOMAIN_CATALOG: - continue - known_years = _event_years(events, domain) - asked_years = asked_years_for_domain(asked_probe_keys, domain) - event_blocked = set(known_years) if relax.r1 else _existence_blocked_years(domain, known_years) - if relax.r2 and domain in EXTRA_FAMILIES: - blocked_years = event_blocked - elif relax.r1: - blocked_years = event_blocked | asked_years - else: - blocked_years = _existence_blocked_years(domain, known_years | asked_years) - domain_lo = _domain_year_floor(birth_year, domain, lo) - eligible = [ - item - for item in boundary_dates - if domain_lo <= item.year <= hi - and item.year not in blocked_years - and f"{domain}:{item.year}" not in holdout_keys - ] - families: tuple[tuple[str, str] | None, ...] - if relax.r2 and domain in EXTRA_FAMILIES: - families = EXTRA_FAMILIES[domain] - else: - families = (None,) - found: list[dict[str, Any]] = [] - for family in families: - if relax.r2 and family is not None: - asked_for_family = { - year - for year in asked_years - if any( - key.startswith(f"{domain}.{year}.") and family_slug(family[0]) in key - for key in asked_probe_keys - ) - } - family_blocked = set(blocked_years) | asked_for_family - family_eligible = [ - item for item in boundary_dates - if domain_lo <= item.year <= hi - and item.year not in family_blocked - and f"{domain}:{item.year}" not in holdout_keys - ] - else: - family_eligible = eligible - evaluated = 0 - sample_size = min(MAX_BOUNDARY_CANDIDATES_PER_DOMAIN, len(family_eligible)) - ctx = catalog_family(domain, family[0], family[1]) if family else nullcontext() - with ctx: - for at in _evaluation_order(family_eligible, MAX_BOUNDARY_CANDIDATES_PER_DOMAIN): - if evaluated >= sample_size and found: - break - row = _evaluate_contexts( - reps, - birth_date=birth_date, - domain=domain, - year=at.year, - month=at.month, - source="dasha_boundary", - clusters=clusters, - set_version=set_version, - ) - evaluated += 1 - if row is None or distinguish_contract_errors(row): - continue - if not isinstance(row.get("year"), int) or int(row["year"]) <= 0: - continue - if family is not None: - row = annotate_family(row, kind=family[0], family=family[1]) - found.append(row) - if evaluated > sample_size: - break - kept = ( - best_probe_per_year_family(found)[:max_per_domain] - if relax.r2 - else _best_probe_per_year(found)[:max_per_domain] - ) - if len(kept) < max_per_domain: - activation = _try_activation_probe( - reps=reps, - birth_date=birth_date, - birth_year=birth_year, - domain=domain, - now=today, - blocked_years=blocked_years | asked_years, - holdout_keys=set(holdout_keys), - clusters=clusters, - set_version=set_version, - ) - if activation is not None: - activation_key = ( - str(activation["domain"]), - int(activation["year"]), - int(activation.get("month") or 0), - str(activation["source"]), - ) - existing = { - (str(row["domain"]), int(row["year"]), int(row.get("month") or 0), str(row["source"])) - for row in kept - } - if activation_key not in existing: - kept.append(activation) - probes.extend(kept) - probes.extend(_quality_distinguish_probes( - events, - clusters, - set_version=set_version, - holdout_ids=set(holdout_event_ids(events)), - holdout_keys=set(holdout_keys), - )) - _annotate_nearby_ledger(probes, events) - probes.sort(key=_probe_sort_key) - return partition_probes(probes, max_probes=max_probes, include_family=relax.r2) - - -def outcome_groups(probe: dict[str, Any]) -> tuple[set[str], set[str]]: - yes: set[str] = set() - no: set[str] = set() - for row in probe.get("expected_outcomes") or []: - if not isinstance(row, dict): - continue - answer = str(row.get("answer_class") or "") - supports = {str(item)[:5] for item in (row.get("supports") or []) if str(item)} - if answer in {"yes", "weak_yes"}: - yes |= supports - elif answer == "no": - no |= supports - return yes, no - - -def inherit_direction(minute: str, yes: set[str], no: set[str]) -> str: - point = _clock(minute) - known = sorted(yes | no, key=_clock) - left = next((item for item in reversed(known) if _clock(item) < point), None) - right = next((item for item in known if _clock(item) > point), None) - if not left or not right: - return "neutral" - yes_times = [_clock(item) for item in yes] - no_times = [_clock(item) for item in no] - in_yes = left in yes and right in yes and yes_times and min(yes_times) <= point <= max(yes_times) - in_no = left in no and right in no and no_times and min(no_times) <= point <= max(no_times) - if in_yes == in_no: - return "neutral" - return "support" if in_yes else "conflict" - - -def true_side(probe: dict[str, Any], true_time: str) -> str: - yes, no = outcome_groups(probe) - if true_time in yes: - return "yes" - if true_time in no: - return "no" - direction = inherit_direction(true_time, yes, no) - if direction == "support": - return "yes" - if direction == "conflict": - return "no" - return "unknown" - - -def separates_true( - probe: dict[str, Any], - true_time: str, - remaining: Sequence[str], - clusters: Sequence[dict[str, Any]], -) -> bool: - target = displayed_true(true_time, remaining, clusters) or true_time - side = true_side(probe, target) - if side == "unknown": - side = true_side(probe, true_time) - if side == "unknown": - return False - yes, no = outcome_groups(probe) - remaining_set = {str(item)[:5] for item in remaining} - yes &= remaining_set - no &= remaining_set - if not yes or not no: - return False - if side == "yes": - return target in yes or inherit_direction(target, yes, no) == "support" - return target in no or inherit_direction(target, yes, no) == "conflict" - - -def split_tuple(probe: dict[str, Any], remaining: Sequence[str]) -> tuple[str, ...]: - yes, no = outcome_groups(probe) - remaining_set = {str(item)[:5] for item in remaining} - yes_kept = tuple(sorted(yes & remaining_set)) - no_kept = tuple(sorted(no & remaining_set)) - return yes_kept + ("|",) + no_kept - - -def apply_answer( - scores: dict[str, float], - conflicts: dict[str, int], - eliminated: set[str], - probe: dict[str, Any], - answer: str, - candidate_times: Sequence[str], -) -> tuple[dict[str, float], dict[str, int], set[str]]: - yes, no = outcome_groups(probe) - next_scores = dict(scores) - next_conflicts = dict(conflicts) - next_eliminated = set(eliminated) - if answer not in {"yes", "weak_yes", "no"}: - return next_scores, next_conflicts, next_eliminated - for time in candidate_times: - if time in next_eliminated: - continue - if time in yes: - raw = "support" - elif time in no: - raw = "conflict" - else: - raw = inherit_direction(time, yes, no) - if answer == "no": - raw = {"support": "conflict", "conflict": "support", "neutral": "neutral"}[raw] - if answer == "weak_yes": - direction = {"support": "weak_support", "conflict": "weak_conflict", "neutral": "neutral"}[raw] - else: - direction = raw - if direction == "conflict": - next_conflicts[time] = next_conflicts.get(time, 0) + 1 - next_scores[time] = next_scores.get(time, 0.0) + SCORE_DELTA[direction] - newly = [ - time for time in candidate_times - if time not in next_eliminated and next_conflicts.get(time, 0) >= STRONG_CONFLICT_ELIMINATION_COUNT - ] - still_active = [ - time for time in candidate_times - if time not in next_eliminated and time not in newly - ] - survivor = None - if not still_active and newly: - survivor = sorted(newly, key=lambda item: (-next_scores.get(item, 0.0), item))[0] - for time in newly: - if time != survivor: - next_eliminated.add(time) - return next_scores, next_conflicts, next_eliminated - - -def optimal_answer(probe: dict[str, Any], true_time: str) -> str | None: - side = true_side(probe, true_time) - if side in {"yes", "no"}: - return side - return None - - -def range_width(times: Sequence[str]) -> int | None: - clocks = sorted(_clock(str(item)[:5]) for item in times if str(item)[:5]) - if not clocks: - return None - return clocks[-1] - clocks[0] + 1 - - -def displayed_true(true_time: str, remaining: Sequence[str], clusters: Sequence[dict[str, Any]]) -> str | None: - remaining_set = {str(item)[:5] for item in remaining} - if true_time in remaining_set: - return true_time - cluster = cluster_of(true_time, clusters) - if cluster is None: - return None - cluster_times = {str(item)[:5] for item in cluster.get("times") or []} - for time in remaining: - if str(time)[:5] in cluster_times: - return str(time)[:5] - return None - - -def top1_hit( - scores: dict[str, float], - active: Sequence[str], - true_time: str, - clusters: Sequence[dict[str, Any]], -) -> bool: - target = displayed_true(true_time, active, clusters) - if target is None: - return False - ranked = sorted(active, key=lambda item: (-scores.get(item, 0.0), item)) - if not ranked: - return False - best = scores.get(ranked[0], 0.0) - leaders = [item for item in active if scores.get(item, 0.0) == best] - return leaders == [target] - - -def cluster_of(true_time: str, clusters: Sequence[dict[str, Any]]) -> dict[str, Any] | None: - for cluster in clusters: - times = [str(item)[:5] for item in cluster.get("times") or []] - if true_time in times: - return cluster - return None - - -def remaining_after_six( - *, - all_times: Sequence[str], - scores: dict[str, float], - eliminated: set[str], - clusters: Sequence[dict[str, Any]], - true_time: str, -) -> tuple[list[str], str, bool]: - active = [time for time in all_times if time not in eliminated] - true_alive = true_time in active - reps: list[str] = [] - for cluster in clusters: - members = [str(item)[:5] for item in cluster.get("times") or [] if str(item)[:5] in active] - if not members: - continue - rep = str(cluster.get("representative_time") or "")[:5] - if not rep or rep not in members: - rep = max(members, key=lambda item: (scores.get(item, 0.0), item)) - reps.append(rep) - if len(reps) <= REMAINING_CAP: - return reps, "natural", true_alive - picked: list[str] = [] - true_cluster = cluster_of(true_time, clusters) - if true_alive and true_cluster is not None: - true_rep = str(true_cluster.get("representative_time") or "")[:5] - members = [str(item)[:5] for item in true_cluster.get("times") or [] if str(item)[:5] in active] - if true_rep not in members and members: - true_rep = max(members, key=lambda item: (scores.get(item, 0.0), item)) - if true_rep in reps: - picked.append(true_rep) - ranked = sorted(reps, key=lambda item: (-scores.get(item, 0.0), item)) - for time in ranked: - if time not in picked: - picked.append(time) - if len(picked) >= REMAINING_CAP: - break - return picked, "capped_to_5", true_alive - - -def asked_key(probe: dict[str, Any]) -> str: - return str(probe.get("semantic_key") or "") - - -def compact_probe( - probe: dict[str, Any], - true_time: str, - remaining: Sequence[str], - clusters: Sequence[dict[str, Any]], -) -> dict[str, Any]: - yes, no = outcome_groups(probe) - side = true_side(probe, true_time) - return { - "semantic_key": asked_key(probe), - "domain": probe.get("domain"), - "year": probe.get("year"), - "month": probe.get("month"), - "source": probe.get("source"), - "event_family": probe.get("event_family"), - "information_gain": probe.get("information_gain"), - "true_side": side, - "separates": separates_true(probe, true_time, remaining, clusters), - "yes_count": len(yes), - "no_count": len(no), - } - - -def measure_variant( - *, - probes: Sequence[dict[str, Any]], - asked_keys: set[str], - remaining: Sequence[str], - true_time: str, - base_scores: dict[str, float], - base_conflicts: dict[str, int], - base_eliminated: set[str], - all_times: Sequence[str], - clusters: Sequence[dict[str, Any]], -) -> dict[str, Any]: - new_probes = [ - probe for probe in probes - if asked_key(probe) and asked_key(probe) not in asked_keys - ] - discriminative = [ - probe for probe in new_probes - if separates_true(probe, true_time, remaining, clusters) - ] - unique_splits = { - split_tuple(probe, remaining) - for probe in discriminative - } - scores = dict(base_scores) - conflicts = dict(base_conflicts) - eliminated = set(base_eliminated) - applied = 0 - skipped = 0 - for probe in new_probes: - answer = optimal_answer(probe, true_time) - if answer is None: - skipped += 1 - continue - scores, conflicts, eliminated = apply_answer( - scores, conflicts, eliminated, probe, answer, all_times, - ) - applied += 1 - active = [time for time in remaining if time not in eliminated] - if not active: - active = [time for time in all_times if time not in eliminated] - return { - "new_probe_count": len(new_probes), - "discriminative_count": len(discriminative), - "unique_split_count": len(unique_splits), - "applied_optimal": applied, - "skipped_unknown_side": skipped, - "top1_hit": top1_hit(scores, active, true_time, clusters), - "range_width": range_width(active), - "active_count": len(active), - "true_alive": true_time not in eliminated, - "probes": [compact_probe(probe, true_time, remaining, clusters) for probe in new_probes], - } - - -def score_case(case: dict[str, Any]) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - request = request_from_case(case) - scoring = scoreable_request(request) - built = build_event_contribution_matrix(scoring) - rows = score_from_matrix(scoring, built) - all_times = [str(row["time"])[:5] for row in rows] - prior = {str(row["time"])[:5]: float(row["score"] or 0) for row in rows} - contexts = _static_contexts(built) - clusters = cluster_contexts_by_signature(contexts) - scan = _scan_for(built) - initial = discriminating_event_probes( - {**request, "refresh_probes": False}, - built, - scan=scan, - candidate_times=all_times, - representative_time=true_time, - today=TODAY, - ) - asked = initial[:ASK_COUNT] - scores = dict(prior) - conflicts = {time: 0 for time in all_times} - eliminated: set[str] = set() - for probe in asked: - answer = optimal_answer(probe, true_time) - if answer is None: - continue - scores, conflicts, eliminated = apply_answer( - scores, conflicts, eliminated, probe, answer, all_times, - ) - remaining, remaining_mode, true_alive = remaining_after_six( - all_times=all_times, - scores=scores, - eliminated=eliminated, - clusters=clusters, - true_time=true_time, - ) - asked_keys = {asked_key(probe) for probe in asked if asked_key(probe)} - refresh_request = { - **request, - "refresh_probes": True, - "asked_probe_keys": sorted(asked_keys), - "column_times": remaining, - } - baseline_after_six = { - "asked_count": len(asked), - "initial_probe_count": len(initial), - "remaining_count": len(remaining), - "remaining_mode": remaining_mode, - "true_alive": true_alive, - "top1_hit": top1_hit(scores, remaining, true_time, clusters), - "range_width": range_width(remaining), - "asked_keys": sorted(asked_keys), - "remaining_times": remaining, - } - variants: dict[str, Any] = {} - for relax in all_relaxations(): - if relax.name == "baseline": - probes = discriminating_event_probes( - refresh_request, - built, - scan=scan, - candidate_times=remaining, - representative_time=remaining[0] if remaining else true_time, - today=TODAY, - ) - else: - probes = generate_refresh_probes( - refresh_request, - built, - remaining_times=remaining, - relax=relax, - today=TODAY, - ) - variants[relax.name] = measure_variant( - probes=probes, - asked_keys=asked_keys, - remaining=remaining, - true_time=true_time, - base_scores=scores, - base_conflicts=conflicts, - base_eliminated=eliminated, - all_times=all_times, - clusters=clusters, - ) - variants[relax.name]["refresh_probe_count"] = len(probes) - variants[relax.name]["refresh_keys"] = [asked_key(item) for item in probes] - return { - "case_id": case["case_id"], - "true_time": true_time, - "radius": int(case.get("candidate_radius_minutes") or 10), - "cluster_count": len(clusters), - "after_six": baseline_after_six, - "variants": variants, - } - - -def summarize(cases: list[dict[str, Any]]) -> dict[str, Any]: - eligible = [ - row for row in cases - if not row.get("error") - and int((row.get("after_six") or {}).get("remaining_count") or 0) >= 2 - and int((row.get("after_six") or {}).get("asked_count") or 0) >= ASK_COUNT - ] - table: dict[str, Any] = {} - names = [relax.name for relax in all_relaxations()] - after_six_hit = [ - bool(row["after_six"]["top1_hit"]) for row in eligible - ] - after_six_width = [ - int(row["after_six"]["range_width"]) - for row in eligible - if row["after_six"].get("range_width") is not None - ] - for name in names: - new_counts = [int(row["variants"][name]["new_probe_count"]) for row in eligible] - disc = [int(row["variants"][name]["discriminative_count"]) for row in eligible] - unique = [int(row["variants"][name]["unique_split_count"]) for row in eligible] - hits = [bool(row["variants"][name]["top1_hit"]) for row in eligible] - widths = [ - int(row["variants"][name]["range_width"]) - for row in eligible - if row["variants"][name].get("range_width") is not None - ] - hit_rate = round(sum(hits) / len(hits), 4) if hits else None - base_hit = round(sum(after_six_hit) / len(after_six_hit), 4) if after_six_hit else None - table[name] = { - "n": len(eligible), - "mean_new_probes": round(statistics.mean(new_counts), 3) if new_counts else 0.0, - "mean_discriminative": round(statistics.mean(disc), 3) if disc else 0.0, - "mean_unique_splits": round(statistics.mean(unique), 3) if unique else 0.0, - "cases_with_any_discriminative": sum(item > 0 for item in disc), - "top1_after_six": base_hit, - "top1_after_replay": hit_rate, - "top1_delta": None if hit_rate is None or base_hit is None else round(hit_rate - base_hit, 4), - "mean_width_after_six": round(statistics.mean(after_six_width), 2) if after_six_width else None, - "mean_width_after_replay": round(statistics.mean(widths), 2) if widths else None, - } - baseline = table.get("baseline") or {} - for name, row in table.items(): - if name == "baseline": - row["extra_new_vs_baseline"] = 0.0 - row["extra_unique_vs_baseline"] = 0.0 - continue - row["extra_new_vs_baseline"] = round( - float(row["mean_new_probes"]) - float(baseline.get("mean_new_probes") or 0), 3, - ) - row["extra_unique_vs_baseline"] = round( - float(row["mean_unique_splits"]) - float(baseline.get("mean_unique_splits") or 0), 3, - ) - return { - "case_count": len(cases), - "eligible_count": len(eligible), - "errors": [row["case_id"] for row in cases if row.get("error")], - "variants": table, - } - - -def decide(summary: dict[str, Any]) -> dict[str, Any]: - eligible = int(summary.get("eligible_count") or 0) - if eligible < 10: - return { - "verdict": "uncertain", - "reason": f"only {eligible} cases asked 6 dated probes and still had a remaining set", - "implement": False, - } - winners: list[str] = [] - for name, row in summary["variants"].items(): - if name == "baseline": - continue - extra = float(row.get("extra_unique_vs_baseline") or 0) - delta = row.get("top1_delta") - if extra >= 1.0 and delta is not None and delta >= 0: - winners.append(name) - if winners: - return { - "verdict": "benefit", - "reason": "at least one relaxation added >=1 unique true-cluster split vs production refresh without dropping top-1", - "implement": True, - "variants": winners, - } - return { - "verdict": "no_benefit", - "reason": "no relaxation added >=1 unique true-cluster split vs production refresh with non-falling top-1", - "implement": False, - } - - -def render_markdown(report: dict[str, Any]) -> str: - summary = report["summary"] - decision = report["decision"] - lines = [ - "# 六题之后刷新出题供给测量(2026-09-13)", - "", - "- 任务:`docs/tasks/TASK-rectification-probe-supply-research-20260913.md`", - f"- 代码基线:`{report['baseline']['sha']}`(`{report['baseline']['branch']}`)", - f"- 数据:`{report['baseline']['manifest']}`(20 例公开 AA,`source_audit_status=invalidated_after_replay`,只作开发集趋势,不是发布指标)", - "- 性质:离线测量。生产 `event_probes.py` 默认行为未改。", - "", - "## 方法", - "", - "1. 每例用 holdout 公开事件对声明分钟 ±`candidate_radius_minutes` 打分,生成生产路径带年月题。", - "2. 按信息增益取前 6 道,用对真实分钟最优的 yes/no 回放(真实分钟落在 yes 组答 yes,落在 no 组答 no)。", - "3. 剩余活动簇代表若多于 5 个,保留真实簇并按后验截到 5 个,模拟「六题后剩余 ≤5 候选」。", - "4. 对该剩余集按 `refresh_probes=true` 再生成题:baseline 走生产函数;R1–R4 只在本脚本里临时改封锁年、事件家族、`MIN_BOUNDARY_DAYS`、Vimshottari 第三级与 D9/D10 上升 Narayana。", - "5. 新题按最优答案继续回放,比较头名命中与剩余范围宽度。", - "", - "有分辨力:真实分钟(或其簇代表)能落到 yes 或 no,且另一组里还有剩余候选。相同 yes/no 划分只计一次 unique split。收益门槛是相对生产刷新 **多出** ≥1 道独立划分,且头名不降。", - "", - "## 放宽项", - "", - "| 代号 | 改法 |", - "| --- | --- |", - "| R1 | 刷新时只封已问/已知的确切年,去掉 ±1 年封锁 |", - "| R2 | 事业按入职/升职/离职、感情按结婚/分手,同域同年可再出一道 |", - "| R3 | 刷新阶段 `MIN_BOUNDARY_DAYS` 45→30 |", - "| R4 | 边界加 Vimshottari pratyantar,以及 D9/D10 上升的 Narayana |", - "", - f"问满 6 道且剩余 ≥2 因而进入刷新测量的例子:{summary['eligible_count']}/{summary['case_count']}。", - "", - "## 总表", - "", - "| 方案 | 平均新增题 | 相对生产多出题 | 平均有分辨力 | 平均独立划分 | 相对生产多出划分 | 有分辨力的例子 | 六题后头名 | 回放后头名 | 头名差 | 六题后宽度 | 回放后宽度 |", - "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", - ] - for name, row in summary["variants"].items(): - lines.append( - "| {name} | {mean_new_probes} | {extra_new_vs_baseline} | {mean_discriminative} | {mean_unique_splits} | {extra_unique_vs_baseline} | {cases_with_any_discriminative}/{n} | {top1_after_six} | {top1_after_replay} | {top1_delta} | {mean_width_after_six} | {mean_width_after_replay} |".format( - name=name, - **{key: row[key] for key in ( - "mean_new_probes", "extra_new_vs_baseline", "mean_discriminative", - "mean_unique_splits", "extra_unique_vs_baseline", - "cases_with_any_discriminative", "n", "top1_after_six", - "top1_after_replay", "top1_delta", "mean_width_after_six", - "mean_width_after_replay", - )}, - ) - ) - verdict_text = { - "benefit": "有收益,可另立实现单。", - "no_benefit": "无收益,关闭方案 B。", - "uncertain": "不确定,还缺足够进入「六题后剩余 ≤5」的例子。", - }[decision["verdict"]] - lines.extend([ - "", - "## 结论", - "", - f"**{verdict_text}**", - "", - f"- 判定:`{decision['verdict']}`", - f"- 原因:{decision['reason']}", - f"- 立实现单:{'是' if decision['implement'] else '否'}", - ]) - if decision.get("variants"): - lines.append(f"- 达到门槛的组合:{', '.join(decision['variants'])}") - if any(name in {"R3", "R4"} or "R3" in name.split("+") or "R4" in name.split("+") for name in decision["variants"]): - r3 = summary["variants"].get("R3") or {} - r4 = summary["variants"].get("R4") or {} - r34 = summary["variants"].get("R3+R4") or {} - r1 = summary["variants"].get("R1") or {} - r2 = summary["variants"].get("R2") or {} - lines.extend([ - "", - "## 建议实现范围", - "", - "立实现单只做 **刷新阶段 R3 + R4**:", - "", - f"- R3:刷新时 `MIN_BOUNDARY_DAYS` 45→30。单独达到门槛(相对生产 +{r3.get('extra_unique_vs_baseline')} 独立划分、+{r3.get('extra_new_vs_baseline')} 题),改动最小。", - f"- R4:刷新边界加 Vimshottari pratyantar 与 D9/D10 上升 Narayana。单独 +{r4.get('extra_unique_vs_baseline')} 独立划分、+{r4.get('extra_new_vs_baseline')} 题。`_vim_start_dates` 已有 `include_pratyantar`,生产默认仍为 false。", - f"- 合做 R3+R4:+{r34.get('extra_unique_vs_baseline')} 独立划分、+{r34.get('extra_new_vs_baseline')} 题;头名 {r34.get('top1_after_replay')} 不降,宽度 {r34.get('mean_width_after_six')}→{r34.get('mean_width_after_replay')}。", - f"- **不做 R1**:只多 {r1.get('extra_unique_vs_baseline')} 划分。", - f"- **不做 R2**:多出的题大多是同一 yes/no 划分的家族复题;单独只多 {r2.get('extra_unique_vs_baseline')} 划分。", - "- 即使 R3+R4,仍有例子问满 6 道后刷新还是 0 题。定向补事(方案 A)仍要保留。", - ]) - lines.extend([ - "", - "## 分例", - "", - "| 例子 | 问了几道 | 剩余 | 截断 | 真实还在 | baseline 新题 | 最好组合 | 该组合新题 | 该组合分辨力 |", - "| --- | ---: | ---: | --- | --- | ---: | --- | ---: | ---: |", - ]) - for row in report["cases"]: - if row.get("error"): - lines.append(f"| {row['case_id']} | error | | | | | | | {row.get('error')} |") - continue - after = row["after_six"] - best_name = "baseline" - best = row["variants"]["baseline"] - for name, variant in row["variants"].items(): - if int(variant["discriminative_count"]) > int(best["discriminative_count"]): - best_name = name - best = variant - lines.append( - f"| {row['case_id']} | {after['asked_count']} | {after['remaining_count']} | {after['remaining_mode']} | {after['true_alive']} | {row['variants']['baseline']['new_probe_count']} | {best_name} | {best['new_probe_count']} | {best['discriminative_count']} |" - ) - lines.extend([ - "", - "## 边界", - "", - "- 最优答案是相对已公布 Rodden AA 分钟的上界,不是真实用户会怎么答。", - "- holdout 已被 `invalidated_after_replay`,不得写成发布准确率。", - "- R2 若只换事件家族文案、分盘激活规则不变,yes/no 划分可能与默认家族重复。", - "- 未把研究脚本接到生产路径。", - "", - ]) - return "\n".join(lines) + "\n" - - -def git_sha() -> str: - head = ROOT / ".git" - try: - import subprocess - return subprocess.check_output( - ["git", "rev-parse", "HEAD"], - cwd=ROOT, - text=True, - ).strip() - except Exception: - return str(head) - - -def run(limit: int | None = None, case_id: str | None = None) -> dict[str, Any]: - payload = json.loads(HOLDOUT_MANIFEST.read_text(encoding="utf-8")) - cases = [item for item in payload.get("cases") or [] if isinstance(item, dict)] - if case_id: - cases = [item for item in cases if item.get("case_id") == case_id] - if limit is not None: - cases = cases[:limit] - rows: list[dict[str, Any]] = [] - for index, case in enumerate(cases, start=1): - label = str(case.get("case_id") or index) - print(f"[{index}/{len(cases)}] {label}", flush=True) - try: - rows.append(score_case(case)) - except Exception as exc: - rows.append({ - "case_id": str(case.get("case_id") or ""), - "error": f"{type(exc).__name__}: {exc}", - "traceback": traceback.format_exc(), - }) - summary = summarize(rows) - decision = decide(summary) - return { - "scope": "probe_supply_after_six", - "today": TODAY.isoformat(), - "baseline": { - "sha": git_sha(), - "branch": "codex/rectification-probe-supply-research-20260913", - "manifest": str(HOLDOUT_MANIFEST.relative_to(ROOT)), - "benchmark_id": payload.get("benchmark_id"), - "min_boundary_days_default": MIN_BOUNDARY_DAYS, - "existence_nearby_years": dict(EXISTENCE_NEARBY_YEARS), - }, - "summary": summary, - "decision": decision, - "cases": rows, - } - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--from-json", type=Path, default=None) - parser.add_argument("--limit", type=int, default=None) - parser.add_argument("--case-id", type=str, default=None) - parser.add_argument("--json-out", type=Path, default=ROOT / "docs/research/probe_supply_after_six_2026_09_13.json") - parser.add_argument("--md-out", type=Path, default=ROOT / "docs/research/probe_supply_after_six_2026_09_13.md") - args = parser.parse_args() - if args.from_json: - previous = json.loads(args.from_json.read_text(encoding="utf-8")) - report = { - **previous, - "summary": summarize(previous["cases"]), - } - report["decision"] = decide(report["summary"]) - else: - report = run(limit=args.limit, case_id=args.case_id) - args.json_out.parent.mkdir(parents=True, exist_ok=True) - args.json_out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - args.md_out.write_text(render_markdown(report), encoding="utf-8") - print(json.dumps({ - "decision": report["decision"], - "eligible_count": report["summary"]["eligible_count"], - "errors": report["summary"]["errors"], - "json_out": str(args.json_out), - "md_out": str(args.md_out), - }, ensure_ascii=False, indent=2)) - return 0 if not report["summary"]["errors"] else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/quality_wording_ab.py b/scripts/research/quality_wording_ab.py deleted file mode 100644 index 966a88967..000000000 --- a/scripts/research/quality_wording_ab.py +++ /dev/null @@ -1,114 +0,0 @@ -#!/usr/bin/env python3 -"""A/B dump for BUG-1088 (quality-probe wording, year-precision label). - -Dumps engine rows, public candidate decisions and every discriminating probe -for a few v4 open-holdout cases plus fictional cases that carry education -quality events. Run on the base and on the patched tree with the same -PYTHONHASHSEED and diff: only `user_meaning` / `display_date_label` text may -change. -""" -from __future__ import annotations - -import json -import sys -from pathlib import Path -from typing import Any -from uuid import NAMESPACE_URL, uuid5 - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import compute_candidate_static_contexts # noqa: E402 -from scripts.rectification.decision_policy import build_candidate_decisions # noqa: E402 -from scripts.rectification.event_probes import _discriminating_event_probe_lists # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) -from scripts.research.guided_collect_holdout_replay import TODAY, load_cases # noqa: E402 -from scripts.research.minute_resolution_sweep import scoring_request_for # noqa: E402 -from scripts.rectification.contracts import normalize_rectification_request # noqa: E402 - -#: Fictional births only (no real person). Education events carry quality kinds. -FICTIONAL = [ - ("1994-06-21", "14:50", [ - ("education", "education_start", "2011-01-01", "2011-12-31", "year"), - ("education", "education_change", "2012-09-01", "2012-09-30", "month"), - ("relocation", "relocation", "2000-01-01", "2000-12-31", "year"), - ("career", "career_entry", "2017-05-01", "2017-05-31", "month"), - ]), - ("1993-11-17", "09:20", [ - ("education", "education_interruption", "2010-01-01", "2010-12-31", "year"), - ("education", "education_start", "2011-09-03", "2011-09-03", "day"), - ("career", "career_entry", "2016-07-01", "2016-07-31", "month"), - ("relocation", "relocation", "2018-01-01", "2018-12-31", "year"), - ]), -] - - -def fictional_request(birth_date: str, time: str, events: list[tuple[str, str, str, str, str]]) -> dict[str, Any]: - hh, mm = int(time[:2]), int(time[3:]) - start = f"{(hh * 60 + mm - 15) // 60:02d}:{(hh * 60 + mm - 15) % 60:02d}" - end = f"{(hh * 60 + mm + 15) // 60:02d}:{(hh * 60 + mm + 15) % 60:02d}" - return scoreable_request(normalize_rectification_request({ - "birth_date": birth_date, "start_time": start, "end_time": end, - "lat": 39.9042, "lon": 116.4074, "tz": 8.0, - "events": [ - {"id": str(uuid5(NAMESPACE_URL, f"fictional-{birth_date}-{index}")), "domain": domain, "event_kind": kind, "date_start": lo, - "date_end": hi, "precision": precision, "summary": f"fictional {kind}"} - for index, (domain, kind, lo, hi, precision) in enumerate(events) - ], - }, today=TODAY)) - - -def dump(request: dict[str, Any]) -> dict[str, Any]: - import scripts.rectification.event_probes as event_probes - - request = {**request, "minute_step": 1} - captured: list[dict[str, Any]] = [] - original = event_probes._quality_distinguish_probes - - def capture(*args: Any, **kwargs: Any) -> list[dict[str, Any]]: - rows = original(*args, **kwargs) - captured.extend(rows) - return rows - - # Quality probes are ranked after the boundary probes and often fall past MAX_PROBES; - # capture the builder output so the A/B sees them. Restored below. - event_probes._quality_distinguish_probes = capture - contexts = compute_candidate_static_contexts(request) - built = build_event_contribution_matrix(request, static_contexts=contexts) - rows = score_from_matrix(request, built) - times = [str(row["time"])[:5] for row in rows] - probes, dropped = _discriminating_event_probe_lists( - {**request, "refresh_probes": False, "asked_probe_keys": []}, built, - scan=window_scan(built), candidate_times=times, representative_time=times[len(times) // 2], - today=TODAY, - ) - event_probes._quality_distinguish_probes = original - assert event_probes._quality_distinguish_probes is original - decisions = build_candidate_decisions(rows, result_id="ab", static_contexts=contexts) - return { - "rows": [{"time": str(row["time"])[:5], "score": str(row.get("score"))} for row in rows], - "decisions": decisions, - "probes": probes, - "dropped": dropped, - "quality_built": captured, - } - - -def main() -> int: - out: dict[str, Any] = {} - for case in load_cases()[:4]: - out[str(case["case_id"])] = dump(scoring_request_for(case, 10)) - for birth_date, time, events in FICTIONAL: - out[f"fictional-{birth_date}"] = dump(fictional_request(birth_date, time, events)) - json.dump(out, sys.stdout, ensure_ascii=False, indent=1, sort_keys=True, default=str) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/rect_scoring_perf_20261013.py b/scripts/research/rect_scoring_perf_20261013.py deleted file mode 100644 index 86e6217a8..000000000 --- a/scripts/research/rect_scoring_perf_20261013.py +++ /dev/null @@ -1,257 +0,0 @@ -#!/usr/bin/env python3 -"""Bench and canonical dump for the 2026-10-13 rectification scoring speedup. - -Read-only aside from the dump files the caller asks for. Cross-process dumps -must be launched with PYTHONHASHSEED=0. The baseline tree has no -include_internal parameter; that call falls back to the old signature. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import statistics -import sys -import time -from datetime import date -from pathlib import Path -from typing import Any, Callable - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.rectification.api_service import block_scan, diagnostics, score_candidates -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification import event_probes -from scripts.rectification import scoring_service -from scripts import active_rectification_event_engine as event_engine - -FROZEN_TODAY = date(2026, 9, 16) -EVENT_SPECS = ( - ("education", "education_start", "2008-01-01", "2008-12-31", "year"), - ("career", "career_entry", "2012-06-01", "2012-06-30", "month"), - ("relocation", "relocation", "2014-03-01", "2014-03-31", "month"), - ("relationship", "relationship_commitment", "2016-10-01", "2016-10-31", "month"), - ("career", "promotion", "2018-01-01", "2018-12-31", "year"), - ("finance", "asset_change", "2019-05-01", "2019-05-31", "month"), - ("family", "family_event", "2020-08-01", "2020-08-31", "month"), - ("health", "self_health_event", "2022-01-01", "2022-12-31", "year"), -) - - -class _FrozenDate(date): - @classmethod - def today(cls) -> date: - return FROZEN_TODAY - - -def _events() -> list[dict[str, Any]]: - rows = [] - for index, (domain, kind, start, end, precision) in enumerate(EVENT_SPECS, start=1): - rows.append({ - "id": f"00000000-0000-4000-8000-{index:012d}", - "domain": domain, - "event_kind": kind, - "date_start": start, - "date_end": end, - "precision": precision, - "summary": "虚构", - }) - return rows - - -def make_request(start: str, end: str, **extra: Any) -> dict[str, Any]: - body = { - "birth_date": "1990-01-01", - "start_time": start, - "end_time": end, - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": _events(), - **extra, - } - return normalize_rectification_request(body, today=FROZEN_TODAY) - - -def _strip(value: Any, keys: set[str]) -> Any: - if isinstance(value, dict): - return {key: _strip(item, keys) for key, item in value.items() if key not in keys} - if isinstance(value, list): - return [_strip(item, keys) for item in value] - return value - - -def _canonical(value: Any) -> bytes: - return json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode("ascii") - - -def _score(request: dict[str, Any]) -> dict[str, Any]: - try: - return score_candidates(request, include_internal=True) - except TypeError: - return score_candidates(request) - - -def _call(kind: str, request: dict[str, Any], *, internal: bool = False) -> dict[str, Any]: - if kind == "score": - # Bench times the product call. Dump asks for the internal matrix so - # the baseline tree, which always returned it, stays comparable. - if internal: - return _score(request) - return score_candidates(request) - if kind == "block": - return block_scan(request) - if kind == "diagnostics": - return diagnostics(request) - raise ValueError(kind) - - -def scenarios() -> list[dict[str, Any]]: - from tests.test_rectification_engine_memoization import public_score_request - - rows = [ - {"name": "12:00-12:20", "kind": "score", "request": make_request("12:00", "12:20")}, - {"name": "11:45-12:15", "kind": "score", "request": make_request("11:45", "12:15")}, - {"name": "11:00-13:00", "kind": "score", "request": make_request("11:00", "13:00")}, - {"name": "23:20-00:40", "kind": "score", "request": make_request("23:20", "00:40")}, - {"name": "declined-relationship-career", "kind": "score", "request": make_request( - "11:30", "12:30", declined_domains=["relationship", "career"], - )}, - {"name": "refresh-probes-columns", "kind": "score", "request": make_request( - "11:30", "12:30", refresh_probes=True, column_times=["11:40", "12:10", "12:20"], - )}, - {"name": "minute-step-2", "kind": "score", "request": make_request("10:00", "13:00", minute_step=2)}, - {"name": "block-step-10", "kind": "block", "request": make_request("00:00", "23:59", minute_step=10)}, - {"name": "block-step-5", "kind": "block", "request": make_request("10:00", "14:00", minute_step=5)}, - {"name": "public-score-request", "kind": "score", "request": normalize_rectification_request( - public_score_request(), today=FROZEN_TODAY, - )}, - {"name": "diagnostics-11:00-13:00", "kind": "diagnostics", "request": make_request("11:00", "13:00")}, - ] - return rows - - -def _strip_keys(kind: str) -> set[str]: - # diagnostics no longer repeats the receipt. Drop it on both sides so the - # remaining payload is what must stay byte-identical. - if kind == "diagnostics": - return {"column_compare_ms", "candidate_decision_receipt"} - return {"column_compare_ms"} - - -class _SegmentTimer: - def __init__(self) -> None: - self.totals = { - "guided_collect_windows": 0.0, - "merge_transition_proximity": 0.0, - "get_current_narayana_dasha": 0.0, - "derive_functional_benefic_malefic": 0.0, - "build_candidate_static_context": 0.0, - } - - def wrap(self, owner: Any, name: str, key: str) -> Callable[[], None]: - original = getattr(owner, name) - - def wrapped(*args: Any, **kwargs: Any) -> Any: - started = time.perf_counter() - try: - return original(*args, **kwargs) - finally: - self.totals[key] += time.perf_counter() - started - - setattr(owner, name, wrapped) - - def restore() -> None: - setattr(owner, name, original) - - return restore - - -def _median(samples: list[float]) -> float: - return round(statistics.median(samples), 4) - - -def bench() -> dict[str, Any]: - jobs = [ - ("12:00-12:20", "score", make_request("12:00", "12:20")), - ("11:45-12:15", "score", make_request("11:45", "12:15")), - ("11:00-13:00", "score", make_request("11:00", "13:00")), - ("block-step-10", "block", make_request("00:00", "23:59", minute_step=10)), - ] - rows = [] - event_probes.date = _FrozenDate - try: - for name, kind, request in jobs: - samples = [] - segments = [] - sizes = [] - counts = [] - for _ in range(5): - timer = _SegmentTimer() - restores = [ - timer.wrap(event_probes, "guided_collect_windows", "guided_collect_windows"), - timer.wrap(scoring_service, "merge_transition_proximity", "merge_transition_proximity"), - timer.wrap(event_engine.narayana_dasha, "get_current_narayana_dasha", "get_current_narayana_dasha"), - timer.wrap(event_engine.functional_benefics, "derive_functional_benefic_malefic", "derive_functional_benefic_malefic"), - timer.wrap(event_engine, "build_candidate_static_context", "build_candidate_static_context"), - ] - started = time.perf_counter() - try: - result = _call(kind, request) - finally: - for restore in restores: - restore() - elapsed = time.perf_counter() - started - samples.append(elapsed) - segments.append({key: round(value, 4) for key, value in timer.totals.items()}) - sizes.append(len(_canonical(_strip(result, _strip_keys(kind))))) - counts.append(result.get("candidate_count") or len(result.get("candidate_scores") or [])) - median_segments: dict[str, float] = {} - for key in segments[0]: - median_segments[key] = _median([item[key] for item in segments]) - rows.append({ - "window": name, - "candidate_count": counts[0], - "median_seconds": _median(samples), - "segment_median_seconds": median_segments, - "response_bytes": int(statistics.median(sizes)), - }) - finally: - event_probes.date = date - return {"runs": 5, "rows": rows} - - -def dump(out_dir: Path) -> list[dict[str, str]]: - out_dir.mkdir(parents=True, exist_ok=True) - written = [] - event_probes.date = _FrozenDate - try: - for row in scenarios(): - result = _call(row["kind"], row["request"], internal=True) - payload = _strip(result, _strip_keys(row["kind"])) - raw = _canonical(payload) - digest = hashlib.sha256(raw).hexdigest() - path = out_dir / f"{row['name'].replace(':', '')}.json" - path.write_bytes(raw) - written.append({"name": row["name"], "sha256": digest, "bytes": str(len(raw))}) - print(f"{row['name']}\t{digest}\t{len(raw)}") - finally: - event_probes.date = date - return written - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("command", choices=("bench", "dump")) - parser.add_argument("--out", type=Path, default=ROOT / "artifacts" / "rect-scoring-perf-20261013") - args = parser.parse_args() - if args.command == "bench": - print(json.dumps(bench(), ensure_ascii=True, indent=2)) - else: - dump(args.out) - - -if __name__ == "__main__": - main() diff --git a/scripts/research/reported_offset_sweep.py b/scripts/research/reported_offset_sweep.py deleted file mode 100644 index a149a3caf..000000000 --- a/scripts/research/reported_offset_sweep.py +++ /dev/null @@ -1,245 +0,0 @@ -#!/usr/bin/env python3 -"""Reported-centre sensitivity on exposed public cases, without oracle answers.""" -from __future__ import annotations - -import argparse -import json -import sys -from datetime import datetime, timedelta, timezone -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( - AYANAMSA, NODE_MODE, compute_candidate_static_contexts, -) -from scripts.minute_rectification_blind_eval import _opaque_winner, implementation_sha256 -from scripts.minute_rectification_holdout_validator import validate -from scripts.rectification.candidate_contrast import select_signature_representatives -from scripts.rectification.scoring_service import build_event_contribution_matrix, score_from_matrix -from scripts.research.cluster_width_lib import SEPARATION_LEAD, still_valid_public -from scripts.research.probe_supply_after_six import request_from_case -from scripts.research.sealed_holdout_rerun import ( - DATASET, file_sha256, historical_comparison, implementation_identity, - opaque_order, verify_frozen_record, -) - -OFFSETS = (-30, -20, -15, -10, -8, -5, -3, 0, 3, 5, 8, 10, 15, 20, 30) -RADII = (15, 30, 60) -MINUTE_STEP = 1 -# 原值: docs/research/reported_offset_upstream_sync8_2026_10_18.{freeze.json,json} -# 新值: docs/research/reported_offset_upstream_sync9b_2026_10_28.{freeze.json,json} -# 原因: sync9b(BUG-1494~1495)改了 scripts/varga.py,它在扩展身份里;报时窗口输出不变,ERR-110 另存新记录 -# 原值: docs/research/reported_offset_upstream_sync9b_2026_10_28.{freeze.json,json} -# 新值: docs/research/reported_offset_d60_mapping_2026_10_29.{freeze.json,json} -# 原因: BUG-1500 修正生产 D60 映射,scripts/varga.py 变了(在扩展身份里);900 条回放不变,ERR-110 另存新记录 -# 原值: docs/research/reported_offset_d60_mapping_2026_10_29.{freeze.json,json} -# 新值: docs/research/reported_offset_data_audit_2026_11_04.{freeze.json,json} -# 原因: 数据核对 BUG-1545(narayana_dasha.py、active_rectification_event_engine.py)与 BUG-1546(shadbala.py)改了冻结身份文件,ERR-110 另存新记录 -# 原值: docs/research/reported_offset_data_audit_2026_11_04.{freeze.json,json} -# 新值: docs/research/reported_offset_moon_paksha_2026_11_04.{freeze.json,json} -# 原因: BUG-1557 月亮 Paksha 口径(scripts/shadbala.py)改了冻结身份文件,ERR-110 另存新记录 -# 原值: docs/research/reported_offset_moon_paksha_2026_11_04.{freeze.json,json} -# 新值: docs/research/reported_offset_audit_wave2_2026_11_04.{freeze.json,json} -# 原因: 数据核对第二波合并(BUG-1560 / BUG-1561 varga.py、divisional_charts_extended.py;BUG-1566 / BUG-1567 jaimini.py;BUG-1270 / BUG-1576 shadbala.py)改了冻结身份文件,ERR-110 在合并后的代码上另存新记录;各分支自己的 audit_g / audit_h / audit_j 记录只对各自分支成立,作为中间记录原样保留 -# 原值: docs/research/reported_offset_audit_wave2_2026_11_04.{freeze.json,json} -# 新值: docs/research/reported_offset_d30_venus_2026_11_04.{freeze.json,json} -# 原因: 产品 2026-11-04 决定按出处改算法:BUG-1560 varga.py 偶数星座 D30 按 BPHS 第 6 章、BUG-1570 白羊 / 天蝎上升金星判功能凶(BPHS 34.20 / 34.35),校正身份升到 scoring-13;冻结身份文件变了且回放结果变了,ERR-110 另存新记录 -# 原值: docs/research/reported_offset_d30_venus_2026_11_04.{freeze.json,json} -# 新值: docs/research/reported_offset_astrologer_166_2026_11_04.{freeze.json,json} -# 原因: #166 占星师裁定(BUG-1581~1589,产品 2026-11-04 决定交付)改了 shadbala.py、jaimini.py、varga.py、divisional_charts_extended.py,校正身份升到 scoring-14;ERR-110 另存新记录 -# 原值: docs/research/reported_offset_astrologer_166_2026_11_04.{freeze.json,json} -# 新值: docs/research/reported_offset_astrologer_166b_2026_11_04.{freeze.json,json} -# 原因: #166 第二批(BUG-1590~1598)改了 functional_benefics.py、jaimini.py、narayana_dasha.py、shadbala.py、varga.py,校正身份升到 scoring-15;ERR-110 另存新记录 -# 原值: docs/research/reported_offset_astrologer_166b_2026_11_04.{freeze.json,json} -# 新值: docs/research/reported_offset_astrologer_166c_2026_11_05.{freeze.json,json} -# 原因: #166 占星师 2026-11-05 答复(BUG-1622~1626)只改了 shadbala.py 的标签、注释与共用的水星规则函数(数值不变),校正身份仍是 scoring-15;ERR-110 另存新记录 -# 原值: docs/research/reported_offset_astrologer_166c_2026_11_05.{freeze.json,json} -# 新值: docs/research/reported_offset_astrologer_166d_2026_11_05.{freeze.json,json} -# 原因: BUG-1622~1626 改号(另一会话已用 BUG-1613)改了 shadbala.py 与本脚本的注释,冻结身份变了,数值不变,仍 scoring-15;ERR-110 另存新记录 -FREEZE = ROOT / "docs/research/reported_offset_astrologer_166d_2026_11_05.freeze.json" -REPORT = ROOT / "docs/research/reported_offset_astrologer_166d_2026_11_05.json" -LEGACY_REPORT = ROOT / "docs/research/reported_offset_2026_09_20.json" - - -def shifted_window(case: dict[str, Any], offset: int, radius: int) -> tuple[dict[str, Any], list[datetime]]: - if radius not in (*RADII, 120): - raise ValueError("unsupported_radius") - true_at = datetime.fromisoformat(f"{case['birth']['date']}T{case['birth']['time']}:00") - reported_at = true_at + timedelta(minutes=offset) - start = reported_at - timedelta(minutes=radius) - end = reported_at + timedelta(minutes=radius) - candidates = [start + timedelta(minutes=i) for i in range(0, radius * 2 + 1, MINUTE_STEP)] - # Reuse only the established event normalization, then replace the window. - # The ranker sees neither the truth label nor the simulated offset. - request = request_from_case(case) - request.update({ - "birth_date": start.date().isoformat(), - "start_time": start.strftime("%H:%M"), - "end_time": end.strftime("%H:%M"), - "minute_step": MINUTE_STEP, - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - }) - return request, candidates - - -def score_window(request: dict[str, Any], contexts: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Use the repaired native single matrix, with candidate dates preserved. - - The historical grouped adapter is archived, not a second active scoring - path. This is a native scoring replay, still not a production Q&A replay. - """ - built = build_event_contribution_matrix(request, static_contexts=contexts) - return score_from_matrix(request, built) - - -def delivery_moments(public: list[dict[str, Any]], candidates: list[datetime]) -> list[datetime]: - """Initial delivery envelope in date-aware order; no truth-based narrowing.""" - valid = still_valid_public(public, {}, lead=SEPARATION_LEAD) - clocks = {str(value)[:5] for row in valid for value in (row.get("cluster_times") or [row["time"]])} - return [candidate for candidate in candidates if candidate.strftime("%H:%M") in clocks] - - -def reveal_metrics( - rows: list[dict[str, Any]], candidates: list[datetime], delivery: list[datetime], - truth: datetime, benchmark_id: str, case_id: str, -) -> dict[str, Any]: - ordered = opaque_order(benchmark_id, case_id, rows) - predicted_clock = _opaque_winner(benchmark_id, case_id, rows) - by_clock = {candidate.strftime("%H:%M"): candidate for candidate in candidates} - if len(by_clock) != len(candidates): - raise ValueError("ambiguous_candidate_clock") - predicted = by_clock[predicted_clock] - within = min(candidates) <= truth <= max(candidates) - in_candidates = truth in candidates - rank = next((i for i, row in enumerate(ordered, 1) if by_clock[row["time"]] == truth), None) - covered = bool(delivery) and min(delivery) <= truth <= max(delivery) - return { - "truth_in_window": within, - "truth_in_candidates": in_candidates, - "true_rank": rank, - "top_1_hit": predicted == truth, - "top_1_minute_error": abs((predicted - truth).total_seconds()) / 60, - "delivery_covers_truth": covered, - "candidate_count": len(candidates), - "delivery_width_minutes": int((max(delivery) - min(delivery)).total_seconds() / 60) + 1 if delivery else 0, - } - - -def summarize(trials: list[dict[str, Any]], radii: tuple[int, ...], offsets: tuple[int, ...]) -> list[dict[str, Any]]: - result = [] - for radius in radii: - for offset in offsets: - group = [row for row in trials if row["radius_minutes"] == radius and row["offset_minutes"] == offset] - count = len(group) - result.append({ - "radius_minutes": radius, "offset_minutes": offset, "trial_count": count, - **{key: round(sum(row[source] for row in group) / count, 4) if count else None for key, source in ( - ("truth_in_window_rate", "truth_in_window"), - ("top_1_rate", "top_1_hit"), - ("delivery_coverage_rate", "delivery_covers_truth"), - ("mean_absolute_minute_error", "top_1_minute_error"), - )}, - }) - return result - - -def freeze_record(dataset: Path = DATASET, radii: tuple[int, ...] = RADII, offsets: tuple[int, ...] = OFFSETS) -> dict[str, Any]: - manifest = json.loads(dataset.read_text(encoding="utf-8")) - legacy_hash = implementation_sha256(manifest["frozen_scoring"]["files"]) - return { - "record_version": "reported-offset-native-candidate-date-v3", - "frozen_at_utc": datetime.now(timezone.utc).isoformat(), - "ayanamsa": AYANAMSA, "node_mode": NODE_MODE, - "radii_minutes": list(radii), "offsets_minutes": list(offsets), "minute_step": MINUTE_STEP, - "dataset": dataset.relative_to(ROOT).as_posix(), "dataset_sha256": file_sha256(dataset), - "dataset_benchmark_id": manifest["benchmark_id"], - "implementation_sha256": legacy_hash, - "implementation_sha256_prefix": legacy_hash[:16], - **implementation_identity(dataset), - "scorer": "native_event_contribution_matrix_not_shadow_fact_ranker", - "delivery": "initial_signature_clusters_peak_gap_lt_8_envelope_no_answers_no_elimination", - "rank": "score_desc_then_sha256(benchmark_id:case_id:candidate_time)", - "grid": "every_minute_inclusive_not_production_two_minute_sampling", - "cross_midnight": "date_aware_candidates_distance_and_native_single_matrix", - "evaluator_sha256": file_sha256(Path(__file__)), - "replay_revision": "native_candidate_date_v3", - "supersedes": "candidate_date_grouped_v2_identity_and_path_not_assumed_numerically_wrong", - "is_blind_evaluation": False, "truth_hidden_from_ranker": True, - "official_valid_independent_blind": False, "official_blind_trial_count": 0, - "results_previously_seen": True, "must_not_use_for_tuning": True, - } - - -def run(dataset: Path = DATASET, radii: tuple[int, ...] = RADII, offsets: tuple[int, ...] = OFFSETS, - freeze_path: Path = FREEZE) -> dict[str, Any]: - frozen = json.loads(freeze_path.read_text(encoding="utf-8")) - verify_frozen_record(frozen, freeze_record(dataset, radii, offsets)) - replay_started_at = datetime.now(timezone.utc).isoformat() - manifest = json.loads(dataset.read_text(encoding="utf-8")) - validation = validate(dataset) - invalid = validation["invalid_cases"] - trials = [] - for index, case in enumerate(manifest["cases"], 1): - if case["case_id"] in invalid: - continue - # Reuse static chart calculations, not window-dependent scores or ranks. - contexts_by_moment: dict[datetime, dict[str, Any]] = {} - for radius in radii: - for offset in offsets: - request, candidates = shifted_window(case, offset, radius) - missing = [moment for moment in candidates if moment not in contexts_by_moment] - if missing: - contexts_by_moment.update(zip(missing, compute_candidate_static_contexts(request, candidates=missing), strict=True)) - contexts = [contexts_by_moment[moment] for moment in candidates] - rows = score_window(request, contexts) - public = select_signature_representatives(rows, contexts) - delivery = delivery_moments(public, candidates) - # All scores and the delivery envelope are locked before reveal. - truth = datetime.fromisoformat(f"{case['birth']['date']}T{case['birth']['time']}:00") - trials.append({ - "case_ordinal": index, "offset_minutes": offset, "radius_minutes": radius, - **reveal_metrics(rows, candidates, delivery, truth, manifest["benchmark_id"], case["case_id"]), - }) - verify_frozen_record(frozen, freeze_record(dataset, radii, offsets)) - return { - "scope": "reported_offset_sensitivity_not_product_accuracy", - "replay_started_at_utc": replay_started_at, - "replay_finished_at_utc": datetime.now(timezone.utc).isoformat(), - "specification": frozen, - "frozen_record": frozen, - "freeze_record_path": freeze_path.relative_to(ROOT).as_posix(), - "implementation_hash_matches_at_replay": True, - "dataset_hash_matches_at_replay": True, - "historical_comparison": historical_comparison(LEGACY_REPORT, trials, ("case_ordinal", "radius_minutes", "offset_minutes")), - "excluded_cases": invalid, "case_count": validation["valid_public_aa_cases"], - "trial_count": len(trials), "trials": trials, - "summary": summarize(trials, radii, offsets), - "widening_geometry": { - "scored_radii": list(radii), - "radius_120_scored": 120 in radii, - "truth_in_window_condition": "abs(reported_offset_minutes) <= radius_minutes", - "radius_15_first_integer_minute_outside": 16, - "all_tested_offsets_within_radius_30_60_120": max(map(abs, offsets)) <= 30, - "boundary": "Geometry rescues candidate inclusion only, not ranking or delivery coverage; no population frequency without a reported-offset distribution.", - }, - } - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--json", action="store_true") - parser.add_argument("--freeze", action="store_true", help="Exclusively create the record before replay") - parser.add_argument("--freeze-path", type=Path, default=FREEZE) - args = parser.parse_args() - if args.freeze: - with args.freeze_path.open("x", encoding="utf-8", newline="\n") as handle: - json.dump(freeze_record(), handle, ensure_ascii=False, indent=2) - handle.write("\n") - print(args.freeze_path.relative_to(ROOT).as_posix()) - else: - print(json.dumps(run(freeze_path=args.freeze_path), ensure_ascii=False, indent=2)) diff --git a/scripts/research/representative_pairs_probe.py b/scripts/research/representative_pairs_probe.py deleted file mode 100644 index 66b9a685e..000000000 --- a/scripts/research/representative_pairs_probe.py +++ /dev/null @@ -1,474 +0,0 @@ -#!/usr/bin/env python3 -"""R3c (2026-09-26): does `_representative_pairs` explain "no dated probes"? - -Offline only. Hypothesis under test (brief 2026-09-26): after the window -narrows, the dated (dasha-boundary) probe pool is empty because -`event_probes._representative_pairs` only pairs adjacent cluster -representatives plus first/last, and adjacent representatives are too close -for their boundaries to clear the 45 / 30 day gate. - -For every v4 case and radius, at the initial stage (all candidates) and the -refresh stage (after the six-question replay, same as the 09-14 research): - -* representative count and minute gaps; -* for each pair (production pairs vs. all pairs): Vimshottari boundary shift, - whether it clears the gate, whether `_boundary_windows`' positional zip is - misaligned; -* boundary dates from `_union_boundary_dates` and probes from the production - generator (before the public cap), with production pairs vs. a research - patch that returns all pairs, and vs. a research patch of - `_boundary_windows` that applies the documented gap to every pair (no - 1-January exemption, off-by-k zip re-aligned). Patches are applied to the - module attribute for the duration of one call and restored immediately. - -Public AA open set (v4). Not a blind test. - -Run: - python3 scripts/research/representative_pairs_probe.py -""" - -from __future__ import annotations - -import argparse -import json -import statistics -import sys -import traceback -from contextlib import contextmanager -from pathlib import Path -from typing import Any, Iterator, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - NODE_MODE, - compute_candidate_static_contexts, -) -import scripts.rectification.event_probes as ep # noqa: E402 -from scripts.rectification.candidate_contrast import cluster_contexts_by_signature # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.research.cluster_width_lib import raw_signature_clusters # noqa: E402 -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.offline_research_20260926_lib import all_pairs, distribution, zip_misaligned # noqa: E402 -from scripts.research.precision_gate_lib import finest_precision # noqa: E402 -from scripts.research.precision_gate_sweep import ( # noqa: E402 - TODAY, - evaluate_delivery, - generate_probes, - score_bundle, -) -from scripts.research.probe_supply_after_six import asked_key, separates_true # noqa: E402 - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -REPORT_JSON = ROOT / "docs" / "research" / "representative_pairs_probe_2026_09_26.json" -RADII = (10, 30, 60) -PRODUCTION_PAIRS = ep._representative_pairs - - -def clock(context: dict[str, Any]) -> int: - return ep._clock(str(ep._context_time(context))) - - -def research_all_pairs(reps: Sequence[dict[str, Any]]) -> list[tuple[dict[str, Any], dict[str, Any]]]: - usable = [item for item in reps if ep._scoreable(item) and ep._context_time(item)] - return all_pairs(usable, clock) - - -PRODUCTION_WINDOWS = ep._boundary_windows - - -def strict_boundary_windows(left: Sequence[Any], right: Sequence[Any], *, min_days: int | None = None) -> list[Any]: - """Research-only reading of the gate as documented: the minimum gap applies - to every pair of corresponding boundaries (no 1-January exemption), and an - off-by-k zip is re-aligned when some offset makes the gaps constant.""" - threshold = ep.MIN_BOUNDARY_DAYS if min_days is None else min_days - one_list = [item for item in (ep._as_start_date(raw) for raw in left) if item is not None] - two_list = [item for item in (ep._as_start_date(raw) for raw in right) if item is not None] - pairs = list(zip(one_list, two_list)) - for offset in (0, 1, -1, 2, -2, 3, -3): - a = one_list[offset:] if offset > 0 else one_list - b = two_list[-offset:] if offset < 0 else two_list - diffs = [(two - one).days for one, two in zip(a, b)] - if diffs and max(diffs) - min(diffs) <= 3: - pairs = list(zip(a, b)) - break - windows: list[Any] = [] - seen: set[tuple[int, int]] = set() - for one, two in pairs: - if abs((one - two).days) < threshold: - continue - for item in (one, two): - key = (item.year, item.month) - if key not in seen: - seen.add(key) - windows.append(item) - return windows - - -@contextmanager -def pairs_mode(mode: str) -> Iterator[None]: - if mode == "production": - yield - return - if mode == "strict_gate": - ep._boundary_windows = strict_boundary_windows - try: - yield - finally: - ep._boundary_windows = PRODUCTION_WINDOWS - return - ep._representative_pairs = research_all_pairs - try: - yield - finally: - ep._representative_pairs = PRODUCTION_PAIRS - - -def aligned_shift(left: Sequence[Any], right: Sequence[Any]) -> int | None: - best: list[int] | None = None - for offset in (0, 1, -1, 2, -2, 3, -3): - a = left[offset:] if offset > 0 else left - b = right[-offset:] if offset < 0 else right - diffs = [(two - one).days for one, two in zip(a, b)] - if diffs and (best is None or max(diffs) - min(diffs) < max(best) - min(best)): - best = diffs - return None if not best else abs(int(statistics.median(best))) - - -def stage_reps(built: dict[str, Any], times: Sequence[str], refresh: bool) -> list[dict[str, Any]]: - """Mirror of the representative selection in `_discriminating_event_probe_lists`.""" - full = ep._static_contexts(built) - remaining = ep._remaining_contexts(built, times) if times else [] - if refresh and remaining: - work = remaining - clusters = cluster_contexts_by_signature(work) - else: - work = full - clusters = cluster_contexts_by_signature(full) - if len(clusters) < 2: - work = remaining or full - clusters = cluster_contexts_by_signature(work) - if len(clusters) < 2: - return [] - reps = [cluster["representative"] for cluster in clusters if ep._scoreable(cluster["representative"])] - if len(reps) < 2: - reps = [item for item in work if ep._scoreable(item)] - return reps - - -def pair_rows( - pairs: Sequence[tuple[dict[str, Any], dict[str, Any]]], - *, - birth_date: str, - lo: int, - hi: int, - threshold: int, - include_pratyantar: bool, -) -> list[dict[str, Any]]: - rows = [] - for left, right in pairs: - left_dates = ep._vim_start_dates( - birth_date, float(left["planet_longitudes"]["Moon"]), lo, hi, - include_pratyantar=include_pratyantar) - right_dates = ep._vim_start_dates( - birth_date, float(right["planet_longitudes"]["Moon"]), lo, hi, - include_pratyantar=include_pratyantar) - windows = ep._boundary_windows(left_dates, right_dates, min_days=threshold) - shift = aligned_shift(left_dates, right_dates) - # Replicate `_boundary_windows`' pass rule per zipped pair and say why - # each pair passed: a real gap >= threshold, or the same-year clause - # being skipped because the two dates straddle 1 January. - # A misaligned zip compares non-corresponding boundaries, so its - # "gap" passes are counted separately. - misaligned = zip_misaligned(left_dates, right_dates) - by_gap = straddle = by_misaligned = 0 - for one, two in zip(left_dates, right_dates): - gap = abs((one - two).days) - if one.year == two.year and gap < threshold: - continue - if gap < threshold: - straddle += 1 - elif misaligned and shift is not None and shift < threshold: - by_misaligned += 1 - else: - by_gap += 1 - rows.append({ - "minutes": abs(clock(right) - clock(left)), - "shift_days": shift, - "clears_gate": shift is not None and shift >= threshold, - "zip_misaligned": misaligned, - "vim_windows": len(windows), - "vim_pass_by_gap": by_gap, - "vim_pass_by_year_straddle": straddle, - "vim_pass_by_misaligned_zip": by_misaligned, - }) - return rows - - -def union_dates(reps: Sequence[dict[str, Any]], mode: str, *, birth_date: str, lo: int, hi: int, refresh: bool) -> int: - kwargs: dict[str, Any] = {} - if refresh: - kwargs = { - "min_boundary_days": ep.REFRESH_MIN_BOUNDARY_DAYS, - "include_pratyantar": True, - "varga_narayana": True, - } - with pairs_mode(mode): - return len(ep._union_boundary_dates(reps, birth_date=birth_date, lo=lo, hi=hi, **kwargs)) - - -def probe_lists( - request: dict[str, Any], - built: dict[str, Any], - times: Sequence[str], - true_time: str, - *, - refresh: bool, - asked: Sequence[str], - mode: str, -) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, int]]: - payload = {**request, "refresh_probes": refresh, "asked_probe_keys": list(asked)} - original = ep._evaluate_contexts - tally = {"dasha_boundary_evaluated": 0, "dasha_boundary_split": 0} - - def counted(*args: Any, **kwargs: Any) -> dict[str, Any] | None: - result = original(*args, **kwargs) - if kwargs.get("source") == "dasha_boundary": - tally["dasha_boundary_evaluated"] += 1 - tally["dasha_boundary_split"] += int(result is not None) - return result - - ep._evaluate_contexts = counted - try: - with pairs_mode(mode): - public, dropped = ep._discriminating_event_probe_lists( - payload, built, scan=window_scan(built), candidate_times=list(times), - representative_time=true_time, today=TODAY, - ) - finally: - ep._evaluate_contexts = original - return public, dropped, tally - - -def count_probes( - public: Sequence[dict[str, Any]], - dropped: Sequence[dict[str, Any]], - *, - asked: Sequence[str], - true_time: str, - remaining: Sequence[str], - clusters: Sequence[dict[str, Any]], -) -> dict[str, Any]: - asked_set = set(asked) - everything = list(public) + list(dropped) - dated_all = [row for row in everything if str(row.get("source")) == "dasha_boundary"] - new_public = [row for row in public if asked_key(row) and asked_key(row) not in asked_set] - return { - "public": len(public), - "all_before_cap": len(everything), - "dasha_boundary_before_cap": len(dated_all), - "dasha_boundary_public": sum(1 for row in public if str(row.get("source")) == "dasha_boundary"), - "public_new": len(new_public), - "public_new_dasha_boundary": sum(1 for row in new_public if str(row.get("source")) == "dasha_boundary"), - "public_new_separating_truth": sum( - 1 for row in new_public if separates_true(row, true_time, remaining, clusters)), - "sources": sorted({str(row.get("source")) for row in everything}), - } - - -def run_case(case: dict[str, Any], radius: int) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - request = scoring_request_for({**case, "candidate_radius_minutes": radius}, radius) - contexts = compute_candidate_static_contexts(request) - events = list(case.get("events") or []) - bundle = score_bundle(case, radius, events, contexts, None) - built, rows, req = bundle["built"], bundle["rows"], bundle["request"] - times = [str(row["time"])[:5] for row in rows] - initial = generate_probes(req, built, times, true_time, gate="G0", - precision=finest_precision(events), refresh=False) - delivery = evaluate_delivery(rows=rows, contexts=list(built.get("static_contexts") or contexts), - probes=initial, true_time=true_time) - remaining = delivery["remaining"] - asked = delivery["asked_keys"] - clusters = raw_signature_clusters(list(built.get("static_contexts") or contexts)) - birth_date = str(req["birth_date"]) - birth_year = int(birth_date[:4]) - lo, hi = birth_year + 5, min(TODAY.year, birth_year + 80) - out: dict[str, Any] = { - "case_id": case["case_id"], "radius": radius, "birth_year": birth_year, "stages": {}, - } - for stage, refresh, stage_times, stage_asked in ( - ("initial", False, times, ()), - ("refresh", True, remaining, asked), - ): - if refresh and len(remaining) < 2: - out["stages"][stage] = {"skipped": "fewer_than_two_remaining", "remaining": len(remaining)} - continue - reps = stage_reps(built, stage_times, refresh) - threshold = ep.REFRESH_MIN_BOUNDARY_DAYS if refresh else ep.MIN_BOUNDARY_DAYS - block: dict[str, Any] = { - "reps": len(reps), - "rep_span_minutes": (clock(max(reps, key=clock)) - clock(min(reps, key=clock))) if reps else 0, - "threshold": threshold, - } - prod_pairs = PRODUCTION_PAIRS(reps) - every_pair = research_all_pairs(reps) - for label, pairs in (("production_pairs", prod_pairs), ("all_pairs", every_pair)): - rows_ = pair_rows(pairs, birth_date=birth_date, lo=lo, hi=hi, threshold=threshold, - include_pratyantar=refresh) - block[label] = { - "count": len(rows_), - "clearing_gate": sum(1 for row in rows_ if row["clears_gate"]), - "zip_misaligned": sum(1 for row in rows_ if row["zip_misaligned"]), - "with_vim_windows": sum(1 for row in rows_ if row["vim_windows"]), - "minutes": [row["minutes"] for row in rows_], - "shift_days": [row["shift_days"] for row in rows_], - } - block[label]["union_dates"] = union_dates( - reps, "production" if label == "production_pairs" else "all", - birth_date=birth_date, lo=lo, hi=hi, refresh=refresh) - public, dropped, tally = probe_lists( - req, built, stage_times, true_time, refresh=refresh, asked=stage_asked, - mode="production" if label == "production_pairs" else "all") - block[label]["probes"] = {**count_probes( - public, dropped, asked=stage_asked, true_time=true_time, - remaining=stage_times, clusters=clusters), **tally} - block[label]["vim_pass_by_gap"] = sum(row["vim_pass_by_gap"] for row in rows_) - block[label]["vim_pass_by_year_straddle"] = sum(row["vim_pass_by_year_straddle"] for row in rows_) - block[label]["vim_pass_by_misaligned_zip"] = sum(row["vim_pass_by_misaligned_zip"] for row in rows_) - strict_public, strict_dropped, strict_tally = probe_lists( - req, built, stage_times, true_time, refresh=refresh, asked=stage_asked, mode="strict_gate") - block["strict_gate"] = { - "union_dates": union_dates(reps, "strict_gate", birth_date=birth_date, lo=lo, hi=hi, refresh=refresh), - "probes": {**count_probes( - strict_public, strict_dropped, asked=stage_asked, true_time=true_time, - remaining=stage_times, clusters=clusters), **strict_tally}, - } - out["stages"][stage] = block - return out - - -def summarize(case_rows: Sequence[dict[str, Any]]) -> dict[str, Any]: - out: dict[str, Any] = {} - for radius in sorted({row["radius"] for row in case_rows}): - out[str(radius)] = {} - for stage in ("initial", "refresh"): - blocks = [row["stages"].get(stage) or {} for row in case_rows if row["radius"] == radius] - live = [block for block in blocks if "reps" in block] - summary: dict[str, Any] = { - "cases": len(blocks), - "cases_birth_before_1900": sum( - 1 for row in case_rows - if row["radius"] == radius and row.get("birth_year", 2000) < 1900), - "cases_measured": len(live), - "cases_skipped": len(blocks) - len(live), - "reps": distribution([block["reps"] for block in live], 1), - "rep_span_minutes": distribution([block["rep_span_minutes"] for block in live], 1), - } - for label in ("production_pairs", "all_pairs"): - parts = [block[label] for block in live] - probes = [part["probes"] for part in parts] - summary[label] = { - "pairs_mean": round(statistics.fmean([p["count"] for p in parts]), 2) if parts else None, - "pairs_clearing_gate_mean": round(statistics.fmean([p["clearing_gate"] for p in parts]), 2) if parts else None, - "cases_with_zero_pairs_clearing_gate": sum(1 for p in parts if p["clearing_gate"] == 0), - "pairs_zip_misaligned_share": round( - sum(p["zip_misaligned"] for p in parts) / max(sum(p["count"] for p in parts), 1), 3), - "pair_minutes": distribution([m for p in parts for m in p["minutes"]], 1), - "pair_shift_days": distribution([d for p in parts for d in p["shift_days"] if d is not None], 1), - "union_dates_mean": round(statistics.fmean([p["union_dates"] for p in parts]), 2) if parts else None, - "cases_zero_union_dates": sum(1 for p in parts if p["union_dates"] == 0), - "dasha_boundary_before_cap_mean": round(statistics.fmean([q["dasha_boundary_before_cap"] for q in probes]), 2) if probes else None, - "cases_zero_dasha_boundary_before_cap": sum(1 for q in probes if q["dasha_boundary_before_cap"] == 0), - "public_mean": round(statistics.fmean([q["public"] for q in probes]), 2) if probes else None, - "public_new_mean": round(statistics.fmean([q["public_new"] for q in probes]), 2) if probes else None, - "public_new_dasha_boundary_mean": round(statistics.fmean([q["public_new_dasha_boundary"] for q in probes]), 2) if probes else None, - "public_new_separating_truth_mean": round(statistics.fmean([q["public_new_separating_truth"] for q in probes]), 2) if probes else None, - "cases_zero_public_new": sum(1 for q in probes if q["public_new"] == 0), - "dasha_boundary_evaluated_mean": round(statistics.fmean([q["dasha_boundary_evaluated"] for q in probes]), 2) if probes else None, - "dasha_boundary_split_rate": round( - sum(q["dasha_boundary_split"] for q in probes) - / max(sum(q["dasha_boundary_evaluated"] for q in probes), 1), 3), - "vim_pass_by_gap_total": sum(p["vim_pass_by_gap"] for p in parts), - "vim_pass_by_year_straddle_total": sum(p["vim_pass_by_year_straddle"] for p in parts), - "vim_pass_by_misaligned_zip_total": sum(p["vim_pass_by_misaligned_zip"] for p in parts), - } - strict = [block["strict_gate"] for block in live] - summary["strict_gate"] = { - "union_dates_mean": round(statistics.fmean([p["union_dates"] for p in strict]), 2) if strict else None, - "dasha_boundary_before_cap_mean": round(statistics.fmean([p["probes"]["dasha_boundary_before_cap"] for p in strict]), 2) if strict else None, - "cases_zero_dasha_boundary_before_cap": sum(1 for p in strict if p["probes"]["dasha_boundary_before_cap"] == 0), - "public_new_mean": round(statistics.fmean([p["probes"]["public_new"] for p in strict]), 2) if strict else None, - "public_new_dasha_boundary_mean": round(statistics.fmean([p["probes"]["public_new_dasha_boundary"] for p in strict]), 2) if strict else None, - "cases_zero_public_new": sum(1 for p in strict if p["probes"]["public_new"] == 0), - "cases_zero_public_new_dasha_boundary": sum(1 for p in strict if p["probes"]["public_new_dasha_boundary"] == 0), - } - for label in ("production_pairs", "all_pairs"): - summary[label]["cases_zero_public_new_dasha_boundary"] = sum( - 1 for block in live if block[label]["probes"]["public_new_dasha_boundary"] == 0) - out[str(radius)][stage] = summary - return out - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", nargs="+", type=int, default=list(RADII)) - parser.add_argument("--no-write", action="store_true") - args = parser.parse_args() - holdout = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(holdout["cases"])[: args.limit or None] - case_rows: list[dict[str, Any]] = [] - errors: list[dict[str, Any]] = [] - for case in cases: - for radius in args.radii: - try: - case_rows.append(run_case(case, radius)) - except Exception as exc: # noqa: BLE001 - errors.append({"case_id": case["case_id"], "radius": radius, - "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()}) - assert ep._representative_pairs is PRODUCTION_PAIRS, "research patch leaked" - assert ep._boundary_windows is PRODUCTION_WINDOWS, "research patch leaked" - assert ep._evaluate_contexts.__name__ == "_evaluate_contexts", "research patch leaked" - print(f"done {case['case_id']}", flush=True) - assert ep.MIN_BOUNDARY_DAYS == 45 and ep.REFRESH_MIN_BOUNDARY_DAYS == 30 - payload = { - "generated_at": "2026-09-26", - "nature": "offline replay on the public AA open set (v4); not a blind test", - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "holdout": str(HOLDOUT.relative_to(ROOT)), - "case_count": len(cases), - "radii": list(args.radii), - "minute_step": MINUTE_STEP, - "today": TODAY.isoformat(), - "summary": summarize(case_rows), - "per_case": [ - { - "case_id": row["case_id"], "radius": row["radius"], "birth_year": row["birth_year"], - "stages": { - stage: (block if "reps" not in block else { - "reps": block["reps"], "rep_span_minutes": block["rep_span_minutes"], - **{label: {k: v for k, v in block[label].items() if k not in {"minutes", "shift_days"}} - for label in ("production_pairs", "all_pairs")}, - "strict_gate": block["strict_gate"], - }) - for stage, block in row["stages"].items() - }, - } - for row in case_rows - ], - "errors": errors, - "command": "python3 scripts/research/representative_pairs_probe.py", - } - if not args.no_write: - REPORT_JSON.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps({"summary": payload["summary"], "errors": len(errors)}, ensure_ascii=False, indent=1)) - return 0 if not errors else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/scoring_research.py b/scripts/research/scoring_research.py deleted file mode 100644 index 9e51e4b2c..000000000 --- a/scripts/research/scoring_research.py +++ /dev/null @@ -1,615 +0,0 @@ -#!/usr/bin/env python3 -"""Offline research runner for TASK-rectification-scoring-research-20260929. - -R-0 research scorer reconciled per minute against the production scorer, then - per-(candidate, event) rule features recorded (eleven production rules, - auxiliary rules, and unscored extras: KP cusp sub/star lords, Pranapada / - Hora / Ghati / Bhava lagna, D60). -R-A likelihood-ratio weights (Laplace α = 1) per radius, leave-one-CASE-out - and full-fit; variants A1 (production features, reward only), A2 (+extras, - reward only), A3 (+extras, naive-Bayes present/absent, negative allowed); - six-probe replay, engine top1, calibration curve, robustness (±7-day and - ±1–3-month date shifts, 1–2 flipped answers). -R-B absence evidence: gap years inside a domain's spoken span answered "no" - at 0.5 / 1.0 / 2.0 points (a card is 2.0), plus "user omitted 1–2 events" - robustness. -R-C precision follow-up: with all day events degraded to year ("spoken" - form), how many events would split candidates if the month were known, - and the gain from asking 1 / 2 of them (as a prior recompute and as an - answered probe). - -Every verdict field is written as ``pending_v5``: the task brief allows a -verdict only on the v5 open set. v4 numbers are debugging references. - -Run: - PYTHONHASHSEED=0 python3 scripts/research/scoring_research.py --limit 2 --radii 10 --no-write - PYTHONHASHSEED=0 python3 scripts/research/scoring_research.py -""" - -from __future__ import annotations - -import argparse -import gc -import json -import pickle -import sys -import time as clock_module -import traceback -from collections import defaultdict -from pathlib import Path -from random import Random -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import AYANAMSA, NODE_MODE, compute_candidate_static_contexts # noqa: E402 -from scripts.rectification.scoring_service import build_event_contribution_matrix, score_from_matrix, scoreable_request # noqa: E402 -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.offline_research_20260926_lib import exhaustive_flip_sets, flipped_answers, sample_flip_sets # noqa: E402 -from scripts.research.precision_gate_lib import gate_verdict, jitter_day_events # noqa: E402 -from scripts.research.probe_supply_after_six import ASK_COUNT, optimal_answer # noqa: E402 -from scripts.active_rectification_events import precision_weight # noqa: E402 -import scripts.research.scoring_research_lib as lib # noqa: E402 - -HOLDOUT_V4 = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -OUT_DIR = ROOT / "docs" / "research" -RADII = (10, 30, 60) -PRIORS = ("raw", "percent") -ABSENCE_POINTS = (0.5, 1.0, 2.0) # score points per "no"; a card is 2.0 -CARD_POINTS = 2.0 -OMIT_REPEATS = 5 -SHIFT_REPEATS = 3 -FLIP_REPEATS = 10 -SEED = 20260929 -ABSENCE_SOURCE = "absence_research" -FOLLOWUP_SOURCE = "precision_followup_research" - - -# --------------------------------------------------------------------------- -# per-case data -# --------------------------------------------------------------------------- - -class CaseData: - def __init__(self, case: dict[str, Any], radius: int, cache_dir: Path | None) -> None: - self.case = case - self.case_id = str(case["case_id"]) - self.radius = radius - self.true_time = str(case["birth"]["time"])[:5] - self.request = scoring_request_for({**case, "candidate_radius_minutes": radius}, radius) - self.contexts = self._contexts(cache_dir) - self.times = [ctx["candidate_at"].strftime("%H:%M") for ctx in self.contexts] - self.truth_times = lib.truth_cluster_times(self.contexts, self.true_time) - self.d60 = lib.d60_charts(self.contexts) - # production - prod_built = build_event_contribution_matrix(self.request, static_contexts=self.contexts) - self.prod_rows = score_from_matrix(self.request, prod_built) - self.prod_built = prod_built - self.probes = lib.production_probes(self.request, prod_built, self.times, self.true_time) - self.prod_public = lib.public_for(self.prod_rows, self.contexts) - # research recording pass (must reconcile to production) - self.store = lib.FeatureStore() - built = build_event_contribution_matrix( - self.request, row_provider=lib.make_recording_provider(self.contexts, self.store, self.d60), - static_contexts=self.contexts, - ) - rows = score_from_matrix(self.request, built) - self.reconciliation = lib.reconcile_rows(self.prod_rows, rows) - self.training_ids = lib.training_event_ids(self.request) - self.representatives = lib.representatives_for(self.contexts) - self.events_by_id = {str(e["id"]): e for e in self.request["events"]} - - def _contexts(self, cache_dir: Path | None) -> list[dict[str, Any]]: - if cache_dir is not None: - path = cache_dir / f"{self.case_id}_{self.radius}.pkl" - if path.exists(): - with path.open("rb") as handle: - return pickle.load(handle) - contexts = compute_candidate_static_contexts(self.request) - if cache_dir is not None: - cache_dir.mkdir(parents=True, exist_ok=True) - with (cache_dir / f"{self.case_id}_{self.radius}.pkl").open("wb") as handle: - pickle.dump(contexts, handle) - return contexts - - # features ------------------------------------------------------------- - def examples(self, *, include_extras: bool) -> list[tuple[dict[str, float], bool]]: - out: list[tuple[dict[str, float], bool]] = [] - truth = set(self.truth_times) - for matrix in self.feature_matrices(include_extras=include_extras).values(): - for time in self.times: - out.append((matrix.get(time, {}), time in truth)) - return out - - def feature_matrices(self, *, include_extras: bool) -> dict[str, dict[str, dict[str, float]]]: - cache = self.__dict__.setdefault("_fm_cache", {}) - if include_extras not in cache: - cache[include_extras] = { - event_id: lib.event_feature_matrix(self.store, event_id, self.times, include_extras=include_extras) - for event_id in self.training_ids - } - return cache[include_extras] - - def proxy_rows(self, table: lib.LRTable, variant: str) -> list[dict[str, Any]]: - """Linear proxy of `weighted_rows` for fitting scale / temperature (no matrix build).""" - include_extras, allow_negative = lib.VARIANT_SPEC[variant] - universe = [n for n in sorted(table.present) if (include_extras or not lib.is_extra_feature(n))] - matrices = self.feature_matrices(include_extras=include_extras) - rows = [] - for time in self.times: - total = 0.0 - for event_id, matrix in matrices.items(): - weight = precision_weight(str(self.events_by_id[event_id]["precision"])) - total += weight * lib.weighted_points(matrix.get(time, {}), table, allow_negative=allow_negative, universe=universe) - rows.append({"time": time, "score": round(total, 6)}) - return rows - - # scoring with a weight table ------------------------------------------ - def weighted_rows( - self, table: lib.LRTable, variant: str, scale: float, - store: lib.FeatureStore | None = None, request: dict[str, Any] | None = None, - ) -> tuple[list[dict[str, Any]], dict[str, Any]]: - request = request or self.request - built = build_event_contribution_matrix( - request, - row_provider=lib.make_weighted_provider(store or self.store, table, variant=variant, scale=scale), - static_contexts=self.contexts, - ) - return score_from_matrix(request, built), built - - def rescored_store(self, events: Sequence[dict[str, Any]]) -> tuple[lib.FeatureStore, dict[str, Any], list[dict[str, Any]]]: - """Re-record features for an altered event list (date shifts): (store, request, production rows).""" - request = scoring_request_for({**self.case, "events": list(events), "candidate_radius_minutes": self.radius}, self.radius) - store = lib.FeatureStore() - built = build_event_contribution_matrix( - request, row_provider=lib.make_recording_provider(self.contexts, store, self.d60), static_contexts=self.contexts, - ) - return store, request, score_from_matrix(request, built) - - def production_rows_for(self, events: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: - request = scoring_request_for({**self.case, "events": list(events), "candidate_radius_minutes": self.radius}, self.radius) - built = build_event_contribution_matrix(request, static_contexts=self.contexts) - return score_from_matrix(request, built) - - -def evaluate(data: CaseData, rows: Sequence[dict[str, Any]], *, softmax_prior: bool, pre_answers=(), answers=None, temperature: float = 1.0, probes=None) -> dict[str, dict[str, Any]]: - public = lib.public_for(rows, data.contexts) - out: dict[str, dict[str, Any]] = {} - for mode in PRIORS: - prior = lib.prior_for(public, mode=mode, softmax=softmax_prior, temperature=temperature) - result = lib.replay( - public=public, prior=prior, probes=data.probes if probes is None else probes, true_time=data.true_time, - window_times=data.times, pre_answers=pre_answers, answers=answers, - ) - result["engine_top1"] = lib.engine_top1(public, data.true_time) - out[mode] = result - return out - - -# --------------------------------------------------------------------------- -# R-A -# --------------------------------------------------------------------------- - -def fit_prior(training: Sequence[CaseData], table: lib.LRTable, variant: str) -> tuple[float, float]: - """(scale, temperature) from training cases only. - - scale: research within-case score range matched to the production median - range (so the raw-prior replay's ±2 / 8-lead constants mean the same); - temperature: single Platt temperature for the percent (softmax) prior. - Training-case scores use the linear proxy (`CaseData.proxy_rows`: feature - weights × precision weight, no kind factor / transition proximity) so a - fold costs O(n) dictionary sums instead of n contribution-matrix builds. - """ - prod = [lib.within_case_range(d.prod_rows) for d in training] - rows_by_case = {d.case_id: d.proxy_rows(table, variant) for d in training} - research = [lib.within_case_range(rows) for rows in rows_by_case.values()] - p_med, r_med = lib.median(prod), lib.median(research) - scale = round(p_med / r_med, 6) if p_med and r_med else 1.0 - publics = [ - (lib.public_for([{**r, "score": float(r["score"]) * scale} for r in rows_by_case[d.case_id]], d.contexts), d.truth_times) - for d in training - ] - return scale, lib.fit_temperature(publics) - - -def run_ra(by_radius: dict[int, list[CaseData]], *, fast: bool, probes_per_variant: bool = False) -> dict[str, Any]: - out: dict[str, Any] = {"variants": list(lib.VARIANTS), "alpha": lib.LAPLACE_ALPHA, "probes_per_variant": probes_per_variant, "radii": {}} - for radius, cases in sorted(by_radius.items()): - block: dict[str, Any] = {"n": len(cases), "baseline": {}, "full_fit": {}, "loo": {}, "robustness": {}, "calibration": {}, "lr_table": {}, "noise_features": {}} - baseline_rows = [] - for data in cases: - row = evaluate(data, data.prod_rows, softmax_prior=False) - baseline_rows.append({"case_id": data.case_id, **{f"{m}": row[m] for m in PRIORS}}) - block["baseline"] = {m: lib.summarize([r[m] for r in baseline_rows]) for m in PRIORS} - block["per_case"] = {"baseline": [{"case_id": r["case_id"], **{m: {k: r[m][k] for k in ("top1", "coverage", "width", "engine_top1")} for m in PRIORS}} for r in baseline_rows]} - per_case_examples = { - include: {d.case_id: d.examples(include_extras=include) for d in cases} for include in (False, True) - } - altered_stores: dict[tuple[str, str, int], tuple[lib.FeatureStore, dict[str, Any]]] = {} - for variant in lib.VARIANTS: - include_extras, _neg = lib.VARIANT_SPEC[variant] - examples = per_case_examples[include_extras] - # full fit ------------------------------------------------------- - full_table = lib.estimate_lr([ex for rows in examples.values() for ex in rows]) - full_scale, full_temperature = fit_prior(cases, full_table, variant) - full_rows = [] - for data in cases: - rows, _ = data.weighted_rows(full_table, variant, full_scale) - full_rows.append(evaluate(data, rows, softmax_prior=True, temperature=full_temperature)) - block["full_fit"][variant] = { - "scale": full_scale, - "temperature": full_temperature, - **{m: lib.summarize([r[m] for r in full_rows]) for m in PRIORS}, - } - if variant == "A3": - block["lr_table"] = { - name: { - "log_lr_present": full_table.present[name], - "log_lr_absent": full_table.absent[name], - **full_table.support[name], - "extra": lib.is_extra_feature(name), - } - for name in sorted(full_table.present) - } - ci = lib.bootstrap_lr(examples, resamples=50 if fast else 200) - for name, interval in ci.items(): - block["lr_table"].setdefault(name, {}).update(interval) - block["noise_features"] = sorted( - name for name, row in block["lr_table"].items() - if row.get("p05") is not None and row["p05"] <= 0.0 <= row["p95"] - ) - # leave-one-case-out ------------------------------------------- - loo_rows = [] - robustness = defaultdict(list) - calibration_points: list[tuple[float, bool]] = [] - temperatures: list[float] = [] - for held in cases: - training = [d for d in cases if d.case_id != held.case_id] - table = lib.estimate_lr([ex for d in training for ex in examples[d.case_id]]) - scale, temperature = fit_prior(training, table, variant) - temperatures.append(temperature) - rows, built_v = held.weighted_rows(table, variant, scale) - result = evaluate(held, rows, softmax_prior=True, temperature=temperature) - if probes_per_variant: - own = lib.production_probes(held.request, built_v, held.times, held.true_time) - result["own_probes"] = evaluate(held, rows, softmax_prior=True, temperature=temperature, probes=own) - result["own_probes_count"] = len(own) - result["case_id"] = held.case_id - loo_rows.append(result) - if variant == "A3": - public = lib.public_for(rows, held.contexts) - posterior = lib.percent_softmax({str(r["time"])[:5]: float(r["score"]) for r in public}, temperature) - truth = set(held.truth_times) - for rep in public: - stamp = str(rep["time"])[:5] - members = {str(t)[:5] for t in (rep.get("cluster_times") or [stamp])} - calibration_points.append((posterior.get(stamp, 0.0) / 100.0, bool(members & truth))) - # robustness: date shifts (features re-recorded with fold weights) - if not fast or variant == "A3": - events = list(held.case.get("events") or []) - shifted_sets = { - "jitter_7d": [jitter_day_events(events, 7, case_id=held.case_id)], - "shift_1_3_months": [ - lib.shift_day_events_by_months(events, seed=f"{SEED}:{held.case_id}:{radius}:{k}") - for k in range(1 if fast else SHIFT_REPEATS) - ], - } - for label, variants_of_events in shifted_sets.items(): - for index, altered in enumerate(variants_of_events): - cache_key = (held.case_id, label, index) - if cache_key not in altered_stores: - altered_stores[cache_key] = held.rescored_store(altered)[:2] - store, request_alt = altered_stores[cache_key] - rows_alt, _ = held.weighted_rows(table, variant, scale, store=store, request=request_alt) - robustness[label].append(evaluate(held, rows_alt, softmax_prior=True, temperature=temperature)) - # answer flips on the LOO rows - asked = list(held.probes)[:ASK_COUNT] - optimal = [optimal_answer(p, held.true_time) for p in asked] - for k in (1, 2): - sets = exhaustive_flip_sets(optimal, k) if k == 1 else sample_flip_sets( - optimal, k, 3 if fast else FLIP_REPEATS, case_id=held.case_id, radius=radius, - ) - for picked in sets: - robustness[f"flip_{k}"].append(evaluate( - held, rows, softmax_prior=True, answers=flipped_answers(optimal, picked), temperature=temperature, - )) - block["loo"][variant] = {m: lib.summarize([r[m] for r in loo_rows]) for m in PRIORS} - block["loo"][variant]["temperatures"] = sorted(set(temperatures)) - block["loo"][variant]["gate_verdict"] = { - m: gate_verdict(block["baseline"][m], block["loo"][variant][m]) for m in PRIORS - } - block["loo"][variant]["hard_line_1"] = { - m: { - "coverage_count": sum(1 for r in loo_rows if r[m]["coverage"]), - "baseline_coverage_count": sum(1 for r in baseline_rows if r[m]["coverage"]), - "top1": block["loo"][variant][m]["top1"], - "baseline_top1": block["baseline"][m]["top1"], - "pass": (sum(1 for r in loo_rows if r[m]["coverage"]) >= sum(1 for r in baseline_rows if r[m]["coverage"]) - and float(block["loo"][variant][m]["top1"]) + 1e-9 >= float(block["baseline"][m]["top1"])), - "note": "truth and opposite cells coincide under D1 (nothing is injected after the six probes)", - } - for m in PRIORS - } - if probes_per_variant: - block["loo"][variant]["own_probes"] = {m: lib.summarize([r["own_probes"][m] for r in loo_rows]) for m in PRIORS} - block["loo"][variant]["own_probes"]["mean_count"] = round(sum(r["own_probes_count"] for r in loo_rows) / max(len(loo_rows), 1), 2) - block["per_case"][variant] = [{"case_id": r["case_id"], **{m: {k: r[m][k] for k in ("top1", "coverage", "width", "engine_top1")} for m in PRIORS}} for r in loo_rows] - block["loo"][variant]["verdict"] = "pending_v5" - if robustness: - block["robustness"][variant] = { - label: {m: lib.summarize([r[m] for r in rows_]) for m in PRIORS} - for label, rows_ in robustness.items() - } - if variant == "A3": - block["calibration"] = lib.calibration_bins(calibration_points) - out["radii"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# R-B -# --------------------------------------------------------------------------- - -def absence_probes(data: CaseData, events: Sequence[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, list[int]]]: - gaps = lib.absent_years(events) - probes: list[dict[str, Any]] = [] - for domain, years in gaps.items(): - for year in years: - probe = lib.split_probe( - data.representatives, birth_date=str(data.request["birth_date"]), domain=domain, - year=year, month=None, source=ABSENCE_SOURCE, - ) - if probe is not None: - probes.append(probe) - return probes, gaps - - -def run_rb(by_radius: dict[int, list[CaseData]], *, fast: bool) -> dict[str, Any]: - out: dict[str, Any] = {"points": list(ABSENCE_POINTS), "card_points": CARD_POINTS, "omit_repeats": OMIT_REPEATS, "radii": {}} - for radius, cases in sorted(by_radius.items()): - rows_by_arm: dict[str, list[dict[str, Any]]] = defaultdict(list) - gap_stats = [] - omit_rows: dict[str, list[dict[str, Any]]] = defaultdict(list) - for data in cases: - training = [data.events_by_id[i] for i in data.training_ids] - spoken = [{**e, "date": e.get("date_start"), "domain": e["domain"]} for e in training] - probes, gaps = absence_probes(data, spoken) - gap_stats.append({ - "case_id": data.case_id, "absent_years": sum(len(v) for v in gaps.values()), - "domains_with_gaps": len(gaps), "absence_probes": len(probes), - }) - base = evaluate(data, data.prod_rows, softmax_prior=False) - rows_by_arm["B0"].append(base) - for points in ABSENCE_POINTS: - pre = [(probe, "no", points / CARD_POINTS) for probe in probes] - rows_by_arm[f"absence@{points}"].append(evaluate(data, data.prod_rows, softmax_prior=False, pre_answers=pre)) - # omission robustness: user did not mention 1–2 of the training events - for k in (1, 2): - for rep in range(1 if fast else OMIT_REPEATS): - kept = lib.drop_events(spoken, k, seed=f"{SEED}:{data.case_id}:{radius}:{k}:{rep}") - probes_k, _ = absence_probes(data, kept) - for points in ABSENCE_POINTS: - pre = [(probe, "no", points / CARD_POINTS) for probe in probes_k] - omit_rows[f"omit_{k}@{points}"].append(evaluate(data, data.prod_rows, softmax_prior=False, pre_answers=pre)) - block: dict[str, Any] = { - "n": len(cases), - "gap_stats": { - "mean_absent_years": round(sum(g["absent_years"] for g in gap_stats) / len(gap_stats), 2), - "mean_absence_probes": round(sum(g["absence_probes"] for g in gap_stats) / len(gap_stats), 2), - "cases_with_probes": sum(1 for g in gap_stats if g["absence_probes"]), - }, - "arms": {arm: {m: lib.summarize([r[m] for r in rows]) for m in PRIORS} for arm, rows in rows_by_arm.items()}, - "omission": {arm: {m: lib.summarize([r[m] for r in rows]) for m in PRIORS} for arm, rows in omit_rows.items()}, - } - for arm in block["arms"]: - if arm == "B0": - continue - block["arms"][arm]["gate_verdict"] = {m: gate_verdict(block["arms"]["B0"][m], block["arms"][arm][m]) for m in PRIORS} - block["arms"][arm]["hard_line_1"] = {m: { - "coverage_count": sum(1 for r in rows_by_arm[arm] if r[m]["coverage"]), - "baseline_coverage_count": sum(1 for r in rows_by_arm["B0"] if r[m]["coverage"]), - "pass": sum(1 for r in rows_by_arm[arm] if r[m]["coverage"]) >= sum(1 for r in rows_by_arm["B0"] if r[m]["coverage"]) - and float(block["arms"][arm][m]["top1"]) + 1e-9 >= float(block["arms"]["B0"][m]["top1"]), - } for m in PRIORS} - block["arms"][arm]["verdict"] = "pending_v5" - out["radii"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# R-C -# --------------------------------------------------------------------------- - -def run_rc(by_radius: dict[int, list[CaseData]], *, fast: bool) -> dict[str, Any]: - out: dict[str, Any] = {"radii": {}} - for radius, cases in sorted(by_radius.items()): - rows_by_arm: dict[str, list[dict[str, Any]]] = defaultdict(list) - askable_counts = [] - for data in cases: - originals = {str(e["id"]): e for e in data.case.get("events") or []} - raw_events = list(data.case.get("events") or []) - spoken = lib.degrade_to_year(raw_events) - spoken_rows = data.production_rows_for(spoken) - - def keep(arm: str, result: dict[str, dict[str, Any]]) -> None: - rows_by_arm[arm].append({"case_id": data.case_id, **result}) - - keep("B0_true_precision", evaluate(data, data.prod_rows, softmax_prior=False)) - keep("C0_spoken", evaluate(data, spoken_rows, softmax_prior=False)) - # which spoken (year) events would split candidates if the month were known? - training = set(data.training_ids) - id_map = {str(e["id"]): str(rid) for rid, e in zip( - [str(x["id"]) for x in data.request["events"]], data.case.get("events") or [], - )} - candidates = [] - for event in raw_events: - if str(event.get("precision")) not in {"day", "month"}: - continue - request_id = id_map.get(str(event["id"])) - if request_id not in training: - continue - year, month = int(str(event["date"])[:4]), int(str(event["date"])[5:7]) - probe = lib.split_probe( - data.representatives, birth_date=str(data.request["birth_date"]), domain=str(event["domain"]), - year=year, month=month, source=FOLLOWUP_SOURCE, - ) - if probe is None: - continue - candidates.append((float(probe.get("information_gain") or 0), str(event["id"]), probe)) - candidates.sort(key=lambda item: (-item[0], item[1])) - askable_counts.append(len(candidates)) - for k in (1, 2): - picked = candidates[:k] - if len(picked) < k: - continue - ids = {item[1] for item in picked} - upgraded = lib.upgrade_to_month(spoken, ids, originals) - upgraded_rows = data.production_rows_for(upgraded) - pre = [(item[2], "yes", 1.0) for item in picked] - keep(f"C{k}_prior", evaluate(data, upgraded_rows, softmax_prior=False)) - keep(f"C{k}_probe", evaluate(data, spoken_rows, softmax_prior=False, pre_answers=pre)) - keep(f"C{k}_both", evaluate(data, upgraded_rows, softmax_prior=False, pre_answers=pre)) - by_case = {arm: {r["case_id"]: r for r in rows} for arm, rows in rows_by_arm.items()} - block: dict[str, Any] = { - "n": len(cases), - "askable_per_case": { - "mean": round(sum(askable_counts) / len(askable_counts), 2) if askable_counts else None, - "distribution": {str(k): askable_counts.count(k) for k in sorted(set(askable_counts))}, - "cases_with_at_least_one": sum(1 for c in askable_counts if c >= 1), - "cases_with_at_least_two": sum(1 for c in askable_counts if c >= 2), - }, - "arms": {arm: {m: lib.summarize([r[m] for r in rows]) for m in PRIORS} for arm, rows in rows_by_arm.items()}, - "per_case": {arm: [{"case_id": r["case_id"], **{m: {k: r[m][k] for k in ("top1", "coverage", "width", "engine_top1")} for m in PRIORS}} for r in rows] for arm, rows in rows_by_arm.items()}, - } - for arm, rows in rows_by_arm.items(): - if arm.startswith("C0") or arm.startswith("B0"): - continue - ids = [r["case_id"] for r in rows] - subset_c0 = [by_case["C0_spoken"][cid] for cid in ids] - subset_b0 = [by_case["B0_true_precision"][cid] for cid in ids] - block["arms"][arm]["subset_C0"] = {m: lib.summarize([r[m] for r in subset_c0]) for m in PRIORS} - block["arms"][arm]["subset_B0"] = {m: lib.summarize([r[m] for r in subset_b0]) for m in PRIORS} - block["arms"][arm]["gate_verdict_vs_subset_C0"] = {m: gate_verdict(block["arms"][arm]["subset_C0"][m], block["arms"][arm][m]) for m in PRIORS} - block["arms"][arm]["hard_line_1_vs_subset_C0"] = {m: { - "coverage_count": sum(1 for r in rows if r[m]["coverage"]), - "subset_C0_coverage_count": sum(1 for r in subset_c0 if r[m]["coverage"]), - "pass": sum(1 for r in rows if r[m]["coverage"]) >= sum(1 for r in subset_c0 if r[m]["coverage"]) - and float(block["arms"][arm][m]["top1"]) + 1e-9 >= float(block["arms"][arm]["subset_C0"][m]["top1"]), - } for m in PRIORS} - block["arms"][arm]["gate_verdict_vs_C0"] = {m: gate_verdict(block["arms"]["C0_spoken"][m], block["arms"][arm][m]) for m in PRIORS} - block["arms"][arm]["verdict"] = "pending_v5" - out["radii"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# main -# --------------------------------------------------------------------------- - -def load_cases(path: Path) -> tuple[dict[str, Any], list[dict[str, Any]]]: - payload = json.loads(path.read_text(encoding="utf-8")) - return payload, list(payload["cases"]) - - -def write_json(path: Path, payload: dict[str, Any]) -> None: - path.write_text(json.dumps(payload, ensure_ascii=False, indent=1, sort_keys=True) + "\n", encoding="utf-8") - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--holdout", default=str(HOLDOUT_V4)) - parser.add_argument("--dataset-label", default="v4") - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", nargs="+", type=int, default=list(RADII)) - parser.add_argument("--parts", nargs="+", default=["ra", "rb", "rc"]) - parser.add_argument("--cache-dir", default="") - parser.add_argument("--fast", action="store_true", help="fewer repeats (development)") - parser.add_argument("--no-write", action="store_true") - parser.add_argument("--out-suffix", default="2026_09_29") - parser.add_argument("--probes-per-variant", action="store_true", help="also replay LOO variants with probes generated from their own matrix") - args = parser.parse_args() - started = clock_module.time() - holdout_path = Path(args.holdout) - meta, cases = load_cases(holdout_path) - if args.limit: - cases = cases[: args.limit] - cache_dir = Path(args.cache_dir) if args.cache_dir else None - errors: list[dict[str, Any]] = [] - reconciliation: list[dict[str, Any]] = [] - parts = {"ra": "lr", "rb": "absence", "rc": "precision_followup"} - radii_results: dict[str, dict[str, dict[str, Any]]] = {key: {} for key in parts.values()} - part_meta: dict[str, dict[str, Any]] = {} - # One radius at a time: 77 cases x 3 radii of static contexts do not fit in memory together. - for radius in args.radii: - loaded: list[CaseData] = [] - for case in cases: - try: - data = CaseData(case, radius, cache_dir) - except Exception as exc: # noqa: BLE001 - errors.append({"case_id": case.get("case_id"), "radius": radius, "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()}) - continue - reconciliation.append({"case_id": data.case_id, "radius": radius, **data.reconciliation}) - loaded.append(data) - print(f"loaded radius {radius}: {len(loaded)} cases ({clock_module.time() - started:.0f}s)", flush=True) - if any(row["changed"] for row in reconciliation if row["radius"] == radius): - print(json.dumps({"UNRECONCILED": [row for row in reconciliation if row["changed"]]}, ensure_ascii=False, indent=1)) - return 2 - by_radius = {radius: loaded} - runners = { - "ra": lambda: run_ra(by_radius, fast=args.fast, probes_per_variant=args.probes_per_variant), - "rb": lambda: run_rb(by_radius, fast=args.fast), - "rc": lambda: run_rc(by_radius, fast=args.fast), - } - for part, key in parts.items(): - if part not in args.parts: - continue - block = runners[part]() - radii_results[key].update(block.pop("radii")) - part_meta[key] = block - print(f"{part.upper()} radius {radius} done {clock_module.time() - started:.0f}s", flush=True) - del loaded, by_radius - gc.collect() - header = { - "generated_for": "TASK-rectification-scoring-research-20260929", - "dataset": args.dataset_label, - "holdout": str(holdout_path.relative_to(ROOT)) if holdout_path.is_relative_to(ROOT) else str(holdout_path), - "case_count": len(cases), - "radii": list(args.radii), - "minute_step": MINUTE_STEP, - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "ask_count": ASK_COUNT, - "probe_today": lib.TODAY.isoformat(), - "probes": "production G0 probes generated once per case/radius from the production matrix; reused for every arm (own_probes = regenerated from the variant matrix)", - "open_set_not_blind": True, - "verdict": "pending_v5" if args.dataset_label != "v5" else "see_report", - "reconciliation": {"cases": len(reconciliation), "unreconciled": sum(1 for r in reconciliation if r["changed"]), "rows": reconciliation}, - "errors": errors, - "seed": SEED, - "fast": bool(args.fast), - } - results: dict[str, dict[str, Any]] = {} - for part, key in parts.items(): - if part in args.parts: - results[key] = {**header, "part": {"ra": "R-A", "rb": "R-B", "rc": "R-C"}[part], **part_meta.get(key, {}), "radii": radii_results[key]} - for key, payload in results.items(): - if not args.no_write: - write_json(OUT_DIR / f"scoring_research_{key}_{args.out_suffix}.json", payload) - brief: dict[str, Any] = {"reconciliation_unreconciled": header["reconciliation"]["unreconciled"], "errors": len(errors), "elapsed_seconds": round(clock_module.time() - started, 1)} - for key, payload in results.items(): - brief[key] = {} - for radius, block in payload["radii"].items(): - if key == "lr": - brief[key][radius] = { - "baseline": {m: (block["baseline"][m]["top1"], block["baseline"][m]["coverage"], block["baseline"][m]["width_median"], block["baseline"][m]["engine_top1"]) for m in PRIORS}, - **{v: {m: (block["loo"][v][m]["top1"], block["loo"][v][m]["coverage"], block["loo"][v][m]["width_median"], block["loo"][v][m]["engine_top1"]) for m in PRIORS} for v in lib.VARIANTS}, - } - else: - brief[key][radius] = {arm: {m: (s[m]["top1"], s[m]["coverage"], s[m]["width_median"]) for m in PRIORS} for arm, s in block["arms"].items()} - print(json.dumps(brief, ensure_ascii=False, indent=1)) - return 0 if not errors else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/research/scoring_research_lib.py b/scripts/research/scoring_research_lib.py deleted file mode 100644 index b1d824c5e..000000000 --- a/scripts/research/scoring_research_lib.py +++ /dev/null @@ -1,820 +0,0 @@ -"""Scaffold (R-0) for TASK-rectification-scoring-research-20260929. - -Offline only. Nothing here changes a production default or a frozen scoring -file. The module records, for every (case, candidate minute, event, sample -date), which scoring rules fire — the eleven production rules from -`active_rectification_event_engine._score_event` plus the auxiliary -transit / Ashtakavarga / Shadbala rules — and a set of *extra* observations -that production computes but does not score (KP cusp sub-lords, Pranapada / -Hora / Ghati / Bhava lagna, D60). Likelihood-ratio weights are estimated per -feature with leave-one-**case**-out folds, and a weighted row provider feeds -the same contribution-matrix / probe / six-question replay machinery that the -09-14 / 09-26 / 09-29 studies used. - -Recording provider vs production: the provider returns exactly the production -evidence (same rule ids, same points), so `build_event_contribution_matrix` -yields the same matrix as the production path. `reconcile_rows` asserts that -per case before any experiment (task hard line 4). -""" - -from __future__ import annotations - -import math -import statistics -import sys -from collections import defaultdict -from dataclasses import dataclass, field -from datetime import date, datetime -from pathlib import Path -from random import Random -from typing import Any, Callable, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - DOMAIN_CONFIG, - OBSERVATION_ONLY_LAYERS, - _active_narayana, - _active_vimshottari, - _ashtakavarga_auxiliary, - _controlled_transit_rules, - _event_datetime, - _relative_house, - _shadbala_verified_components_auxiliary, - _varga_chart, - _varga_house, -) -import scripts.rectification.event_probes as event_probes # noqa: E402 -from scripts.rectification.candidate_contrast import cluster_contexts_by_signature # noqa: E402 -from scripts.rectification.case_holdout import holdout_event_ids # noqa: E402 -from scripts.rectification.contracts import is_scoreable_event # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, -) -from scripts.research.cluster_width_lib import ( # noqa: E402 - SEPARATION_LEAD, - delivery_from_public, - merge_adjacent_traced, - metrics_bundle, - public_from_clusters, - raw_signature_clusters, - shannon_entropy, - still_valid_public, -) -from scripts.research.precision_gate_lib import ( # noqa: E402 - VargaPolicy, - score_event_with_policy, -) -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - SCORE_DELTA, - apply_answer, - inherit_direction, - optimal_answer, - outcome_groups, -) -import varga # noqa: E402 - -TODAY = date(2026, 9, 16) # same probe "today" as the 09-16 / 09-29 replays -LAPLACE_ALPHA = 1.0 -EPS = 1e-9 -EXTRA_PREFIXES = ("kp_", "pranapada_", "hora_lagna_", "ghati_lagna_", "bhava_lagna_") -D60_SUFFIX = "_domain_varga_d60" -IGNORED_RULE_PREFIXES = ("event_kind:", "event_kind_profile:", "no_domain_activation") -CONSTANT_RULES = frozenset({"occupation_auxiliary_not_primary", "appearance_auxiliary_not_primary"}) -VARIANTS = ("A1", "A2", "A3") -VARIANT_SPEC = { - # (uses extra features, allows negative / absence weights) - "A1": (False, False), - "A2": (True, False), - "A3": (True, True), -} - - -# --------------------------------------------------------------------------- -# small helpers -# --------------------------------------------------------------------------- - -def hhmm(value: object) -> str | None: - text = str(value or "")[:5] - return text if len(text) == 5 and text[2] == ":" else None - - -def clock(value: str) -> int: - return int(value[:2]) * 60 + int(value[3:5]) - - -def is_extra_feature(name: str) -> bool: - return name.startswith(EXTRA_PREFIXES) or name.endswith(D60_SUFFIX) - - -def is_scoring_rule(name: str) -> bool: - if name.startswith(IGNORED_RULE_PREFIXES) or name in CONSTANT_RULES: - return False - return not is_extra_feature(name) - - -def median(values: Sequence[float]) -> float | None: - items = [float(item) for item in values if item is not None] - return statistics.median(items) if items else None - - -# --------------------------------------------------------------------------- -# R-0 · feature recording provider (production-identical evidence + extras) -# --------------------------------------------------------------------------- - -@dataclass -class FeatureStore: - """(event_id, sample_date) -> HH:MM -> {rules, extras}.""" - - rows: dict[tuple[str, str], dict[str, dict[str, Any]]] = field(default_factory=dict) - - def put(self, event_id: str, sample: str, time: str, rules: Sequence[str], extras: Sequence[str]) -> None: - self.rows.setdefault((event_id, sample), {})[time] = { - "rules": sorted(set(rules)), - "extras": sorted(set(extras)), - } - - def samples_for(self, event_id: str) -> list[str]: - return sorted(sample for (item, sample) in self.rows if item == event_id) - - -def d60_charts(contexts: Sequence[dict[str, Any]]) -> dict[str, dict[str, Any] | None]: - out: dict[str, dict[str, Any] | None] = {} - for context in contexts: - stamp = context["candidate_at"].strftime("%H:%M") - try: - computed = varga.calc_all_vargas( - context["planet_longitudes"], float(context["ascendant_longitude"]), divisions=[60], - ) - out[stamp] = _varga_chart(computed, "D60") - except (KeyError, TypeError, ValueError): - out[stamp] = None - return out - - -def extra_features( - context: dict[str, Any], - target_houses: tuple[int, ...], - vimshottari: tuple[str, str, str], - d60: dict[str, Any] | None, -) -> list[str]: - feature = context.get("feature") if isinstance(context.get("feature"), dict) else {} - ascendant_index = int(context["ascendant_index"]) - kp_houses = ((feature.get("kp_cusps") or {}).get("houses") or {}) - target_sub = {str((kp_houses.get(str(h)) or {}).get("sub_lord") or "") for h in target_houses} - target_star = {str((kp_houses.get(str(h)) or {}).get("nakshatra_lord") or "") for h in target_houses} - asc_sub = str((kp_houses.get("1") or {}).get("sub_lord") or "") - out: list[str] = [] - for lord, label in zip(vimshottari, ("md", "ad", "pd")): - if lord in target_sub: - out.append(f"kp_target_cusp_sublord_is_vim_{label}") - if lord in target_star: - out.append(f"kp_target_cusp_starlord_is_vim_{label}") - if asc_sub and lord == asc_sub: - out.append(f"kp_asc_sublord_is_vim_{label}") - if isinstance(d60, dict) and _varga_house(d60, lord) in target_houses: - out.append(f"vim_{label}{D60_SUFFIX}") - for key, name in ( - ("pranapada_sign_index", "pranapada"), - ("hora_sign_index", "hora_lagna"), - ("ghati_sign_index", "ghati_lagna"), - ("bhava_sign_index", "bhava_lagna"), - ): - index = feature.get(key) - if isinstance(index, int) and _relative_house(index, ascendant_index) in target_houses: - out.append(f"{name}_in_target_house") - return out - - -def recorded_row( - request: dict[str, Any], - context: dict[str, Any], - *, - store: FeatureStore, - transit_cache: dict[tuple[Any, ...], dict[str, Any]], - d60_by_time: dict[str, dict[str, Any] | None], -) -> dict[str, Any]: - """Production `_candidate_row` for one legacy (single event, one date) request, plus extras.""" - candidate_at = context["candidate_at"] - chart = context["chart"] - planet_longitudes = context["planet_longitudes"] - ascendant_index = context["ascendant_index"] - arudha_padas = context["arudha_padas"] - varga_charts = context["varga_charts"] - moon_longitude = planet_longitudes["Moon"] - stamp = candidate_at.strftime("%H:%M") - policy = VargaPolicy(name="V0", window_minutes=0.0) - evidence: list[dict[str, Any]] = [] - missing: list[str] = [] - for event in request["events"]: - event_at = _event_datetime(event) - prefixes, target_houses = DOMAIN_CONFIG[event["domain"]] - selected = {prefix: varga_charts.get(prefix) for prefix in prefixes} - if any(item is None for item in selected.values()): - missing.extend(prefixes) - continue - try: - vimshottari = _active_vimshottari( - candidate_at.date().isoformat(), moon_longitude, event_at, context.get("vimshottari_timeline"), - ) - except (KeyError, TypeError, ValueError): - missing.append("Vimshottari_MD_AD_PD") - continue - try: - narayana = _active_narayana( - ascendant_index, planet_longitudes, candidate_at, event_at, context.get("narayana_periods"), - ) - except (KeyError, TypeError, ValueError): - missing.append("Narayana_MD_AD") - continue - if narayana[0] is None or narayana[1] is None: - missing.append("Narayana_MD_AD") - continue - row = score_event_with_policy( - candidate_time=stamp, event=event, natal_chart=chart, - varga_by_prefix={k: v for k, v in selected.items() if isinstance(v, dict)}, - vimshottari=vimshottari, narayana=narayana, arudha_padas=arudha_padas, policy=policy, - ) - weight = 1.0 # legacy requests carry precision "day"; the matrix applies the real weight - transit_rules = _controlled_transit_rules( - request, event, ascendant_index, target_houses, transit_cache, - ) - if transit_rules: - row["rule_ids"].extend(transit_rules) - row["points"] = round(row["points"] + 0.25 * len(transit_rules) * weight, 4) - av_rules, av_points = _ashtakavarga_auxiliary( - chart, ascendant_index, target_houses, context.get("ashtakavarga_result"), - ) - if av_rules: - row["rule_ids"].extend(av_rules) - row["points"] = round(row["points"] + av_points * weight, 4) - sb_rules, sb_points = _shadbala_verified_components_auxiliary( - chart, candidate_at.hour + candidate_at.minute / 60, vimshottari, context.get("shadbala_result"), - ) - if sb_rules: - row["rule_ids"].extend(sb_rules) - row["points"] = round(row["points"] + sb_points * weight, 4) - evidence.append(row) - store.put( - str(event["id"]), str(event["date"]), stamp, row["rule_ids"], - extra_features(context, target_houses, vimshottari, d60_by_time.get(stamp)), - ) - return { - "time": stamp, - "score": round(sum(item["points"] for item in evidence), 4), - "evidence": evidence, - "missing_layers": sorted(set( - missing + [layer for layer in context["feature"]["blocked_layers"] if layer not in OBSERVATION_ONLY_LAYERS] - )), - } - - -def make_recording_provider( - contexts: Sequence[dict[str, Any]], - store: FeatureStore, - d60_by_time: dict[str, dict[str, Any] | None], -) -> Callable[[dict[str, Any]], list[dict[str, Any]]]: - transit_cache: dict[tuple[Any, ...], dict[str, Any]] = {} - - def provider(request: dict[str, Any]) -> list[dict[str, Any]]: - return [ - recorded_row(request, context, store=store, transit_cache=transit_cache, d60_by_time=d60_by_time) - for context in contexts - ] - - return provider - - -def score_map(rows: Sequence[dict[str, Any]]) -> dict[str, float]: - return {str(row["time"])[:5]: float(row.get("score") or 0) for row in rows} - - -def reconcile_rows(production: Sequence[dict[str, Any]], research: Sequence[dict[str, Any]]) -> dict[str, Any]: - """Per-minute score and rule-id comparison. `changed == 0` is the R-0 gate.""" - prod = {str(r["time"])[:5]: r for r in production} - rese = {str(r["time"])[:5]: r for r in research} - changed: list[dict[str, Any]] = [] - for time, row in prod.items(): - other = rese.get(time) - if other is None: - changed.append({"time": time, "reason": "missing"}) - continue - if abs(float(row.get("score") or 0) - float(other.get("score") or 0)) > EPS: - changed.append({"time": time, "reason": "score", "production": row.get("score"), "research": other.get("score")}) - continue - prod_rules = { - (item["event_id"], tuple(sorted(item["rule_ids"]))) for item in row.get("evidence") or [] - } - rese_rules = { - (item["event_id"], tuple(sorted(item["rule_ids"]))) for item in other.get("evidence") or [] - } - if prod_rules != rese_rules: - changed.append({"time": time, "reason": "rule_ids"}) - return {"candidates": len(prod), "changed": len(changed), "details": changed[:5]} - - -# --------------------------------------------------------------------------- -# feature matrices and likelihood-ratio weights -# --------------------------------------------------------------------------- - -def event_feature_matrix( - store: FeatureStore, - event_id: str, - times: Sequence[str], - *, - include_extras: bool, -) -> dict[str, dict[str, float]]: - """HH:MM -> feature -> fraction of sample dates on which it fired.""" - samples = store.samples_for(event_id) - out: dict[str, dict[str, float]] = {} - if not samples: - return {time: {} for time in times} - for time in times: - counts: dict[str, int] = defaultdict(int) - for sample in samples: - cell = store.rows.get((event_id, sample), {}).get(time) - if not cell: - continue - names = [name for name in cell["rules"] if is_scoring_rule(name)] - if include_extras: - names += list(cell["extras"]) - for name in names: - counts[name] += 1 - out[time] = {name: round(count / len(samples), 6) for name, count in counts.items()} - return out - - -def training_event_ids(request: dict[str, Any]) -> list[str]: - holdout = holdout_event_ids(request["events"]) - return [str(e["id"]) for e in request["events"] if is_scoreable_event(e) and str(e["id"]) not in holdout] - - -@dataclass -class LRTable: - alpha: float - positives: float - negatives: float - present: dict[str, float] # log LR of the feature firing - absent: dict[str, float] # log LR of the feature not firing (naive Bayes complement) - support: dict[str, dict[str, float]] - - def weight(self, name: str, *, allow_negative: bool) -> tuple[float, float]: - """(present weight, absent weight) under the variant policy.""" - present = self.present.get(name, 0.0) - absent = self.absent.get(name, 0.0) - if allow_negative: - return present, absent - return max(present, 0.0), 0.0 - - -def estimate_lr(examples: Sequence[tuple[dict[str, float], bool]], *, alpha: float = LAPLACE_ALPHA) -> LRTable: - """Per-feature log likelihood ratios from (feature fractions, is-truth-cluster) examples.""" - positives = float(sum(1 for _values, truth in examples if truth)) - negatives = float(sum(1 for _values, truth in examples if not truth)) - names: set[str] = set() - pos_sum: dict[str, float] = defaultdict(float) - neg_sum: dict[str, float] = defaultdict(float) - for values, truth in examples: - for name, value in values.items(): - names.add(name) - if truth: - pos_sum[name] += float(value) - else: - neg_sum[name] += float(value) - present: dict[str, float] = {} - absent: dict[str, float] = {} - support: dict[str, dict[str, float]] = {} - for name in sorted(names): - p_pos = (pos_sum[name] + alpha) / (positives + 2 * alpha) - p_neg = (neg_sum[name] + alpha) / (negatives + 2 * alpha) - present[name] = round(math.log(p_pos / p_neg), 6) - absent[name] = round(math.log((1 - p_pos) / (1 - p_neg)), 6) - support[name] = { - "fires_truth": round(pos_sum[name], 4), - "fires_other": round(neg_sum[name], 4), - "p_truth": round(p_pos, 6), - "p_other": round(p_neg, 6), - } - return LRTable(alpha=alpha, positives=positives, negatives=negatives, present=present, absent=absent, support=support) - - -def bootstrap_lr( - per_case_examples: dict[str, list[tuple[dict[str, float], bool]]], - *, - resamples: int = 200, - seed: int = 20260929, - alpha: float = LAPLACE_ALPHA, -) -> dict[str, dict[str, float]]: - """Case-level bootstrap 5–95 % interval of the present-log-LR per feature.""" - ids = sorted(per_case_examples) - rng = Random(f"{seed}:lr-bootstrap") - draws: dict[str, list[float]] = defaultdict(list) - for _ in range(resamples): - picked = [rng.choice(ids) for _ in ids] - table = estimate_lr([ex for cid in picked for ex in per_case_examples[cid]], alpha=alpha) - for name, value in table.present.items(): - draws[name].append(value) - out: dict[str, dict[str, float]] = {} - for name, values in draws.items(): - ordered = sorted(values) - lo = ordered[int(0.05 * (len(ordered) - 1))] - hi = ordered[int(0.95 * (len(ordered) - 1))] - out[name] = {"p05": round(lo, 4), "p95": round(hi, 4), "draws": len(ordered)} - return out - - -def weighted_points(values: dict[str, float], table: LRTable, *, allow_negative: bool, universe: Sequence[str]) -> float: - total = 0.0 - for name in universe: - present, absent = table.weight(name, allow_negative=allow_negative) - x = float(values.get(name, 0.0)) - total += x * present + (1.0 - x) * absent - return total - - -def make_weighted_provider( - store: FeatureStore, - table: LRTable, - *, - variant: str, - scale: float = 1.0, - baseline_rows_by_sample: dict[tuple[str, str], dict[str, dict[str, Any]]] | None = None, -) -> Callable[[dict[str, Any]], list[dict[str, Any]]]: - """Row provider that scores each (event, sample date) as Σ feature weights. - - Production rule ids are kept on the evidence so the matrix's kind factor - and technique layers behave as in production; only the points change. - """ - include_extras, allow_negative = VARIANT_SPEC[variant] - universe = [ - name for name in sorted(table.present) - if (include_extras or not is_extra_feature(name)) - ] - - def provider(request: dict[str, Any]) -> list[dict[str, Any]]: - rows: list[dict[str, Any]] = [] - for event in request["events"]: - key = (str(event["id"]), str(event["date"])) - cells = store.rows.get(key, {}) - for time in sorted(cells, key=clock): - cell = cells[time] - names = [name for name in cell["rules"] if is_scoring_rule(name)] - if include_extras: - names += list(cell["extras"]) - values = {name: 1.0 for name in names} - points = round(scale * weighted_points(values, table, allow_negative=allow_negative, universe=universe), 4) - rows.append({ - "time": time, - "score": points, - "evidence": [{ - "event_id": event["id"], "domain": event["domain"], "candidate_time": time, - "rule_ids": list(cell["rules"]), "points": points, - }], - "missing_layers": [], - }) - return rows - - return provider - - -def loo_folds(case_ids: Sequence[str]) -> list[tuple[str, list[str]]]: - ids = list(case_ids) - return [(held, [other for other in ids if other != held]) for held in ids] - - -# --------------------------------------------------------------------------- -# truth labels, priors, replay -# --------------------------------------------------------------------------- - -def truth_cluster_times(contexts: Sequence[dict[str, Any]], true_time: str) -> list[str]: - for cluster in raw_signature_clusters(contexts): - times = [str(item)[:5] for item in cluster.get("times") or []] - if true_time[:5] in times: - return sorted(times, key=clock) - return [true_time[:5]] - - -def public_for(rows: Sequence[dict[str, Any]], contexts: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: - raw = raw_signature_clusters(contexts) - by_time = {stamp: row for row in rows if (stamp := hhmm(row.get("time")))} - merged, _trace = merge_adjacent_traced(raw, by_time) - public = public_from_clusters(merged, rows) - for row in public: - row["score"] = float(row.get("score") or 0) - return public - - -def percent_proportional(scores: dict[str, float]) -> dict[str, float]: - total = sum(max(value, 0.0) for value in scores.values()) - if total <= 0: - return {key: 0.0 for key in scores} - return {key: float(round(max(value, 0.0) / total * 100)) for key, value in scores.items()} - - -def softmax_probabilities(scores: dict[str, float], temperature: float = 1.0) -> dict[str, float]: - if not scores: - return {} - temp = float(temperature) if temperature and temperature > 0 else 1.0 - peak = max(scores.values()) - weights = {key: math.exp((value - peak) / temp) for key, value in scores.items()} - total = sum(weights.values()) - return {key: weight / total for key, weight in weights.items()} - - -def percent_softmax(scores: dict[str, float], temperature: float = 1.0) -> dict[str, float]: - return {key: float(round(p * 100)) for key, p in softmax_probabilities(scores, temperature).items()} - - -TEMPERATURE_GRID = (0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0) - - -def truth_mass(public: Sequence[dict[str, Any]], probabilities: dict[str, float], truth_times: Sequence[str]) -> float: - truth = {str(t)[:5] for t in truth_times} - mass = 0.0 - for row in public: - stamp = str(row["time"])[:5] - members = {str(t)[:5] for t in (row.get("cluster_times") or [stamp])} - if members & truth: - mass += probabilities.get(stamp, 0.0) - return mass - - -def fit_temperature( - training: Sequence[tuple[Sequence[dict[str, Any]], Sequence[str]]], - grid: Sequence[float] = TEMPERATURE_GRID, -) -> float: - """Platt-style single temperature: maximise Σ log P(truth cluster) on training cases only.""" - best_t, best_ll = 1.0, None - for temp in grid: - ll = 0.0 - for public, truth_times in training: - base = {str(r["time"])[:5]: float(r.get("score") or 0) for r in public} - mass = truth_mass(public, softmax_probabilities(base, temp), truth_times) - ll += math.log(max(mass, 1e-9)) - if best_ll is None or ll > best_ll + 1e-12: - best_t, best_ll = float(temp), ll - return best_t - - -def prior_for(public: Sequence[dict[str, Any]], *, mode: str, softmax: bool, temperature: float = 1.0) -> dict[str, float]: - base = {str(row["time"])[:5]: float(row.get("score") or 0) for row in public} - if mode == "raw": - return base - return percent_softmax(base, temperature) if softmax else percent_proportional(base) - - -def apply_scaled_answer( - scores: dict[str, float], - conflicts: dict[str, int], - eliminated: set[str], - probe: dict[str, Any], - answer: str, - candidate_times: Sequence[str], - factor: float, -) -> tuple[dict[str, float], dict[str, int], set[str]]: - """`apply_answer` at card strength (factor == 1); weaker evidence scales the - delta and never counts a strong conflict (so it can never eliminate).""" - if factor >= 1.0 - EPS: - return apply_answer(scores, conflicts, eliminated, probe, answer, candidate_times) - yes, no = outcome_groups(probe) - next_scores = dict(scores) - for time in candidate_times: - if time in eliminated: - continue - if time in yes: - raw = "support" - elif time in no: - raw = "conflict" - else: - raw = inherit_direction(time, yes, no) - if answer == "no": - raw = {"support": "conflict", "conflict": "support", "neutral": "neutral"}[raw] - next_scores[time] = next_scores.get(time, 0.0) + SCORE_DELTA[raw] * factor - return next_scores, dict(conflicts), set(eliminated) - - -def replay( - *, - public: Sequence[dict[str, Any]], - prior: dict[str, float], - probes: Sequence[dict[str, Any]], - true_time: str, - window_times: Sequence[str], - pre_answers: Sequence[tuple[dict[str, Any], str, float]] = (), - answers: Sequence[str | None] | None = None, -) -> dict[str, Any]: - """Prior → optional pre-answers (probe, answer, factor) → six probes answered from truth.""" - reps = [str(row["time"])[:5] for row in public] - scores = {time: float(prior.get(time, 0.0)) for time in reps} - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - for probe, answer, factor in pre_answers: - scores, conflicts, eliminated = apply_scaled_answer(scores, conflicts, eliminated, probe, answer, reps, factor) - asked = list(probes)[:ASK_COUNT] - given = list(answers) if answers is not None else [optimal_answer(p, true_time) for p in asked] - answered = 0 - for probe, answer in zip(asked, given): - if answer is None: - continue - answered += 1 - scores, conflicts, eliminated = apply_answer(scores, conflicts, eliminated, probe, answer, reps) - posterior = [{**row, "score": scores.get(str(row["time"])[:5], row.get("score") or 0)} for row in public] - valid = still_valid_public(posterior, scores, eliminated, lead=SEPARATION_LEAD) - delivery = delivery_from_public(valid) - alive = [row for row in posterior if str(row["time"])[:5] not in eliminated] - metrics = metrics_bundle( - public=alive, true_time=true_time, window_times=window_times, - delivery_times=delivery["times"], delivery_width=delivery["width"], independent=True, - entropy_scores=[scores.get(str(row["time"])[:5], 0.0) for row in alive], - ) - truth_eliminated = any( - true_time in (row.get("cluster_times") or [str(row.get("time"))[:5]]) and str(row["time"])[:5] in eliminated - for row in public - ) - return { - "top1": bool(metrics["top1_hit"]), - "coverage": bool(metrics["coverage"]), - "width": delivery["width"], - "tie": bool(metrics["tie"]), - "squeezed": bool(metrics["truth_squeezed"]), - "eliminated": len(eliminated), - "truth_eliminated": bool(truth_eliminated), - "questions": answered, - "entropy": round(shannon_entropy(max(s, 0.0) for t, s in scores.items() if t not in eliminated), 4), - } - - -def engine_top1(public: Sequence[dict[str, Any]], true_time: str) -> bool: - from scripts.research.cluster_width_lib import top1_from_public - return bool(top1_from_public(public, true_time)) - - -def within_case_range(rows: Sequence[dict[str, Any]]) -> float: - scores = [float(row.get("score") or 0) for row in rows] - return (max(scores) - min(scores)) if scores else 0.0 - - -def summarize(rows: Sequence[dict[str, Any]]) -> dict[str, Any]: - """Same keys as precision_gate_sweep.summarize so `gate_verdict` can read it.""" - if not rows: - return {"n": 0, "top1": None, "coverage": None, "width_median": None, "tie": None, "squeezed": 0, - "engine_top1": None, "refresh_mean": 0.0, "entropy": None, "truth_eliminated": 0} - n = len(rows) - return { - "n": n, - "top1": round(sum(1 for r in rows if r.get("top1")) / n, 4), - "coverage": round(sum(1 for r in rows if r.get("coverage")) / n, 4), - "width_median": median([r.get("width") for r in rows]), - "tie": round(sum(1 for r in rows if r.get("tie")) / n, 4), - "squeezed": sum(1 for r in rows if r.get("squeezed")), - "engine_top1": round(sum(1 for r in rows if r.get("engine_top1")) / n, 4), - "refresh_mean": 0.0, - "entropy": round(sum(float(r.get("entropy") or 0) for r in rows) / n, 4), - "truth_eliminated": sum(1 for r in rows if r.get("truth_eliminated")), - } - - -# --------------------------------------------------------------------------- -# probes on representatives (typed-event convention), absence, precision follow-up -# --------------------------------------------------------------------------- - -def production_probes(request: dict[str, Any], built: dict[str, Any], times: Sequence[str], true_time: str) -> list[dict[str, Any]]: - payload = {**request, "refresh_probes": False, "asked_probe_keys": []} - return event_probes.discriminating_event_probes( - payload, built, scan=window_scan(built), candidate_times=list(times), - representative_time=true_time, today=TODAY, - ) - - -@dataclass -class Representatives: - reps: list[dict[str, Any]] - clusters: list[dict[str, Any]] - set_version: str - - -def representatives_for(contexts: Sequence[dict[str, Any]]) -> Representatives: - full = [item for item in contexts if event_probes._context_time(item)] - full.sort(key=lambda item: event_probes._clock(str(event_probes._context_time(item)))) - clusters = cluster_contexts_by_signature(full) - reps = [c["representative"] for c in clusters if event_probes._scoreable(c["representative"])] - if len(reps) < 2: - reps = [item for item in full if event_probes._scoreable(item)] - version = event_probes.candidate_set_version([c["times"] for c in clusters]) - return Representatives(reps=reps, clusters=clusters, set_version=version) - - -def split_probe( - representatives: Representatives, - *, - birth_date: str, - domain: str, - year: int, - month: int | None, - source: str, -) -> dict[str, Any] | None: - canonical = event_probes.canonical_domain(domain) - if canonical not in event_probes.DOMAIN_CATALOG: - return None - return event_probes._evaluate_contexts( - representatives.reps, birth_date=birth_date, domain=canonical, year=year, month=month, - source=source, clusters=representatives.clusters, set_version=representatives.set_version, - ) - - -def event_year(event: dict[str, Any]) -> int | None: - raw = str(event.get("date_start") or event.get("date") or "") - return int(raw[:4]) if raw[:4].isdigit() else None - - -def event_month(event: dict[str, Any]) -> int | None: - raw = str(event.get("date_start") or event.get("date") or "") - return int(raw[5:7]) if len(raw) >= 7 and raw[4] == "-" else None - - -def absent_years(events: Sequence[dict[str, Any]]) -> dict[str, list[int]]: - """Per domain: years strictly inside the span of that domain's dated events with no event.""" - years: dict[str, set[int]] = defaultdict(set) - for event in events: - year = event_year(event) - if year is None: - continue - years[str(event.get("domain") or "")].add(year) - out: dict[str, list[int]] = {} - for domain, known in years.items(): - if len(known) < 2: - continue - lo, hi = min(known), max(known) - gaps = [year for year in range(lo + 1, hi) if year not in known] - if gaps: - out[domain] = gaps - return dict(sorted(out.items())) - - -def drop_events(events: Sequence[dict[str, Any]], count: int, *, seed: str) -> list[dict[str, Any]]: - rng = Random(seed) - if count <= 0 or count >= len(events): - return list(events) - dropped = set(rng.sample(range(len(events)), count)) - return [event for index, event in enumerate(events) if index not in dropped] - - -def degrade_to_year(events: Sequence[dict[str, Any]]) -> list[dict[str, Any]]: - """The 'spoken' form of a case: every day/month event becomes year precision.""" - out = [] - for event in events: - item = dict(event) - if str(item.get("precision")) in {"day", "month"}: - item["precision"] = "year" - item["date"] = str(item.get("date") or "")[:4] - out.append(item) - return out - - -def upgrade_to_month(events: Sequence[dict[str, Any]], event_ids: set[str], originals: dict[str, dict[str, Any]]) -> list[dict[str, Any]]: - out = [] - for event in events: - item = dict(event) - original = originals.get(str(item.get("id"))) - if str(item.get("id")) in event_ids and original is not None and len(str(original.get("date") or "")) >= 7: - item["precision"] = "month" - item["date"] = str(original["date"])[:7] - out.append(item) - return out - - -def shift_day_events_by_months(events: Sequence[dict[str, Any]], *, seed: str, choices: Sequence[int] = (-3, -2, -1, 1, 2, 3)) -> list[dict[str, Any]]: - rng = Random(seed) - out = [] - for event in events: - item = dict(event) - raw = str(item.get("date") or "") - if str(item.get("precision")) == "day" and len(raw) >= 10: - year, month, day = int(raw[:4]), int(raw[5:7]), int(raw[8:10]) - index = year * 12 + (month - 1) + rng.choice(list(choices)) - new_year, new_month = divmod(index, 12) - item["date"] = f"{new_year:04d}-{new_month + 1:02d}-{min(day, 28):02d}" - item["shift_months"] = index - (year * 12 + month - 1) - out.append(item) - return out - - -def calibration_bins(points: Sequence[tuple[float, bool]], edges: Sequence[float] = (0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 1.0001)) -> list[dict[str, Any]]: - out = [] - for lo, hi in zip(edges, edges[1:]): - inside = [(p, t) for p, t in points if lo <= p < hi] - out.append({ - "bin": f"[{lo:.2f},{min(hi, 1.0):.2f})", - "n": len(inside), - "predicted_mean": round(sum(p for p, _ in inside) / len(inside), 4) if inside else None, - "observed_rate": round(sum(1 for _, t in inside if t) / len(inside), 4) if inside else None, - }) - return out - - -__all__ = [name for name in dir() if not name.startswith("__")] diff --git a/scripts/research/sealed_holdout_rerun.py b/scripts/research/sealed_holdout_rerun.py deleted file mode 100644 index 22d939c59..000000000 --- a/scripts/research/sealed_holdout_rerun.py +++ /dev/null @@ -1,271 +0,0 @@ -#!/usr/bin/env python3 -"""Freeze and replay the exposed v3 corpus; never claim a fresh blind holdout.""" -from __future__ import annotations - -import argparse -import hashlib -import json -import sys -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import AYANAMSA, NODE_MODE -from scripts.minute_rectification_blind_eval import ( - _candidate_moments, _clock_distance, _opaque_winner, _request, - implementation_sha256, summarize_trials, -) -from scripts.minute_rectification_fact_blind_eval_v4 import _would_confirm -from scripts.minute_rectification_fact_ranker_v4 import ( - ALGORITHM_VERSION, rank_fact_rows, score_fact_ranker_v4, -) -from scripts.minute_rectification_feature_facts_v4 import build_feature_fact_rows -from scripts.minute_rectification_holdout_validator import validate - -DATASET = ROOT / "references/real_case_calibration/minute_rectification_holdout_v3.json" -# 原值: docs/research/sealed_holdout_rerun_upstream_sync8_2026_10_18.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_upstream_sync9b_2026_10_28.{freeze.json,json} -# 原因: sync9b(BUG-1494~1495)改了 scripts/varga.py,它在扩展身份里;切盘输出不变,ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_upstream_sync9b_2026_10_28.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_d60_mapping_2026_10_29.{freeze.json,json} -# 原因: BUG-1500 修正生产 D60 映射,scripts/varga.py 变了(在扩展身份里);20 条回放不变,ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_d60_mapping_2026_10_29.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_data_audit_2026_11_04.{freeze.json,json} -# 原因: 数据核对 BUG-1545(narayana_dasha.py、active_rectification_event_engine.py)与 BUG-1546(shadbala.py)改了冻结身份文件,ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_data_audit_2026_11_04.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_moon_paksha_2026_11_04.{freeze.json,json} -# 原因: BUG-1557 月亮 Paksha 口径(scripts/shadbala.py)改了冻结身份文件,ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_moon_paksha_2026_11_04.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_audit_wave2_2026_11_04.{freeze.json,json} -# 原因: 数据核对第二波合并(BUG-1560 / BUG-1561 varga.py、divisional_charts_extended.py;BUG-1566 / BUG-1567 jaimini.py;BUG-1270 / BUG-1576 shadbala.py)改了冻结身份文件,ERR-110 在合并后的代码上另存新记录;各分支自己的 audit_g / audit_h / audit_j 记录只对各自分支成立,作为中间记录原样保留 -# 原值: docs/research/sealed_holdout_rerun_audit_wave2_2026_11_04.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_d30_venus_2026_11_04.{freeze.json,json} -# 原因: 产品 2026-11-04 决定按出处改算法:BUG-1560 varga.py 偶数星座 D30 按 BPHS 第 6 章、BUG-1570 白羊 / 天蝎上升金星判功能凶(BPHS 34.20 / 34.35),校正身份升到 scoring-13;冻结身份文件变了且回放结果变了,ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_d30_venus_2026_11_04.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_astrologer_166_2026_11_04.{freeze.json,json} -# 原因: #166 占星师裁定(BUG-1581~1589,产品 2026-11-04 决定交付)改了 shadbala.py、jaimini.py、varga.py、divisional_charts_extended.py,校正身份升到 scoring-14;ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_astrologer_166_2026_11_04.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_astrologer_166b_2026_11_04.{freeze.json,json} -# 原因: #166 第二批(BUG-1590~1598)改了 functional_benefics.py、jaimini.py、narayana_dasha.py、shadbala.py、varga.py,校正身份升到 scoring-15;ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_astrologer_166b_2026_11_04.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_astrologer_166c_2026_11_05.{freeze.json,json} -# 原因: #166 占星师 2026-11-05 答复(BUG-1622~1626)只改了 shadbala.py 的标签、注释与共用的水星规则函数(数值不变),校正身份仍是 scoring-15;ERR-110 另存新记录 -# 原值: docs/research/sealed_holdout_rerun_astrologer_166c_2026_11_05.{freeze.json,json} -# 新值: docs/research/sealed_holdout_rerun_astrologer_166d_2026_11_05.{freeze.json,json} -# 原因: BUG-1622~1626 改号(另一会话已用 BUG-1613)改了 shadbala.py 与本脚本的注释,冻结身份变了,数值不变,仍 scoring-15;ERR-110 另存新记录 -FREEZE = ROOT / "docs/research/sealed_holdout_rerun_astrologer_166d_2026_11_05.freeze.json" -REPORT = ROOT / "docs/research/sealed_holdout_rerun_astrologer_166d_2026_11_05.json" -LEGACY_REPORT = ROOT / "docs/research/sealed_holdout_rerun_2026_09_20.json" -ARCHIVE = ROOT / "docs/research/history/rectification_pre_cross_midnight_2026_09_20" -PRODUCTION_FILES = [ - "scripts/rectification/scoring_service.py", - "scripts/rectification/dasha_transition_proximity.py", - "scripts/rectification/candidate_contrast.py", - "scripts/rectification/case_holdout.py", - "scripts/rectification/contracts.py", - "scripts/rectification/event_probes.py", - "scripts/rectification/candidate_window.py", - "scripts/rectification/decision_policy.py", - "scripts/rectification/refinement_packet.py", - "scripts/rectification/api_service.py", - # BUG-1181: functional roles feed *_functional_*_auxiliary scoring rules; - # 57782aea changed scores without tripping this identity. - "scripts/functional_benefics.py", -] -RESEARCH_FILES = [ - "scripts/research/reported_offset_sweep.py", - "scripts/research/cluster_width_lib.py", - "scripts/research/probe_supply_after_six.py", - "scripts/research/sealed_holdout_rerun.py", - "scripts/minute_rectification_blind_eval.py", - "scripts/minute_rectification_fact_blind_eval_v4.py", - "scripts/minute_rectification_holdout_validator.py", -] - - -def file_sha256(path: Path) -> str: - return hashlib.sha256(path.read_bytes()).hexdigest() - - -def opaque_order(benchmark_id: str, case_id: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Extend the existing opaque winner to a total, truth-independent ranking.""" - return sorted(rows, key=lambda row: ( - -row["score"], - hashlib.sha256(f"{benchmark_id}:{case_id}:{row['time']}".encode()).hexdigest(), - )) - - -def implementation_identity(dataset: Path = DATASET) -> dict[str, Any]: - """Bind legacy scorer, changed production files and both replay adapters. - - The production identity is contextual for the shadow rerun, not a claim - that the shadow scorer executes transition proximity. These are explicit - audited file sets, not a transitive dependency or environment lock. - """ - legacy_files = json.loads(dataset.read_text(encoding="utf-8"))["frozen_scoring"]["files"] - production_files = sorted(set(legacy_files + PRODUCTION_FILES)) - return { - "historical_artifacts_manifest_sha256": file_sha256(ARCHIVE / "manifest.json"), - "production_scoring_files": production_files, - "production_scoring_sha256": implementation_sha256(production_files), - "research_files": RESEARCH_FILES, - "research_implementation_sha256": implementation_sha256(RESEARCH_FILES), - "file_sha256": {path: file_sha256(ROOT / path) for path in sorted(set(production_files + RESEARCH_FILES))}, - "hash_scope": "explicit_identity_file_sets_not_a_transitive_dependency_lock", - } - - -def verify_frozen_record(frozen: dict[str, Any], actual: dict[str, Any]) -> None: - for key in actual: - if key != "frozen_at_utc" and actual[key] != frozen.get(key): - raise ValueError(f"frozen_record_mismatch:{key}") - if set(frozen) != set(actual): - raise ValueError("frozen_record_mismatch:keys") - - -def historical_comparison(report_path: Path, trials: list[dict[str, Any]], keys: tuple[str, ...]) -> dict[str, Any]: - """Keep every before/after row, including unchanged rows and failures.""" - history_path = ARCHIVE / report_path.relative_to(ROOT) - archive_manifest = json.loads((ARCHIVE / "manifest.json").read_text(encoding="utf-8")) - entry = next(item for item in archive_manifest["files"] if item["source_path"] == report_path.relative_to(ROOT).as_posix()) - if file_sha256(history_path) != entry["sha256"]: - raise ValueError("historical_report_bytes_changed") - previous = json.loads(history_path.read_text(encoding="utf-8")) - identity = lambda row: tuple(row[key] for key in keys) - old = {identity(row): row for row in previous["trials"]} - new = {identity(row): row for row in trials} - if len(old) != len(previous["trials"]) or len(new) != len(trials) or old.keys() != new.keys(): - raise ValueError("historical_comparison_trial_identity_mismatch") - comparisons = [{ - **{key: row[key] for key in keys}, - "before": old[identity(row)], "after": row, - "changed_fields": sorted(key for key in set(row) | set(old[identity(row)]) - if row.get(key) != old[identity(row)].get(key)), - } for row in trials] - return { - "source_report": history_path.relative_to(ROOT).as_posix(), - "source_report_sha256": file_sha256(history_path), - "reason": "BUG-981 new production identity and native single-matrix sweep; prior grouped sweep/shadow metrics not presumed incorrect", - "trial_count": len(comparisons), - "changed_trial_count": sum(bool(row["changed_fields"]) for row in comparisons), - "trials": comparisons, - } - - -def freeze_record(dataset: Path = DATASET) -> dict[str, Any]: - manifest = json.loads(dataset.read_text(encoding="utf-8")) - files = manifest["frozen_scoring"]["files"] - return { - "record_version": "exposed-v3-fixed-protocol-cross-midnight-rerun-v2", - "extended_identity": implementation_identity(dataset), - "production_identity_scope": "context_only_shadow_scorer_does_not_call_transition_proximity", - "frozen_at_utc": datetime.now(timezone.utc).isoformat(), - "dataset_path": dataset.relative_to(ROOT).as_posix(), - "dataset_sha256": file_sha256(dataset), - "algorithm_version": ALGORITHM_VERSION, - "implementation_sha256": implementation_sha256(files), - "files": files, - "historical_frozen_sha256": manifest["frozen_scoring"]["implementation_sha256"], - "evaluator_sha256": file_sha256(Path(__file__)), - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "candidate_radius_minutes": sorted({case["candidate_radius_minutes"] for case in manifest["cases"]}), - "minute_step": 1, - "release_metrics": manifest["release_metrics"], - "results_previously_seen": True, - "official_valid_independent_blind": False, - "must_not_use_for_tuning": True, - "tie_breaker": manifest["frozen_scoring"]["tie_breaker"], - "metric_rank_definition": "competition_rank_1_plus_strictly_higher_scores_legacy_protocol", - "extra_metric_rank_definition": "score_desc_then_existing_opaque_sha256_total_order", - } - - -def run(freeze_path: Path = FREEZE, dataset: Path = DATASET) -> dict[str, Any]: - frozen = json.loads(freeze_path.read_text(encoding="utf-8")) - actual = freeze_record(dataset) - verify_frozen_record(frozen, actual) - replay_started_at = datetime.now(timezone.utc).isoformat() - manifest = json.loads(dataset.read_text(encoding="utf-8")) - validation = validate(dataset) - invalid = validation["invalid_cases"] - trials = [] - for index, case in enumerate(manifest["cases"], 1): - if case["case_id"] in invalid: - continue - request = _request(case, case["events"]) - candidates = _candidate_moments(case) - facts = build_feature_fact_rows(request, candidates=candidates) - rows, _ = rank_fact_rows(facts, request["events"]) - result = score_fact_ranker_v4(facts, request["events"]) - predicted = _opaque_winner(manifest["benchmark_id"], case["case_id"], rows) - ordered = opaque_order(manifest["benchmark_id"], case["case_id"], rows) - sparse_request = _request(case, case["events"][:1]) - sparse_facts = build_feature_fact_rows(sparse_request, candidates=candidates) - sparse_result = score_fact_ranker_v4(sparse_facts, sparse_request["events"]) - # Truth is revealed only after both full and sparse ranking/decisions. - truth = case["birth"]["time"] - truth_score = next(row["score"] for row in rows if row["time"] == truth) - would_confirm = _would_confirm(result) - trials.append({ - "case_ordinal": index, - "candidate_count": len(rows), - "event_count": len(request["events"]), - "true_rank": 1 + sum(row["score"] > truth_score for row in rows), - "opaque_true_rank": next(i for i, row in enumerate(ordered, 1) if row["time"] == truth), - "minute_error": _clock_distance(predicted, truth), - "would_confirm": would_confirm, - "false_confirmation": would_confirm and predicted != truth, - "insufficient_evidence_rejected": not _would_confirm(sparse_result), - "full_trial_reasons": result["reasons"], - "sparse_trial_reasons": sparse_result["reasons"], - }) - verify_frozen_record(frozen, freeze_record(dataset)) - aggregate = summarize_trials(trials, manifest["release_metrics"]) - count = len(trials) - return { - "scope": "fixed_protocol_previously_exposed_v3_rerun", - "replay_started_at_utc": replay_started_at, - "replay_finished_at_utc": datetime.now(timezone.utc).isoformat(), - "historical_comparison": historical_comparison(LEGACY_REPORT, trials, ("case_ordinal",)), - "evaluated_on": datetime.now(timezone.utc).date().isoformat(), - "frozen_record": frozen, - "implementation_hash_matches_at_replay": True, - "dataset_hash_matches_at_replay": True, - "source_audit_status": manifest["source_audit_status"], - "validation_status": validation["status"], - "valid_public_aa_cases": validation["valid_public_aa_cases"], - "excluded_cases": invalid, - "trial_count": count, - "trials": trials, - **aggregate, - "opaque_exact_top_1_rate": sum(row["opaque_true_rank"] == 1 for row in trials) / count if count else None, - "opaque_exact_top_3_rate": sum(row["opaque_true_rank"] <= 3 for row in trials) / count if count else None, - "official_valid_independent_blind": False, - "official_blind_trial_count": 0, - "is_blind_evaluation": False, - "truth_hidden_from_ranker": True, - "results_previously_seen": True, - "verified_minute_claim_allowed": False, - "status": "blocked_independent_blind_evidence", - "boundary": "Three-event low-information protocol, not a mathematical accuracy lower bound and not representative of real sessions. Historical v3/v4 exposure cannot be undone by freezing today's scorer. No tuning or release claims.", - } - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--freeze", action="store_true", help="Create a new record before replay; never overwrite an existing record") - parser.add_argument("--freeze-path", type=Path, default=FREEZE) - parser.add_argument("--json", action="store_true") - args = parser.parse_args() - if args.freeze: - with args.freeze_path.open("x", encoding="utf-8", newline="\n") as handle: - json.dump(freeze_record(), handle, ensure_ascii=False, indent=2) - handle.write("\n") - print(args.freeze_path.relative_to(ROOT).as_posix()) - else: - print(json.dumps(run(args.freeze_path), ensure_ascii=False, indent=2)) diff --git a/scripts/research/typed_event_as_probe.py b/scripts/research/typed_event_as_probe.py deleted file mode 100644 index b00c3cada..000000000 --- a/scripts/research/typed_event_as_probe.py +++ /dev/null @@ -1,391 +0,0 @@ -#!/usr/bin/env python3 -"""Offline research for TASK-rectification-typed-event-scoring-research-20260929. - -Question: should a dated typed event ("I changed jobs in 2019-10") move the -candidate scores the same way an answered existence probe does? - -Today an answered dated probe moves every candidate by ±2 through the -Vimshottari/Narayana boundary-month split (`event_probes._evaluate_contexts`), -while a typed event only reaches the engine prior, and the frontend skips -`classified_from === "evidence"` yes answers (`core/build-state.ts`). - -This script replays the v4 open holdout (20 public Rodden-AA cases, 7–8 events -each; 59 day-precision and 84 year-precision events, no month-precision) with -the same six-probe replay used by the 09-14 / 09-16 / 09-26 studies, and adds -research arms: - -* ``B0`` baseline: prior, then the first six public probes answered from truth. -* ``R1d`` each training typed event with day precision is scored as an answered - ``yes`` probe (split from `_evaluate_contexts` at that year/month), - then the same six probes. -* ``R1y`` as R1d, plus year-precision events scored with the year-level split - (`_evaluate_contexts(month=None)`, the existing year probe path). -* ``R2k`` R1 with k ∈ {1, 2} typed day events moved by ±1–3 months (seeded); - reports how often the truth is pushed out of the delivered range. -* ``R3`` `_existence_blocked_years` narrowed to "same domain, same year" - (probe supply count), alone and combined with R1d. - -Two prior scales are reported: ``raw`` (engine row score, the research-lib -convention of the earlier studies) and ``percent`` (proportional percent over -public representatives, the production `relative_support` convention). - -Nothing here changes a production default. Module attributes are patched for -one call and restored; the end of `main` asserts they are the originals. -This is an open-set replay, not a blind test: numbers are not accuracy. -""" - -from __future__ import annotations - -import argparse -import json -import random -import statistics -import sys -from contextlib import contextmanager -from datetime import date -from pathlib import Path -from typing import Any, Iterator, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -import scripts.rectification.event_probes as event_probes # noqa: E402 -from scripts.active_rectification_event_engine import compute_candidate_static_contexts # noqa: E402 -from scripts.rectification.candidate_contrast import cluster_contexts_by_signature # noqa: E402 -from scripts.rectification.case_holdout import holdout_event_ids # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, -) -from scripts.research.cluster_width_lib import ( # noqa: E402 - SEPARATION_LEAD, - delivery_from_public, - merge_adjacent_traced, - public_from_clusters, - raw_signature_clusters, - still_valid_public, -) -from scripts.research.guided_collect_holdout_replay import ( # noqa: E402 - TODAY, - _hhmm, - _minutes, - load_cases, - precision_gate, -) -from scripts.research.minute_resolution_sweep import scoring_request_for # noqa: E402 -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - apply_answer, - optimal_answer, - top1_hit, -) - -RADII = (10, 30, 60) -PRIORS = ("raw", "percent") -REPORT_JSON = ROOT / "docs" / "research" / "rectification_typed_event_scoring_2026_09_29.json" -SHIFT_SEED = 20260929 -SHIFT_REPEATS = 10 -TYPED_SOURCE = "typed_event_research" - -ORIGINAL_BLOCKED_YEARS = event_probes._existence_blocked_years - - -@contextmanager -def narrowed_blocking() -> Iterator[None]: - """R3: an already-known year blocks only itself in the same domain.""" - event_probes._existence_blocked_years = lambda _domain, known_years: set(known_years) - try: - yield - finally: - event_probes._existence_blocked_years = ORIGINAL_BLOCKED_YEARS - - -def _percent(scores: dict[str, float]) -> dict[str, float]: - total = sum(max(value, 0.0) for value in scores.values()) - if total <= 0: - return {key: 0.0 for key in scores} - # Integer percent like `_relative_support_proportional` (largest remainder is not - # needed for ranking; plain rounding keeps the research copy independent). - return {key: float(round(max(value, 0.0) / total * 100)) for key, value in scores.items()} - - -def _event_month(event: dict[str, Any]) -> int | None: - raw = str(event.get("date_start") or "") - return int(raw[5:7]) if len(raw) >= 7 and raw[4] == "-" else None - - -def _event_year(event: dict[str, Any]) -> int | None: - raw = str(event.get("date_start") or "") - return int(raw[:4]) if raw[:4].isdigit() else None - - -def _shift_month(event: dict[str, Any], months: int) -> dict[str, Any]: - year, month = _event_year(event), _event_month(event) - if year is None or month is None: - return event - index = year * 12 + (month - 1) + months - new_year, new_month = divmod(index, 12) - stamp = f"{new_year:04d}-{new_month + 1:02d}-15" - return {**event, "date_start": stamp, "date_end": stamp} - - -def typed_event_probes( - request: dict[str, Any], - contexts: Sequence[dict[str, Any]], - *, - include_year: bool, - events: Sequence[dict[str, Any]] | None = None, -) -> tuple[list[dict[str, Any]], dict[str, int]]: - """Score each training typed event through the probe split, answered ``yes``.""" - full = [item for item in contexts if event_probes._context_time(item)] - full.sort(key=lambda item: event_probes._clock(str(event_probes._context_time(item)))) - clusters = cluster_contexts_by_signature(full) - reps = [cluster["representative"] for cluster in clusters if event_probes._scoreable(cluster["representative"])] - if len(reps) < 2: - reps = [item for item in full if event_probes._scoreable(item)] - set_version = event_probes.candidate_set_version([cluster["times"] for cluster in clusters]) - source_events = list(events if events is not None else request["events"]) - holdout = set(holdout_event_ids(request["events"])) - stats = {"training_day": 0, "training_year": 0, "split_day": 0, "split_year": 0} - rows: list[dict[str, Any]] = [] - for event in source_events: - if str(event.get("id")) in holdout: - continue - domain = event_probes.canonical_domain(event.get("domain")) - if domain not in event_probes.DOMAIN_CATALOG: - continue - precision = str(event.get("precision") or "") - year = _event_year(event) - if year is None: - continue - if precision in {"day", "month"}: - stats["training_day"] += 1 - month = _event_month(event) - key = "split_day" - elif precision == "year" and include_year: - stats["training_year"] += 1 - month = None - key = "split_year" - else: - continue - row = event_probes._evaluate_contexts( - reps, - birth_date=str(request["birth_date"]), - domain=domain, - year=year, - month=month, - source=TYPED_SOURCE, - clusters=clusters, - set_version=set_version, - ) - if row is None: - continue - stats[key] += 1 - rows.append(row) - return rows, stats - - -def replay( - *, - rows: Sequence[dict[str, Any]], - contexts: Sequence[dict[str, Any]], - typed: Sequence[dict[str, Any]], - probes: Sequence[dict[str, Any]], - true_time: str, - prior_mode: str, -) -> dict[str, Any]: - raw = raw_signature_clusters(contexts) - by_time = {stamp: row for row in rows if (stamp := _hhmm(row.get("time")))} - merged, _trace = merge_adjacent_traced(raw, by_time) - public = public_from_clusters(merged, rows) - reps = [str(row["time"])[:5] for row in public] - base = {stamp: float(row.get("score") or 0) for row in public if (stamp := _hhmm(row.get("time")))} - scores = _percent(base) if prior_mode == "percent" else dict(base) - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - for probe in typed: - scores, conflicts, eliminated = apply_answer(scores, conflicts, eliminated, probe, "yes", reps) - asked = 0 - for probe in list(probes)[:ASK_COUNT]: - answer = optimal_answer(probe, true_time) - if answer is None: - continue - asked += 1 - scores, conflicts, eliminated = apply_answer(scores, conflicts, eliminated, probe, answer, reps) - posterior = [{**row, "score": scores.get(str(row["time"])[:5], row.get("score") or 0)} for row in public] - valid = still_valid_public(posterior, scores, eliminated, lead=SEPARATION_LEAD) - delivery = delivery_from_public(valid) - start, end = delivery.get("start"), delivery.get("end") - inside = start is not None and end is not None and _minutes(start) <= _minutes(true_time) <= _minutes(end) - active = [time for time in reps if time not in eliminated] - gate = precision_gate(valid, scores) - return { - "width": delivery.get("width"), - "truth_in_range": bool(inside), - "top1": bool(top1_hit(scores, active, true_time, merged)), - "tied": bool(gate["tied_for_first"]), - "questions": asked, - "typed_scored": len(typed), - "probe_supply": len(probes), - } - - -def evaluate_case(case: dict[str, Any], radius: int) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - request = scoring_request_for(case, radius) - contexts = compute_candidate_static_contexts(request) - built = build_event_contribution_matrix(request, static_contexts=contexts) - rows = score_from_matrix(request, built) - times = [stamp for row in rows if (stamp := _hhmm(row.get("time")))] - - def probes_now() -> list[dict[str, Any]]: - return event_probes.discriminating_event_probes( - {**request, "refresh_probes": False, "asked_probe_keys": []}, built, - scan=window_scan(built), candidate_times=times, representative_time=true_time, today=TODAY, - ) - - probes = probes_now() - with narrowed_blocking(): - probes_narrow = probes_now() - assert event_probes._existence_blocked_years is ORIGINAL_BLOCKED_YEARS - - typed_day, stats = typed_event_probes(request, contexts, include_year=False) - typed_all, stats_all = typed_event_probes(request, contexts, include_year=True) - - rng = random.Random(f"{SHIFT_SEED}:{case.get('case_id')}:{radius}") - holdout = set(holdout_event_ids(request["events"])) - day_events = [ - index for index, event in enumerate(request["events"]) - if str(event.get("precision")) in {"day", "month"} and str(event.get("id")) not in holdout - ] - shifted: dict[str, list[dict[str, Any]]] = {"1": [], "2": []} - for k in (1, 2): - if len(day_events) < k: - continue - for _ in range(SHIFT_REPEATS): - picks = rng.sample(day_events, k) - events = [ - _shift_month(event, rng.choice((-3, -2, -1, 1, 2, 3))) if index in picks else event - for index, event in enumerate(request["events"]) - ] - moved, _ = typed_event_probes(request, contexts, include_year=False, events=events) - shifted[str(k)].append({"typed": moved}) - - out: dict[str, Any] = {"case_id": case.get("case_id"), "radius": radius, "typed_stats": {**stats, **{ - "training_year": stats_all["training_year"], "split_year": stats_all["split_year"]}}, - "probe_supply": len(probes), "probe_supply_narrow": len(probes_narrow), - "asked_keys_changed_narrow": [p["semantic_key"] for p in probes[:ASK_COUNT]] - != [p["semantic_key"] for p in probes_narrow[:ASK_COUNT]], - "arms": {}} - for prior in PRIORS: - def run(typed: Sequence[dict[str, Any]], pool: Sequence[dict[str, Any]]) -> dict[str, Any]: - return replay(rows=rows, contexts=contexts, typed=typed, probes=pool, true_time=true_time, prior_mode=prior) - - arms = { - "B0": run([], probes), - "R1d": run(typed_day, probes), - "R1y": run(typed_all, probes), - "R3": run([], probes_narrow), - "R3+R1d": run(typed_day, probes_narrow), - } - for k, trials in shifted.items(): - results = [run(item["typed"], probes) for item in trials] - if results: - arms[f"R2k{k}"] = { - "trials": len(results), - "truth_out": sum(1 for row in results if not row["truth_in_range"]), - "top1": sum(1 for row in results if row["top1"]), - "median_width": statistics.median(row["width"] for row in results if row["width"] is not None), - } - out["arms"][prior] = arms - return out - - -def summarize(rows: Sequence[dict[str, Any]], prior: str, radius: int, arm: str) -> dict[str, Any]: - subset = [row["arms"][prior][arm] for row in rows if row.get("radius") == radius and not row.get("error") - and arm in row["arms"][prior]] - n = len(subset) - if not n: - return {"n": 0} - if arm.startswith("R2k"): - trials = sum(item["trials"] for item in subset) - return { - "n": n, - "trials": trials, - "truth_out_rate": round(sum(item["truth_out"] for item in subset) / trials, 4), - "cases_with_truth_out": sum(1 for item in subset if item["truth_out"] > 0), - "top1_rate": round(sum(item["top1"] for item in subset) / trials, 4), - "median_width": statistics.median(item["median_width"] for item in subset), - } - return { - "n": n, - "top1": round(sum(item["top1"] for item in subset) / n, 4), - "truth_in_range": round(sum(item["truth_in_range"] for item in subset) / n, 4), - "median_width": statistics.median(item["width"] for item in subset if item["width"] is not None), - "tie_rate": round(sum(item["tied"] for item in subset) / n, 4), - "mean_questions": round(statistics.mean(item["questions"] for item in subset), 2), - "mean_typed_scored": round(statistics.mean(item["typed_scored"] for item in subset), 2), - "mean_probe_supply": round(statistics.mean(item["probe_supply"] for item in subset), 2), - } - - -def verdict(summary: dict[str, Any], prior: str, arm: str) -> str: - """Gate: top1 not lower AND truth-in-range not lower AND median width lower, all radii.""" - passes = [] - for radius in RADII: - base = summary[prior][str(radius)]["B0"] - cand = summary[prior][str(radius)][arm] - if not cand.get("n"): - return "uncertain" - passes.append( - cand["top1"] >= base["top1"] - and cand["truth_in_range"] >= base["truth_in_range"] - and cand["median_width"] < base["median_width"] - ) - return "benefit" if all(passes) else "no_benefit" - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--json-out", default=str(REPORT_JSON)) - args = parser.parse_args() - cases = load_cases() - if args.limit: - cases = cases[: args.limit] - rows: list[dict[str, Any]] = [] - for case in cases: - for radius in RADII: - try: - rows.append(evaluate_case(case, radius)) - except Exception as exc: # noqa: BLE001 - rows.append({"case_id": case.get("case_id"), "radius": radius, "error": f"{type(exc).__name__}: {exc}"}) - arms = ("B0", "R1d", "R1y", "R3", "R3+R1d", "R2k1", "R2k2") - summary = {prior: {str(radius): {arm: summarize(rows, prior, radius, arm) for arm in arms} - for radius in RADII} for prior in PRIORS} - verdicts = {prior: {arm: verdict(summary, prior, arm) for arm in ("R1d", "R1y", "R3", "R3+R1d")} for prior in PRIORS} - assert event_probes._existence_blocked_years is ORIGINAL_BLOCKED_YEARS - payload = { - "generated_for": "TASK-rectification-typed-event-scoring-research-20260929", - "today": TODAY.isoformat(), - "holdout": "references/real_case_calibration/minute_rectification_holdout_v4.json", - "ask_count": ASK_COUNT, - "separation_lead": SEPARATION_LEAD, - "shift_seed": SHIFT_SEED, - "shift_repeats": SHIFT_REPEATS, - "open_set_not_blind": True, - "summary": summary, - "verdicts": verdicts, - "rows": rows, - "errors": [row for row in rows if row.get("error")], - } - out = Path(args.json_out) - out.write_text(json.dumps(payload, ensure_ascii=False, indent=1, sort_keys=True) + "\n", encoding="utf-8") - print(json.dumps({"summary": summary, "verdicts": verdicts}, ensure_ascii=False, indent=1)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/varga_resolution_lib.py b/scripts/research/varga_resolution_lib.py deleted file mode 100644 index 5793b6bdf..000000000 --- a/scripts/research/varga_resolution_lib.py +++ /dev/null @@ -1,634 +0,0 @@ -#!/usr/bin/env python3 -"""Varga-resolution research library (TASK-rectification-varga-resolution-research-20260930). - -Offline only. Nothing here is imported by production code, and nothing here -changes production scoring: the six-probe replay reuses the production probe -generator (`event_probes.discriminating_event_probes`), the production card -update (`probe_supply_after_six.apply_answer`, ±2 / three strong conflicts -eliminate) and the production delivery rule (`cluster_width_lib.still_valid_public`, -lead 8). What this module adds on top is bookkeeping *by varga ascendant -segment* instead of by candidate minute: - -* `signs_per_minute` — D1 / D9 / D10 / D12 ascendant sign for every minute - offset in the search window (step 1); -* `segments_for` — contiguous runs of one sign = "chart-type segments"; -* `segment_shares` — posterior mass per segment (raw / percent / uniform) - over the still-valid candidate minutes; -* `segment_information_gain` + `select_probes_by_segment` — research-side - re-ranking of the *same* probe pool by how well an - answer separates the segments of a target varga. - -Calculation profile is the repository default (`raman`, mean node), the -candidate step is the production research step (2 minutes) and the six-probe -replay answers from the true minute, exactly as the 09-14 / 09-26 / 09-29 -studies did. -""" - -from __future__ import annotations - -import json -import math -import pickle -import sys -from datetime import datetime, timedelta -from pathlib import Path -from random import Random -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) -SCRIPTS = ROOT / "scripts" -if str(SCRIPTS) not in sys.path: - sys.path.insert(0, str(SCRIPTS)) - -import domain_calculation_service # noqa: E402 -import varga as varga_module # noqa: E402 -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - NODE_MODE, - compute_candidate_static_contexts, -) -from scripts.rectification.event_probes import discriminating_event_probes # noqa: E402 -from scripts.rectification.refinement_packet import window_scan # noqa: E402 -from scripts.rectification.scoring_service import ( # noqa: E402 - build_event_contribution_matrix, - score_from_matrix, - scoreable_request, -) -from scripts.research.cluster_width_lib import ( # noqa: E402 - SEPARATION_LEAD, - delivery_from_public, - hhmm, - still_valid_public, -) -from scripts.research.guided_collect_holdout_replay import TODAY # noqa: E402 -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.probe_supply_after_six import ( # noqa: E402 - ASK_COUNT, - apply_answer, - inherit_direction, - optimal_answer, - outcome_groups, -) -from scripts.research.scoring_research_lib import public_for # noqa: E402 - -HOLDOUT_V5 = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v5.json" -VARGAS: tuple[str, ...] = ("D1", "D9", "D10", "D12") -RADII: tuple[int, ...] = (10, 30, 60) -COUNT_RADII: tuple[int, ...] = (10, 15, 30, 60) -MODES: tuple[str, ...] = ("raw", "percent", "uniform") -THRESHOLDS: tuple[float, ...] = (0.5, 0.6, 0.7, 0.8, 0.9) -TARGET_ACCURACIES: tuple[float, ...] = (0.8, 0.9) -MIN_TRAINING_CASES = 5 -#: Question-domain strategies (decision record: 事业 → D1+D10, 婚恋 → D1+D9, 综合 → D1+D9+D10). -STRATEGIES: dict[str, tuple[str, ...]] = { - "career": ("D1", "D10"), - "relationship": ("D1", "D9"), - "general": ("D1", "D9", "D10"), -} -LMT_ERA_BEFORE_YEAR = 1900 -DAY_SHIFT = 7 -FLIP_SEEDS = 5 -EPS = 1e-9 - - -# --------------------------------------------------------------------------- -# cases and clocks -# --------------------------------------------------------------------------- - -def load_cases(path: Path = HOLDOUT_V5) -> list[dict[str, Any]]: - payload = json.loads(path.read_text(encoding="utf-8")) - return list(payload.get("cases") or []) - - -def clock(value: str) -> int: - hours, minutes = str(value)[:5].split(":") - return int(hours) * 60 + int(minutes) - - -def offset_of(stamp: str, true_time: str) -> int: - """Signed minute offset of a HH:MM candidate from the true minute, nearest across midnight.""" - delta = (clock(stamp) - clock(true_time)) % 1440 - return delta - 1440 if delta > 720 else delta - - -def birth_datetime(case: dict[str, Any]) -> datetime: - birth = case["birth"] - return datetime.strptime(f"{birth['date']} {str(birth['time'])[:5]}", "%Y-%m-%d %H:%M") - - -def is_lmt_era(case: dict[str, Any]) -> bool: - return int(str(case["birth"]["date"])[:4]) < LMT_ERA_BEFORE_YEAR - - -# --------------------------------------------------------------------------- -# M0 · ascendant signs per minute and segments -# --------------------------------------------------------------------------- - -def _divisions(vargas: Sequence[str]) -> list[int]: - return sorted({int(name[1:]) for name in vargas if name != "D1"}) - - -def signs_at(birth: dict[str, Any], moment: datetime, vargas: Sequence[str] = VARGAS) -> dict[str, int]: - chart = domain_calculation_service.compute_chart({ - "year": moment.year, "month": moment.month, "day": moment.day, - "hour": moment.hour, "minute": moment.minute, - "lat": float(birth["latitude"]), "lon": float(birth["longitude"]), - "tz": float(birth["timezone_offset"]), - "ayanamsa": AYANAMSA, "node_mode": NODE_MODE, - }) - planet_longitudes = { - name: float(item["lon"]) for name, item in chart.get("planets", {}).items() - if isinstance(item, dict) and isinstance(item.get("lon"), (int, float)) - } - ascendant = float(chart["ascendant"]["lon"]) - out: dict[str, int] = {} - if "D1" in vargas: - out["D1"] = int(ascendant // 30) % 12 - divisions = _divisions(vargas) - if divisions: - computed = varga_module.calc_all_vargas(planet_longitudes, ascendant, divisions=divisions) - for value in computed.values(): - division = int(value["_meta"]["div"]) - out[f"D{division}"] = int(value["Ascendant"]["sign_idx"]) - return out - - -def signs_per_minute( - case: dict[str, Any], - radius: int, - *, - vargas: Sequence[str] = VARGAS, - cache_dir: Path | None = None, -) -> dict[int, dict[str, int]]: - """{offset: {varga: sign_idx}} for every minute in [-radius, radius] (step 1).""" - key = f"{case['case_id']}_{radius}_{'-'.join(vargas)}.json" - if cache_dir is not None: - path = cache_dir / key - if path.exists(): - raw = json.loads(path.read_text(encoding="utf-8")) - return {int(offset): dict(signs) for offset, signs in raw.items()} - origin = birth_datetime(case) - out = { - offset: signs_at(case["birth"], origin + timedelta(minutes=offset), vargas) - for offset in range(-radius, radius + 1) - } - if cache_dir is not None: - cache_dir.mkdir(parents=True, exist_ok=True) - (cache_dir / key).write_text( - json.dumps({str(k): v for k, v in out.items()}, sort_keys=True), encoding="utf-8", - ) - return out - - -def segments_for(signs: dict[int, dict[str, int]], vargas: Sequence[str]) -> list[dict[str, Any]]: - """Contiguous minute runs where every varga in `vargas` keeps its ascendant sign. - - Each segment: {"index", "start", "end", "key"} with key = tuple of signs. - """ - offsets = sorted(signs) - segments: list[dict[str, Any]] = [] - for offset in offsets: - key = tuple(int(signs[offset][name]) for name in vargas) - if segments and segments[-1]["key"] == key and segments[-1]["end"] == offset - 1: - segments[-1]["end"] = offset - else: - segments.append({"index": len(segments), "start": offset, "end": offset, "key": key}) - return segments - - -def segment_index_of(segments: Sequence[dict[str, Any]], offset: int) -> int | None: - for segment in segments: - if segment["start"] <= offset <= segment["end"]: - return int(segment["index"]) - return None - - -def distinct_signs(signs: dict[int, dict[str, int]], radius: int, vargas: Sequence[str]) -> int: - return len({tuple(int(signs[o][name]) for name in vargas) for o in range(-radius, radius + 1) if o in signs}) - - -def count_table(per_case: dict[str, dict[int, dict[str, int]]], radii: Sequence[int] = COUNT_RADII) -> dict[str, Any]: - """Table 1 of the brief: how many ascendant signs / combinations inside each window.""" - keys: dict[str, tuple[str, ...]] = {name: (name,) for name in VARGAS} - keys["D1xD9xD10"] = ("D1", "D9", "D10") - out: dict[str, Any] = {} - for radius in radii: - row: dict[str, Any] = {} - for label, vargas in keys.items(): - counts = [distinct_signs(signs, radius, vargas) for signs in per_case.values()] - row[label] = { - "single": sum(1 for c in counts if c == 1), - "n": len(counts), - "mean": round(sum(counts) / len(counts), 2) if counts else None, - "max": max(counts) if counts else None, - } - out[str(radius)] = row - return out - - -# --------------------------------------------------------------------------- -# six-probe replay with segment bookkeeping -# --------------------------------------------------------------------------- - -class CaseReplay: - """One case at one radius: production scores, production probe pool, public clusters.""" - - def __init__(self, case: dict[str, Any], radius: int, *, cache_dir: Path | None = None) -> None: - self.case = case - self.case_id = str(case["case_id"]) - self.radius = int(radius) - self.true_time = str(case["birth"]["time"])[:5] - self.request = scoring_request_for({**case, "candidate_radius_minutes": radius}, radius) - self.request["ayanamsa"] = AYANAMSA - self.request["node_mode"] = NODE_MODE - self.request["minute_step"] = MINUTE_STEP - self.contexts = self._contexts(cache_dir) - self.times = [ctx["candidate_at"].strftime("%H:%M") for ctx in self.contexts] - self.rows, self.probes = self.rows_and_probes(self.request) - self.public = public_for(self.rows, self.contexts) - self.signs = signs_per_minute(case, radius, cache_dir=cache_dir) - - def _contexts(self, cache_dir: Path | None) -> list[dict[str, Any]]: - if cache_dir is not None: - path = cache_dir / f"{self.case_id}_{self.radius}.pkl" - if path.exists(): - with path.open("rb") as handle: - return pickle.load(handle) - contexts = compute_candidate_static_contexts(self.request) - if cache_dir is not None: - cache_dir.mkdir(parents=True, exist_ok=True) - with (cache_dir / f"{self.case_id}_{self.radius}.pkl").open("wb") as handle: - pickle.dump(contexts, handle) - return contexts - - def rows_and_probes(self, request: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - built = build_event_contribution_matrix(request, static_contexts=self.contexts) - rows = score_from_matrix(request, built) - times = [stamp for row in rows if (stamp := hhmm(row.get("time")))] - probes = discriminating_event_probes( - {**request, "refresh_probes": False, "asked_probe_keys": []}, - built, scan=window_scan(built), candidate_times=times, - representative_time=self.true_time, today=TODAY, - ) - return rows, list(probes) - - def shifted(self, days: int, *, seed: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: - """Rows / probes / public after moving every day-precision event by ±days (random sign).""" - rng = Random(seed) - events = [] - for event in self.request["events"]: - item = dict(event) - raw = str(item.get("date") or "") - if str(item.get("precision")) == "day" and len(raw) >= 10: - when = datetime.strptime(raw[:10], "%Y-%m-%d") + timedelta(days=days * rng.choice((-1, 1))) - item["date"] = when.strftime("%Y-%m-%d") - events.append(item) - request = scoreable_request({**self.request, "events": events}) - rows, probes = self.rows_and_probes(request) - return rows, probes, public_for(rows, self.contexts) - - # --- segment helpers ------------------------------------------------ - def segments(self, vargas: Sequence[str]) -> list[dict[str, Any]]: - return segments_for(self.signs, vargas) - - def truth_segment(self, segments: Sequence[dict[str, Any]]) -> int: - index = segment_index_of(segments, 0) - assert index is not None - return index - - -def replay_scores( - public: Sequence[dict[str, Any]], - probes: Sequence[dict[str, Any]], - true_time: str, - *, - answers: Sequence[str | None] | None = None, - ask_count: int = ASK_COUNT, -) -> dict[str, Any]: - """Production posterior after `ask_count` probes: scores per cluster - representative, eliminated set, still-valid clusters and delivery.""" - reps = [str(row["time"])[:5] for row in public] - scores = {time: float(row.get("score") or 0) for time, row in zip(reps, public)} - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - asked = list(probes)[:ask_count] - given = list(answers) if answers is not None else [optimal_answer(p, true_time) for p in asked] - answered = 0 - for probe, answer in zip(asked, given): - if answer is None: - continue - answered += 1 - scores, conflicts, eliminated = apply_answer(scores, conflicts, eliminated, probe, answer, reps) - return finish_state(public, scores, eliminated, answered) - - -def finish_state( - public: Sequence[dict[str, Any]], - scores: dict[str, float], - eliminated: set[str], - answered: int, -) -> dict[str, Any]: - posterior = [{**row, "score": scores.get(str(row["time"])[:5], row.get("score") or 0)} for row in public] - valid = still_valid_public(posterior, scores, eliminated, lead=SEPARATION_LEAD) - delivery = delivery_from_public(valid) - return { - "scores": scores, - "eliminated": set(eliminated), - "public": posterior, - "valid": valid, - "delivery": delivery, - "answered": answered, - } - - -def minute_weights(state: dict[str, Any], mode: str, *, valid_only: bool = True) -> dict[str, float]: - """Posterior mass per candidate minute (HH:MM). - - raw — cluster score (clipped at 0) spread evenly over its member minutes; - percent — proportional percent over clusters, spread evenly over members; - uniform — every surviving minute weighs 1. - """ - rows = state["valid"] if valid_only else [r for r in state["public"] if str(r["time"])[:5] not in state["eliminated"]] - scores = state["scores"] - cluster_mass: dict[str, float] = {} - for row in rows: - stamp = str(row["time"])[:5] - cluster_mass[stamp] = max(float(scores.get(stamp, row.get("score") or 0)), 0.0) - if mode == "percent": - total = sum(cluster_mass.values()) - cluster_mass = {k: (v / total if total > 0 else 0.0) for k, v in cluster_mass.items()} - weights: dict[str, float] = {} - for row in rows: - stamp = str(row["time"])[:5] - members = [str(t)[:5] for t in (row.get("cluster_times") or [stamp])] - if mode == "uniform": - for member in members: - weights[member] = 1.0 - continue - share = cluster_mass[stamp] / len(members) if members else 0.0 - for member in members: - weights[member] = weights.get(member, 0.0) + share - return weights - - -def segment_shares( - weights: dict[str, float], - segments: Sequence[dict[str, Any]], - true_time: str, -) -> dict[str, Any]: - mass = [0.0 for _ in segments] - for stamp, weight in weights.items(): - index = segment_index_of(segments, offset_of(stamp, true_time)) - if index is not None: - mass[index] += float(weight) - total = sum(mass) - shares = [m / total if total > 0 else 0.0 for m in mass] - alive = [i for i, m in enumerate(mass) if m > EPS] - truth = segment_index_of(segments, 0) - ranked = sorted(alive, key=lambda i: (-shares[i], i)) - top = ranked[0] if ranked else None - return { - "shares": [round(s, 6) for s in shares], - "alive_segments": len(alive), - "top_segment": top, - "top_share": round(shares[top], 6) if top is not None else 0.0, - "truth_segment": truth, - "truth_retained": truth in alive, - "top_is_truth": top is not None and top == truth, - "truth_share": round(shares[truth], 6) if truth is not None else 0.0, - } - - -def truth_in_delivery(state: dict[str, Any], true_time: str) -> bool: - start, end = state["delivery"].get("start"), state["delivery"].get("end") - if start is None or end is None: - return False - span = (clock(end) - clock(start)) % 1440 - return (clock(true_time) - clock(start)) % 1440 <= span - - -# --------------------------------------------------------------------------- -# M2 · segment-aware probe ordering -# --------------------------------------------------------------------------- - -def _entropy(values: Sequence[float]) -> float: - total = sum(values) - if total <= 0: - return 0.0 - out = 0.0 - for value in values: - if value > 0: - p = value / total - out -= p * math.log2(p) - return out - - -def probe_side(probe: dict[str, Any], stamp: str) -> str: - yes, no = outcome_groups(probe) - if stamp in yes: - return "yes" - if stamp in no: - return "no" - direction = inherit_direction(stamp, yes, no) - return {"support": "yes", "conflict": "no"}.get(direction, "neutral") - - -def segment_information_gain( - probe: dict[str, Any], - weights: dict[str, float], - segments: Sequence[dict[str, Any]], - true_time: str, -) -> float: - """I(segment ; answer) under the current minute mass. - - A candidate minute on the probe's yes side answers "yes" with probability 1, - one on the no side answers "no" with probability 1; a minute the probe says - nothing about (neutral) is an uninformative coin (½ / ½), which is what the - production card update does with it (delta 0).""" - n = len(segments) - joint: dict[str, list[float]] = {"yes": [0.0] * n, "no": [0.0] * n} - for stamp, weight in weights.items(): - index = segment_index_of(segments, offset_of(stamp, true_time)) - if index is None or weight <= 0: - continue - side = probe_side(probe, stamp) - if side == "neutral": - joint["yes"][index] += float(weight) / 2 - joint["no"][index] += float(weight) / 2 - else: - joint[side][index] += float(weight) - prior = [sum(joint[a][i] for a in joint) for i in range(n)] - total = sum(prior) - if total <= 0: - return 0.0 - conditional = 0.0 - for answer, mass in joint.items(): - p_answer = sum(mass) / total - if p_answer > 0: - conditional += p_answer * _entropy(mass) - return round(_entropy(prior) - conditional, 6) - - -def select_probes_by_segment( - public: Sequence[dict[str, Any]], - pool: Sequence[dict[str, Any]], - segments: Sequence[dict[str, Any]], - true_time: str, - *, - ask_count: int = ASK_COUNT, - mode: str = "raw", - stop_share: float | None = None, - answers_override: dict[str, str | None] | None = None, -) -> dict[str, Any]: - """Sequential selection: at each step pick the unasked probe with the largest - segment information gain under the current posterior, answer it from the - true minute (as the production replay does), apply the production card - update, repeat. Optional `stop_share` stops as soon as the top segment holds - that share of the mass. Returns the final state plus the asked order.""" - reps = [str(row["time"])[:5] for row in public] - scores = {time: float(row.get("score") or 0) for time, row in zip(reps, public)} - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - remaining = list(pool) - asked: list[dict[str, Any]] = [] - answered = 0 - gains: list[float] = [] - while remaining and len(asked) < ask_count: - state = finish_state(public, scores, eliminated, answered) - weights = minute_weights(state, mode) - if stop_share is not None: - share = segment_shares(weights, segments, true_time) - if share["alive_segments"] <= 1 or share["top_share"] >= stop_share - EPS: - break - scored = [(segment_information_gain(p, weights, segments, true_time), -i, i) for i, p in enumerate(remaining)] - gain, _neg, index = max(scored) - probe = remaining.pop(index) - asked.append(probe) - gains.append(gain) - key = str(probe.get("semantic_key") or probe.get("id") or "") - answer = answers_override.get(key, optimal_answer(probe, true_time)) if answers_override else optimal_answer(probe, true_time) - if answer is None: - continue - answered += 1 - scores, conflicts, eliminated = apply_answer(scores, conflicts, eliminated, probe, answer, reps) - state = finish_state(public, scores, eliminated, answered) - state["asked"] = asked - state["gains"] = gains - return state - - -def production_order_with_stop( - public: Sequence[dict[str, Any]], - pool: Sequence[dict[str, Any]], - segments: Sequence[dict[str, Any]], - true_time: str, - *, - ask_count: int = ASK_COUNT, - mode: str = "raw", - stop_share: float | None = None, -) -> dict[str, Any]: - """Production probe order (first N of the ranked pool) with the same optional stop rule.""" - reps = [str(row["time"])[:5] for row in public] - scores = {time: float(row.get("score") or 0) for time, row in zip(reps, public)} - conflicts = {time: 0 for time in reps} - eliminated: set[str] = set() - asked: list[dict[str, Any]] = [] - answered = 0 - for probe in list(pool)[:ask_count]: - if stop_share is not None: - state = finish_state(public, scores, eliminated, answered) - share = segment_shares(minute_weights(state, mode), segments, true_time) - if share["alive_segments"] <= 1 or share["top_share"] >= stop_share - EPS: - break - asked.append(probe) - answer = optimal_answer(probe, true_time) - if answer is None: - continue - answered += 1 - scores, conflicts, eliminated = apply_answer(scores, conflicts, eliminated, probe, answer, reps) - state = finish_state(public, scores, eliminated, answered) - state["asked"] = asked - return state - - -# --------------------------------------------------------------------------- -# M1 · threshold / accuracy tables -# --------------------------------------------------------------------------- - -def threshold_table(points: Sequence[tuple[float, bool]], thresholds: Sequence[float] = THRESHOLDS) -> list[dict[str, Any]]: - """Full-fit: among cases whose top share ≥ t, how often the top segment is the truth.""" - out = [] - for t in thresholds: - inside = [ok for share, ok in points if share + EPS >= t] - out.append({ - "threshold": t, - "n": len(inside), - "accuracy": round(sum(inside) / len(inside), 4) if inside else None, - }) - return out - - -def loo_threshold( - points: Sequence[tuple[float, bool]], - *, - target: float, - thresholds: Sequence[float] = THRESHOLDS, - min_training: int = MIN_TRAINING_CASES, -) -> dict[str, Any]: - """Leave-one-case-out: pick the smallest grid threshold whose *training* - accuracy reaches `target` (with at least `min_training` training cases - above it), then score the held-out case: labelled 'confident' when its - share clears that threshold. Reports how often 'confident' was right.""" - labelled: list[tuple[float | None, bool, bool]] = [] # (threshold used, confident?, correct?) - for hold in range(len(points)): - training = [p for i, p in enumerate(points) if i != hold] - chosen: float | None = None - for t in thresholds: - inside = [ok for share, ok in training if share + EPS >= t] - if len(inside) >= min_training and sum(inside) / len(inside) + EPS >= target: - chosen = t - break - share, ok = points[hold] - confident = chosen is not None and share + EPS >= chosen - labelled.append((chosen, confident, ok)) - confident_rows = [ok for _t, c, ok in labelled if c] - thresholds_used = sorted({t for t, _c, _ok in labelled if t is not None}) - return { - "target": target, - "confident_n": len(confident_rows), - "confident_accuracy": round(sum(confident_rows) / len(confident_rows), 4) if confident_rows else None, - "not_confident_n": len(labelled) - len(confident_rows), - "no_threshold_folds": sum(1 for t, _c, _ok in labelled if t is None), - "thresholds_used": thresholds_used, - } - - -# --------------------------------------------------------------------------- -# answer perturbation (robustness) -# --------------------------------------------------------------------------- - -def flipped_answers( - probes: Sequence[dict[str, Any]], - true_time: str, - *, - flips: int, - seed: str, - ask_count: int = ASK_COUNT, -) -> list[str | None]: - """Optimal answers with `flips` of the answered probes inverted (yes↔no).""" - asked = list(probes)[:ask_count] - answers: list[str | None] = [optimal_answer(p, true_time) for p in asked] - answerable = [i for i, a in enumerate(answers) if a in {"yes", "no"}] - rng = Random(seed) - for index in rng.sample(answerable, min(flips, len(answerable))): - answers[index] = "no" if answers[index] == "yes" else "yes" - return answers - - -def stable_json(payload: Any) -> str: - return json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n" - - -__all__ = [name for name in dir() if not name.startswith("__")] diff --git a/scripts/research/varga_resolution_method_replay.py b/scripts/research/varga_resolution_method_replay.py deleted file mode 100644 index 93f8ea2bb..000000000 --- a/scripts/research/varga_resolution_method_replay.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Method-selection + direct reducer diagnostic (not answer persistence). - -Public holdout-v5 cases only. Truth goes exclusively to the offline answer -oracle; the frozen collection, holdout, delivery and stopping gates stay live. -The bridge does not exercise option classification, owned contrast registration -or persistV9ChoiceAction. Early stop or a missing probe is not six-question -validation. This is not the accepted single-chart M2 experiment. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import platform -from datetime import timedelta -from pathlib import Path - -from scripts.research import varga_resolution_lib as vr -from scripts.research.varga_resolution_production_bridge import ProductionSegmentBridge -from scripts.rectification.api_service import score_candidates - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--dataset", default=str(vr.HOLDOUT_V5)) - parser.add_argument("--output", required=True) - parser.add_argument("--cache-dir", required=True) - parser.add_argument("--limit", type=int) - parser.add_argument("--radii", default="10,30,60") - args = parser.parse_args() - cases = vr.load_cases(Path(args.dataset)) - if args.limit: - cases = cases[:args.limit] - cache = Path(args.cache_dir) - cache.mkdir(parents=True, exist_ok=True) - bridge = ProductionSegmentBridge() - records = [] - try: - for case in cases: - for radius in map(int, args.radii.split(",")): - replay = vr.CaseReplay(case, radius, cache_dir=cache) - key = hashlib.sha256(json.dumps(replay.request, sort_keys=True).encode()).hexdigest() - response_file = cache / f"score-api-{key}.json" - if response_file.exists(): - response = json.loads(response_file.read_text(encoding="utf-8")) - else: - response = score_candidates(replay.request) - response_file.write_text(json.dumps(response, ensure_ascii=False), encoding="utf-8") - intervals = response["decision_receipt"]["candidate_intervals"] - birth = case["birth"] - origin = vr.birth_datetime(case) - snapshot = {"birth_date": str(birth["date"]), "reported_birth_time": replay.true_time, - "birth_time_source": "approximate", "timezone_offset": replay.request["tz"], - "timezone_id": replay.request.get("timezone_id"), - "latitude": replay.request["lat"], "longitude": replay.request["lon"]} - evidence = [{"id": str(event["id"]), "status": "confirmed", "domain": event["domain"], - "datePrecision": event.get("precision", "day"), "occurredFrom": event.get("date_start", event.get("date")), - "occurredTo": event.get("date_end", event.get("date")), "eventKind": event.get("event_kind", "dated_event"), - "summary": event.get("description", "Public calibration event")} - for event in replay.request["events"]] - minutes = [{"offset": offset + radius, "date": (origin + timedelta(minutes=offset)).strftime("%Y-%m-%d"), - "time": (origin + timedelta(minutes=offset)).strftime("%H:%M"), - "signs": {chart: signs[chart] for chart in ("D1", "D9", "D10")}} - for offset, signs in sorted(replay.signs.items())] - for enabled in (False, True): - result = bridge.call({"operation": "method_replay", "request": replay.request, - "response": response, "snapshot": snapshot, - "range": {"start_time": replay.request["start_time"], "end_time": replay.request["end_time"], - "candidate_intervals": intervals}, - "evidence": evidence, "minutes": minutes, "targets": ["D1", "D9", "D10"], - "enabled": enabled, "true_time": replay.true_time, "ask_count": vr.ASK_COUNT}) - state = result.pop("state") - raw = bridge.call({"operation": "weights", "rows": [{"time": row["time"], "score": row.get("raw_posterior_score", 0), - "cluster_times": row.get("cluster_times")} for row in state["candidates"]], - "eliminated": [row["time"] for row in state["candidates"] if row.get("raw_eliminated")]}) - metrics = {} - for chart in ("D9", "D10"): - segments = replay.segments([chart]) - summary = bridge.call({"operation": "summary_weights", "weights": raw, "segments": segments, - "offsets": {stamp: vr.offset_of(stamp, replay.true_time) for stamp in raw}, "truth_offset": 0}) - metrics[chart] = summary - records.append({"case_id": replay.case_id, "radius": radius, "strategy": "joint" if enabled else "frozen", - "api_response_sha256": hashlib.sha256(response_file.read_bytes()).hexdigest(), - **result, "metrics": metrics}) - print(f"method replay completed radius={radius}", flush=True) - finally: - bridge.close() - aggregate = {} - for radius in map(int, args.radii.split(",")): - for strategy in ("frozen", "joint"): - rows = [row for row in records if row["radius"] == radius and row["strategy"] == strategy] - aggregate[f"{radius}:{strategy}"] = {"cases": len(rows), "asked": sum(len(row["asked"]) for row in rows), - "D9": {"truth_kept": sum(row["metrics"]["D9"]["truth_retained"] for row in rows), - "top_hit": sum(row["metrics"]["D9"]["top_is_truth"] for row in rows)}, - "D10": {"truth_kept": sum(row["metrics"]["D10"]["truth_retained"] for row in rows), - "top_hit": sum(row["metrics"]["D10"]["top_is_truth"] for row in rows)}} - output = {"scope": "method-selection + direct reducer diagnostic (not answer persistence); real score API/parser/inference/catalog/method/decision, default joint targets; early stop/missing probe is not six-question validation", - "python_version": platform.python_version(), "dataset_sha256": hashlib.sha256(Path(args.dataset).read_bytes()).hexdigest(), - "aggregate": aggregate, "records": records} - Path(args.output).write_text(json.dumps(output, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/varga_resolution_persisted_replay.py b/scripts/research/varga_resolution_persisted_replay.py deleted file mode 100644 index c179abbf1..000000000 --- a/scripts/research/varga_resolution_persisted_replay.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Public holdout replay through live API and production PostgreSQL answer paths. - -Explicit fictional Case seeds are not successful product opening. No turn, -evidence, focus or answer is seeded: a refused production RPC stops that row. -Off is the default; on changes only segment ordering. Truth is oracle-only. -""" -from __future__ import annotations - -import argparse -import hashlib -import json -import os -import platform -import subprocess -import threading -from http.server import ThreadingHTTPServer -from pathlib import Path - -from scripts.jyotish_api_server import DEFAULT_ALLOWED_HOSTS, DEFAULT_ALLOWED_ORIGINS, JyotishAPIHandler -from scripts.research import varga_resolution_lib as vr -from scripts.research.minute_resolution_sweep import scoring_request_for - -ROOT = Path(__file__).resolve().parents[2] - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--dataset", default=str(vr.HOLDOUT_V5)) - parser.add_argument("--output", required=True) - parser.add_argument("--limit", type=int, default=10) - parser.add_argument("--radii", default="10,30,60") - parser.add_argument("--study", action="store_true") - parser.add_argument("--modes", default="all_correct,flip_1,flip_3,flip_5") - parser.add_argument("--orderings", default="off") - parser.add_argument("--code-sha", default="") - args = parser.parse_args() - target = Path(args.output) - if target.exists(): - parser.error("--output already exists; retain prior evidence and choose a unique label") - cases = vr.load_cases(Path(args.dataset)) - if args.limit: - cases = cases[:args.limit] - rows = [] - for case in cases: - birth = case["birth"] - for radius in map(int, args.radii.split(",")): - request = scoring_request_for(case, radius) - rows.append({"case_key": case["case_id"], "radius": radius, - "snapshot": {"birth_date": birth["date"], "reported_birth_time": str(birth["time"])[:5], - "birth_time_source": "approximate", "active_birth_time": None, - "uncertainty_before_minutes": radius, "uncertainty_after_minutes": radius, - "latitude": request["lat"], "longitude": request["lon"], - "timezone_offset": request["tz"], "timezone_id": birth.get("timezone_id")}, - "range": {"start_time": request["start_time"], "end_time": request["end_time"]}, - "events": request["events"], "oracle_truth_minute": str(birth["time"])[:5]}) - server = ThreadingHTTPServer(("127.0.0.1", 0), JyotishAPIHandler) - server.daemon_threads = True - origin = f"http://127.0.0.1:{server.server_port}" - server.allowed_hosts = set(DEFAULT_ALLOWED_HOSTS) - server.allowed_origins = set(DEFAULT_ALLOWED_ORIGINS) | {origin} - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - env = {**os.environ, "JYOTISH_API_BASE": origin} - body: dict = {"rows": rows} - if args.study: - body["study"] = { - "modes": [item for item in args.modes.split(",") if item], - "orderings": [item for item in args.orderings.split(",") if item], - "code_sha": args.code_sha, - } - result = subprocess.run(["node", "--import", "tsx", "tests/research/rectification-segment-persisted-replay.ts"], - cwd=ROOT / "frontend", env=env, input=json.dumps(body), - text=True, encoding="utf-8", stdout=subprocess.PIPE, check=False) - payload = json.loads(result.stdout) - payload.update({"python_version": platform.python_version(), - "dataset_sha256": hashlib.sha256(Path(args.dataset).read_bytes()).hexdigest(), - "runner_exit": result.returncode}) - if args.study: - for row in payload.get("records") or []: - if isinstance(row, dict): - for key in ("asked", "gates", "ledger_before", "ledger_after", "metrics", "targets", "domain"): - row.pop(key, None) - payload["rerun"] = { - "command": "python scripts/research/varga_resolution_persisted_replay.py --study " - f"--modes {args.modes} --orderings {args.orderings} --radii {args.radii} " - f"--limit {args.limit} --code-sha {args.code_sha or ''} --output ", - "max_rounds": "DEFAULT_MAX_DISCRIMINATION_ROUNDS", - "truth_clock": "omitted; real-case calibration stores containment booleans only", - } - target.parent.mkdir(parents=True, exist_ok=True) - with target.open("x", encoding="utf-8") as stream: - stream.write(json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n") - print(f"persisted replay rows={len(payload.get('records', []))}; runner_exit={result.returncode}", flush=True) - return result.returncode - finally: - server.shutdown() - thread.join(timeout=10) - server.server_close() - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/varga_resolution_probe.py b/scripts/research/varga_resolution_probe.py deleted file mode 100644 index 835675e49..000000000 --- a/scripts/research/varga_resolution_probe.py +++ /dev/null @@ -1,487 +0,0 @@ -#!/usr/bin/env python3 -"""Varga-resolution research runner (TASK-rectification-varga-resolution-research-20260930). - -Stages (``--stages``, comma list, default all): - -* ``m0`` — Table 1 (signs per window) and Table 2 (chart type inside the - six-probe delivery interval) of the brief, reproduced from - `varga_resolution_lib`; written to ``--baseline-out``. -* ``m1`` — segment shares after the production six probes, raw / percent / - uniform mass; full-fit threshold table and leave-one-case-out - confidence labels per varga × radius; truth-segment retention. -* ``m2`` — production probe order vs segment-information-gain order on the - same pool, per target varga; also with a stop rule. -* ``m3`` — question-domain strategies (career / relationship / general): - joint segments, "no rectification needed" share, accuracy, - questions with stop rule. -* ``robust`` — 1 / 2 flipped answers (5 seeds), ±7-day shift of day-precision - events, LMT-era cases split out. - -Everything is offline; no production file is touched. ``PYTHONHASHSEED=0`` and -two runs must be byte-identical (``--json-out`` is written with sorted keys). - -Usage:: - - PYTHONHASHSEED=0 python3 scripts/research/varga_resolution_probe.py \ - --stages m0,m1,m2,m3,robust --radii 10,30,60 \ - --cache-dir /tmp/varga-cache \ - --baseline-out docs/research/varga_resolution_baseline_2026_09_30.json \ - --json-out docs/research/varga_resolution_research_2026_09_30.json -""" - -from __future__ import annotations - -import argparse -import hashlib -import platform -import statistics -import sys -import time -from collections import Counter, defaultdict -from pathlib import Path -from typing import Any, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.research import varga_resolution_lib as vr # noqa: E402 - -BASELINE_JSON = ROOT / "docs" / "research" / "varga_resolution_baseline_2026_09_30.json" -REPORT_JSON = ROOT / "docs" / "research" / "varga_resolution_research_2026_09_30.json" -TABLE_KEYS: dict[str, tuple[str, ...]] = { - "D1": ("D1",), "D9": ("D9",), "D10": ("D10",), "D12": ("D12",), "D1xD9xD10": ("D1", "D9", "D10"), -} -STOP_SHARES: tuple[float, ...] = (0.7, 0.8) - - -def _rate(values: Sequence[bool]) -> float | None: - return round(sum(1 for v in values if v) / len(values), 4) if values else None - - -def _median(values: Sequence[float | int | None]) -> float | None: - clean = [float(v) for v in values if v is not None] - return statistics.median(clean) if clean else None - - -# --------------------------------------------------------------------------- -# M0 -# --------------------------------------------------------------------------- - -def interval_offsets(state: dict[str, Any], true_time: str, radius: int) -> list[int]: - """Every minute (step 1) from delivery start to end, as offsets from the true minute.""" - start, end = state["delivery"].get("start"), state["delivery"].get("end") - if start is None or end is None: - return [] - # Forward span from start to end (through midnight when the window straddles - # it, e.g. a 00:01–23:59 range around a 23:15 birth), every offset folded - # into [-720, 720] and clipped to the search window. Interior minutes that - # were eliminated stay inside: this is the range the product shows. - span = (vr.clock(end) - vr.clock(start)) % 1440 - first = vr.offset_of(start, true_time) - offsets = [] - for step in range(span + 1): - offset = ((first + step + 720) % 1440) - 720 - if -radius <= offset <= radius: - offsets.append(offset) - return sorted(set(offsets)) - - -def table2_row(signs: dict[int, dict[str, int]], offsets: Sequence[int]) -> dict[str, Any]: - row: dict[str, Any] = {} - for label, vargas in TABLE_KEYS.items(): - keys = [tuple(signs[o][v] for v in vargas) for o in offsets if o in signs] - if not keys: - row[label] = {"kinds": 0, "single": False, "le2": False, "mode_is_truth": False} - continue - counter = Counter(keys) # insertion order = ascending offset; ties go to the earliest sign - ranked = counter.most_common() - mode_key = ranked[0][0] - tied = len(ranked) > 1 and ranked[1][1] == ranked[0][1] - truth_key = tuple(signs[0][v] for v in vargas) - row[label] = { - "kinds": len(counter), - "single": len(counter) == 1, - "le2": len(counter) <= 2, - "mode_is_truth": mode_key == truth_key, - "mode_tied": tied, - } - return row - - -def stage_m0(replays: dict[tuple[str, int], vr.CaseReplay], signs60: dict[str, dict[int, dict[str, int]]], radii: Sequence[int]) -> dict[str, Any]: - table1 = vr.count_table(signs60) - per_case: list[dict[str, Any]] = [] - for (case_id, radius), rep in sorted(replays.items()): - state = vr.replay_scores(rep.public, rep.probes, rep.true_time) - offsets = interval_offsets(state, rep.true_time, radius) - per_case.append({ - "case_id": case_id, "radius": radius, - "start": state["delivery"].get("start"), "end": state["delivery"].get("end"), - "width": state["delivery"].get("width"), - "truth_in_range": vr.truth_in_delivery(state, rep.true_time), - "table2": table2_row(rep.signs, offsets), - }) - table2: dict[str, Any] = {} - for radius in radii: - rows = [r for r in per_case if r["radius"] == radius] - summary: dict[str, Any] = { - "n": len(rows), - "truth_in_range": sum(1 for r in rows if r["truth_in_range"]), - "width_median": _median([r["width"] for r in rows]), - } - for label in TABLE_KEYS: - summary[label] = { - "single": sum(1 for r in rows if r["table2"][label]["single"]), - "le2": sum(1 for r in rows if r["table2"][label]["le2"]), - "mode_is_truth": sum(1 for r in rows if r["table2"][label]["mode_is_truth"]), - "mode_tied": sum(1 for r in rows if r["table2"][label]["mode_tied"]), - "mean_kinds": round(sum(r["table2"][label]["kinds"] for r in rows) / len(rows), 2) if rows else None, - } - table2[str(radius)] = summary - return {"table1_signs_per_window": table1, "table2_delivery_interval": table2, "per_case": per_case} - - -# --------------------------------------------------------------------------- -# M1 -# --------------------------------------------------------------------------- - -def share_points(replays: dict[tuple[str, int], vr.CaseReplay], radius: int, vargas: Sequence[str], mode: str, - *, cases_filter: set[str] | None = None) -> list[dict[str, Any]]: - out = [] - for (case_id, r), rep in sorted(replays.items()): - if r != radius or (cases_filter is not None and case_id not in cases_filter): - continue - state = vr.replay_scores(rep.public, rep.probes, rep.true_time) - share = vr.segment_shares(vr.minute_weights(state, mode), rep.segments(vargas), rep.true_time) - out.append({"case_id": case_id, **share, "segments_in_window": len(rep.segments(vargas))}) - return out - - -def summarize_shares(points: Sequence[dict[str, Any]]) -> dict[str, Any]: - pairs = [(p["top_share"], p["top_is_truth"]) for p in points] - return { - "n": len(points), - "truth_retained": sum(1 for p in points if p["truth_retained"]), - "top_is_truth": sum(1 for p in points if p["top_is_truth"]), - "alive_le2": sum(1 for p in points if p["alive_segments"] <= 2), - "alive_single": sum(1 for p in points if p["alive_segments"] == 1), - "top_share_median": _median([p["top_share"] for p in points]), - "full_fit": vr.threshold_table(pairs), - "loo": [vr.loo_threshold(pairs, target=t) for t in vr.TARGET_ACCURACIES], - } - - -def stage_m1(replays: dict[tuple[str, int], vr.CaseReplay], radii: Sequence[int], lmt_ids: set[str]) -> dict[str, Any]: - out: dict[str, Any] = {"by_radius": {}, "lmt_era_case_ids": sorted(lmt_ids)} - for radius in radii: - block: dict[str, Any] = {} - for label, vargas in TABLE_KEYS.items(): - block[label] = {} - for mode in vr.MODES: - points = share_points(replays, radius, vargas, mode) - summary = summarize_shares(points) - non_lmt = [p for p in points if p["case_id"] not in lmt_ids] - summary["excluding_lmt_era"] = { - "n": len(non_lmt), - "truth_retained": sum(1 for p in non_lmt if p["truth_retained"]), - "top_is_truth": sum(1 for p in non_lmt if p["top_is_truth"]), - } - summary["per_case"] = [ - {k: p[k] for k in ("case_id", "top_share", "top_is_truth", "truth_retained", "alive_segments", "segments_in_window")} - for p in points - ] - block[label][mode] = summary - out["by_radius"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# M2 -# --------------------------------------------------------------------------- - -def order_outcome(rep: vr.CaseReplay, state: dict[str, Any], vargas: Sequence[str], mode: str) -> dict[str, Any]: - share = vr.segment_shares(vr.minute_weights(state, mode), rep.segments(vargas), rep.true_time) - return { - "questions": len(state.get("asked", [])) if "asked" in state else state["answered"], - "answered": state["answered"], - "truth_retained": share["truth_retained"], - "top_is_truth": share["top_is_truth"], - "top_share": share["top_share"], - "alive_segments": share["alive_segments"], - "width": state["delivery"].get("width"), - "truth_in_range": vr.truth_in_delivery(state, rep.true_time), - } - - -def stage_m2(replays: dict[tuple[str, int], vr.CaseReplay], radii: Sequence[int], mode: str = "raw") -> dict[str, Any]: - targets = {"D9": ("D9",), "D10": ("D10",), "D1xD9xD10": ("D1", "D9", "D10")} - out: dict[str, Any] = {"mode": mode, "by_radius": {}} - for radius in radii: - block: dict[str, Any] = {} - for label, vargas in targets.items(): - rows = [] - for (case_id, r), rep in sorted(replays.items()): - if r != radius: - continue - segments = rep.segments(vargas) - prod = vr.replay_scores(rep.public, rep.probes, rep.true_time) - prod["asked"] = list(rep.probes)[:vr.ASK_COUNT] - seg = vr.select_probes_by_segment(rep.public, rep.probes, segments, rep.true_time, mode=mode) - row: dict[str, Any] = { - "case_id": case_id, - "pool": len(rep.probes), - "production": order_outcome(rep, prod, vargas, mode), - "segment_order": order_outcome(rep, seg, vargas, mode), - "same_first_six": [p.get("semantic_key") for p in prod["asked"]] == [p.get("semantic_key") for p in seg["asked"]], - } - for stop in STOP_SHARES: - prod_stop = vr.production_order_with_stop(rep.public, rep.probes, segments, rep.true_time, mode=mode, stop_share=stop) - seg_stop = vr.select_probes_by_segment(rep.public, rep.probes, segments, rep.true_time, mode=mode, stop_share=stop) - row[f"stop_{stop}"] = { - "production": order_outcome(rep, prod_stop, vargas, mode), - "segment_order": order_outcome(rep, seg_stop, vargas, mode), - } - rows.append(row) - - def agg(getter) -> dict[str, Any]: - items = [getter(r) for r in rows] - return { - "n": len(items), - "mean_questions": round(sum(i["questions"] for i in items) / len(items), 2) if items else None, - "truth_retained": sum(1 for i in items if i["truth_retained"]), - "top_is_truth": sum(1 for i in items if i["top_is_truth"]), - "alive_le2": sum(1 for i in items if i["alive_segments"] <= 2), - "top_share_median": _median([i["top_share"] for i in items]), - "truth_in_range": sum(1 for i in items if i["truth_in_range"]), - "width_median": _median([i["width"] for i in items]), - } - - summary: dict[str, Any] = { - "six": {"production": agg(lambda r: r["production"]), "segment_order": agg(lambda r: r["segment_order"])}, - "same_first_six_cases": sum(1 for r in rows if r["same_first_six"]), - "pool_median": _median([r["pool"] for r in rows]), - } - for stop in STOP_SHARES: - summary[f"stop_{stop}"] = { - "production": agg(lambda r, s=stop: r[f"stop_{s}"]["production"]), - "segment_order": agg(lambda r, s=stop: r[f"stop_{s}"]["segment_order"]), - } - summary["per_case"] = rows - block[label] = summary - out["by_radius"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# M3 -# --------------------------------------------------------------------------- - -def stage_m3(replays: dict[tuple[str, int], vr.CaseReplay], signs60: dict[str, dict[int, dict[str, int]]], - radii: Sequence[int], mode: str = "raw") -> dict[str, Any]: - out: dict[str, Any] = {"mode": mode, "strategies": {k: list(v) for k, v in vr.STRATEGIES.items()}, "by_radius": {}} - for radius in list(radii) + [r for r in vr.COUNT_RADII if r not in radii]: - block: dict[str, Any] = {} - for name, vargas in vr.STRATEGIES.items(): - # "no rectification needed": the target vargas keep one joint sign across the whole window - no_need = sum(1 for signs in signs60.values() if vr.distinct_signs(signs, radius, vargas) == 1) - entry: dict[str, Any] = {"no_rectification_needed": no_need, "n_cases": len(signs60)} - if radius in radii: - rows = [] - for (case_id, r), rep in sorted(replays.items()): - if r != radius: - continue - segments = rep.segments(vargas) - prod = vr.replay_scores(rep.public, rep.probes, rep.true_time) - prod["asked"] = list(rep.probes)[:vr.ASK_COUNT] - seg = vr.select_probes_by_segment(rep.public, rep.probes, segments, rep.true_time, mode=mode) - row = { - "case_id": case_id, - "segments_in_window": len(segments), - "production": order_outcome(rep, prod, vargas, mode), - "segment_order": order_outcome(rep, seg, vargas, mode), - } - for stop in STOP_SHARES: - seg_stop = vr.select_probes_by_segment(rep.public, rep.probes, segments, rep.true_time, mode=mode, stop_share=stop) - row[f"stop_{stop}"] = order_outcome(rep, seg_stop, vargas, mode) - rows.append(row) - - def agg(items: Sequence[dict[str, Any]]) -> dict[str, Any]: - return { - "n": len(items), - "mean_questions": round(sum(i["questions"] for i in items) / len(items), 2) if items else None, - "truth_retained": sum(1 for i in items if i["truth_retained"]), - "top_is_truth": sum(1 for i in items if i["top_is_truth"]), - "alive_le2": sum(1 for i in items if i["alive_segments"] <= 2), - "alive_single": sum(1 for i in items if i["alive_segments"] == 1), - "top_share_median": _median([i["top_share"] for i in items]), - } - - entry.update({ - "segments_in_window_mean": round(sum(r["segments_in_window"] for r in rows) / len(rows), 2) if rows else None, - "production_six": agg([r["production"] for r in rows]), - "segment_order_six": agg([r["segment_order"] for r in rows]), - **{f"segment_order_stop_{s}": agg([r[f"stop_{s}"] for r in rows]) for s in STOP_SHARES}, - "per_case": rows, - }) - block[name] = entry - out["by_radius"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# robustness -# --------------------------------------------------------------------------- - -def stage_robust(replays: dict[tuple[str, int], vr.CaseReplay], radii: Sequence[int], lmt_ids: set[str], mode: str = "raw") -> dict[str, Any]: - targets = {"D9": ("D9",), "D10": ("D10",)} - out: dict[str, Any] = {"mode": mode, "by_radius": {}} - for radius in radii: - block: dict[str, Any] = {} - reps = [(cid, rep) for (cid, r), rep in sorted(replays.items()) if r == radius] - for label, vargas in targets.items(): - entry: dict[str, Any] = {} - base = [] - for cid, rep in reps: - state = vr.replay_scores(rep.public, rep.probes, rep.true_time) - base.append((cid, vr.segment_shares(vr.minute_weights(state, mode), rep.segments(vargas), rep.true_time))) - entry["baseline"] = { - "n": len(base), - "truth_retained": sum(1 for _c, s in base if s["truth_retained"]), - "top_is_truth": sum(1 for _c, s in base if s["top_is_truth"]), - "lmt_era": { - "n": sum(1 for c, _s in base if c in lmt_ids), - "truth_retained": sum(1 for c, s in base if c in lmt_ids and s["truth_retained"]), - "top_is_truth": sum(1 for c, s in base if c in lmt_ids and s["top_is_truth"]), - }, - } - for flips in (1, 2): - retained: list[bool] = [] - correct: list[bool] = [] - for seed in range(vr.FLIP_SEEDS): - for cid, rep in reps: - answers = vr.flipped_answers(rep.probes, rep.true_time, flips=flips, seed=f"{cid}:{radius}:{flips}:{seed}") - state = vr.replay_scores(rep.public, rep.probes, rep.true_time, answers=answers) - share = vr.segment_shares(vr.minute_weights(state, mode), rep.segments(vargas), rep.true_time) - retained.append(share["truth_retained"]) - correct.append(share["top_is_truth"]) - entry[f"flip_{flips}"] = { - "replays": len(retained), - "truth_retained_rate": _rate(retained), - "top_is_truth_rate": _rate(correct), - } - shifted_retained: list[bool] = [] - shifted_correct: list[bool] = [] - for cid, rep in reps: - rows, probes, public = rep.shifted(vr.DAY_SHIFT, seed=f"{cid}:{radius}:shift") - state = vr.replay_scores(public, probes, rep.true_time) - share = vr.segment_shares(vr.minute_weights(state, mode), rep.segments(vargas), rep.true_time) - shifted_retained.append(share["truth_retained"]) - shifted_correct.append(share["top_is_truth"]) - entry["shift_7_days"] = { - "n": len(shifted_retained), - "truth_retained": sum(shifted_retained), - "top_is_truth": sum(shifted_correct), - } - block[label] = entry - out["by_radius"][str(radius)] = block - return out - - -# --------------------------------------------------------------------------- -# main -# --------------------------------------------------------------------------- - -def build_replays(cases: Sequence[dict[str, Any]], radii: Sequence[int], cache_dir: Path | None, log) -> dict[tuple[str, int], vr.CaseReplay]: - replays: dict[tuple[str, int], vr.CaseReplay] = {} - for case in cases: - for radius in radii: - started = time.perf_counter() - replays[(str(case["case_id"]), radius)] = vr.CaseReplay(case, radius, cache_dir=cache_dir) - log(f"{case['case_id']} ±{radius} ready in {time.perf_counter() - started:.1f}s") - return replays - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--dataset", default=str(vr.HOLDOUT_V5)) - parser.add_argument("--stages", default="m0,m1,m2,m3,robust") - parser.add_argument("--radii", default=",".join(str(r) for r in vr.RADII)) - parser.add_argument("--vargas", default=",".join(vr.VARGAS)) - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--cache-dir", default="") - parser.add_argument("--baseline-out", default=str(BASELINE_JSON)) - parser.add_argument("--json-out", default=str(REPORT_JSON)) - parser.add_argument("--quiet", action="store_true") - parser.add_argument("--posterior", choices=("research", "production"), default="research") - args = parser.parse_args() - if args.posterior == "production": - from scripts.research.varga_resolution_production_bridge import ProductionSegmentBridge - ProductionSegmentBridge().install(vr) - stages = {s.strip() for s in args.stages.split(",") if s.strip()} - radii = tuple(int(r) for r in args.radii.split(",") if r.strip()) - cache_dir = Path(args.cache_dir) if args.cache_dir else None - log = (lambda *_a, **_k: None) if args.quiet else (lambda msg: print(msg, flush=True)) - - started = time.perf_counter() - cases = vr.load_cases(Path(args.dataset)) - if args.limit: - cases = cases[: args.limit] - lmt_ids = {str(c["case_id"]) for c in cases if vr.is_lmt_era(c)} - signs60 = {str(c["case_id"]): vr.signs_per_minute(c, max(vr.COUNT_RADII), cache_dir=cache_dir) for c in cases} - log(f"signs ready for {len(signs60)} cases") - replays = build_replays(cases, radii, cache_dir, log) - - meta = { - "dataset": Path(args.dataset).name, - "case_count": len(cases), - "radii": list(radii), - "vargas": list(vr.VARGAS), - "ayanamsa": vr.AYANAMSA, - "node_mode": vr.NODE_MODE, - "minute_step_candidates": vr.MINUTE_STEP, - "minute_step_signs": 1, - "ask_count": vr.ASK_COUNT, - "separation_lead": vr.SEPARATION_LEAD, - "lmt_era_before_year": vr.LMT_ERA_BEFORE_YEAR, - "open_set_not_blind": True, - } - if args.posterior == "production": - sources = ["frontend/scripts/rectification-segment-bridge.ts", - "frontend/src/lib/rectification-agentic/core/build-state.ts", - "frontend/src/lib/rectification-agentic/core/apply-probe-outcome.ts", - "frontend/src/lib/rectification-agentic/core/segment-summary.ts", - "frontend/src/lib/rectification-agentic/core/segment-probe-order.ts", - "scripts/research/varga_resolution_production_bridge.py"] - meta["implementation_identity"] = { - "posterior": args.posterior, "python_version": platform.python_version(), - "scope": "m1 raw answers via buildInferenceState; mass/summary/gain via production TS; m2 loop remains research experiment, including >61", - "source_sha256": {name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() for name in sources}, - } - if "m0" in stages: - baseline = {**meta, **stage_m0(replays, signs60, radii)} - Path(args.baseline_out).write_text(vr.stable_json(baseline), encoding="utf-8") - log(f"m0 written to {args.baseline_out}") - report: dict[str, Any] = {**meta, "stages": sorted(stages - {"m0"})} - if "m1" in stages: - report["m1"] = stage_m1(replays, radii, lmt_ids) - log("m1 done") - if "m2" in stages: - report["m2"] = stage_m2(replays, radii) - log("m2 done") - if "m3" in stages: - report["m3"] = stage_m3(replays, signs60, radii) - log("m3 done") - if "robust" in stages: - report["robust"] = stage_robust(replays, radii, lmt_ids) - log("robust done") - if stages - {"m0"}: - # No wall-clock value goes into the JSON so two runs stay byte-identical. - Path(args.json_out).write_text(vr.stable_json(report), encoding="utf-8") - log(f"report written to {args.json_out}") - log(f"elapsed {time.perf_counter() - started:.0f}s") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/research/varga_sensitivity_rerun.py b/scripts/research/varga_sensitivity_rerun.py deleted file mode 100644 index 1770c835c..000000000 --- a/scripts/research/varga_sensitivity_rerun.py +++ /dev/null @@ -1,303 +0,0 @@ -#!/usr/bin/env python3 -"""R2 (2026-09-26): rerun of the M1b divisional-sensitivity weights V1 / V2. - -Offline only; production scoring (equal-weight vargas), probe gates and Skill -text are untouched. BUG-692 re-labelled the 09-14 V1/V2 verdict `not_measured` -because V1/V2 printed exactly the V0 numbers. This script first checks, per -case and radius, whether the V1/V2 weights change any candidate score at all -(and whether the research scorer copy equals production at V0), then reruns -the six-question replay with the closure-document metrics. - -V1n is a supplementary variant that is not in the 09-14 design: weight per -varga proportional to 1/minutes-per-ascendant-change, normalised so the mean -factor over the 11 production vargas is 1 (total varga mass unchanged, only -redistributed toward the fast vargas). It exists because V1 as specified is -capped at 1 and saturates. - -Public AA open set (v4). Not a blind test, not accuracy. - -Run: - python3 scripts/research/varga_sensitivity_rerun.py - python3 scripts/research/varga_sensitivity_rerun.py --limit 2 --no-write -""" - -from __future__ import annotations - -import argparse -import json -import sys -import traceback -from contextlib import contextmanager -from pathlib import Path -from typing import Any, Iterator, Sequence - -ROOT = Path(__file__).resolve().parents[2] -if str(ROOT) not in sys.path: - sys.path.insert(0, str(ROOT)) - -from scripts.active_rectification_event_engine import ( # noqa: E402 - AYANAMSA, - DOMAIN_CONFIG, - NODE_MODE, - compute_candidate_static_contexts, -) -import scripts.rectification.event_probes as event_probes # noqa: E402 -import scripts.research.precision_gate_lib as pgl # noqa: E402 -from scripts.research.cluster_width_lib import ( # noqa: E402 - merge_adjacent_traced, - public_from_clusters, - raw_signature_clusters, - top1_from_public, -) -from scripts.research.minute_resolution_sweep import MINUTE_STEP, scoring_request_for # noqa: E402 -from scripts.research.offline_research_20260926_lib import median_of, rate # noqa: E402 -from scripts.research.precision_gate_lib import ( # noqa: E402 - PRODUCTION_VARGA_PREFIXES, - finest_precision, - gate_verdict, - varga_factor, - varga_minutes, - window_minutes_for_radius, -) -from scripts.research.precision_gate_sweep import ( # noqa: E402 - run_variant, - score_bundle, - summarize, - varga_policy_for, -) - -HOLDOUT = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" -REPORT_JSON = ROOT / "docs" / "research" / "varga_sensitivity_rerun_2026_09_26.json" -RADII = (10, 30, 60) -VARIANTS = ("V0", "V1", "V2", "V1n") -EPS = 1e-9 - - -def v1n_factor_table() -> dict[str, float]: - inverse = {prefix: 1.0 / varga_minutes(prefix) for prefix in PRODUCTION_VARGA_PREFIXES} - mean = sum(inverse.values()) / len(inverse) - return {prefix: round(value / mean, 6) for prefix, value in inverse.items()} - - -V1N_FACTORS = v1n_factor_table() - - -@contextmanager -def v1n_factors() -> Iterator[None]: - """Swap the research module's varga_factor for the normalised table. - - Only the research module `precision_gate_lib` is patched, and it is - restored on exit. Production modules are never touched. - """ - previous = pgl.varga_factor - - def factor(prefix: str, window_minutes: float, cap: float = pgl.VARGA_CAP) -> float: - return float(V1N_FACTORS.get(prefix, 1.0)) - - pgl.varga_factor = factor - try: - yield - finally: - pgl.varga_factor = previous - - -def factor_table() -> dict[str, dict[str, float]]: - return { - str(radius): { - prefix: round(varga_factor(prefix, window_minutes_for_radius(radius)), 4) - for prefix in PRODUCTION_VARGA_PREFIXES - } - for radius in RADII - } - - -def score_map(rows: Sequence[dict[str, Any]]) -> dict[str, float]: - return {str(row["time"])[:5]: float(row.get("score") or 0) for row in rows} - - -def diff_stats(base: dict[str, float], other: dict[str, float]) -> dict[str, Any]: - deltas = [abs(other[time] - base[time]) for time in base if time in other] - changed = [item for item in deltas if item > EPS] - base_top = max(base, key=lambda time: (base[time], time)) if base else None - other_top = max(other, key=lambda time: (other[time], time)) if other else None - return { - "candidates": len(deltas), - "changed": len(changed), - "max_abs": round(max(deltas), 6) if deltas else 0.0, - "top_changed": base_top != other_top, - } - - -def engine_top1(rows: Sequence[dict[str, Any]], contexts: Sequence[dict[str, Any]], true_time: str) -> bool: - raw = raw_signature_clusters(contexts) - by_time = {str(row["time"])[:5]: row for row in rows} - merged, _ = merge_adjacent_traced(raw, by_time) - public = public_from_clusters(merged, rows) - for row in public: - row["score"] = float(row.get("score") or 0) - return top1_from_public(public, true_time) - - -def domain_prefix_drop(policy: Any, events: Sequence[dict[str, Any]]) -> dict[str, list[str]]: - dropped: dict[str, list[str]] = {} - for domain in sorted({str(event["domain"]) for event in events}): - prefixes = list(DOMAIN_CONFIG[domain][0]) - gone = [item for item in prefixes if item not in policy.changing] - if gone: - dropped[domain] = gone - return dropped - - -def run_case(case: dict[str, Any], radius: int) -> dict[str, Any]: - true_time = str(case["birth"]["time"])[:5] - request = scoring_request_for({**case, "candidate_radius_minutes": radius}, radius) - contexts = compute_candidate_static_contexts(request) - events = list(case.get("events") or []) - precision = finest_precision(events) - production = score_bundle(case, radius, events, contexts, None) - bundles: dict[str, dict[str, Any]] = {} - policies: dict[str, Any] = {} - for name in VARIANTS: - policy_name = "V1" if name == "V1n" else name - policy = varga_policy_for(policy_name, radius, contexts) - if name == "V1n": - with v1n_factors(): - bundles[name] = score_bundle(case, radius, events, contexts, policy) - else: - bundles[name] = score_bundle(case, radius, events, contexts, policy) - policies[name] = policy - prod_scores = score_map(production["rows"]) - v0_scores = score_map(bundles["V0"]["rows"]) - proof = { - "production_vs_V0_policy": diff_stats(prod_scores, v0_scores), - **{ - f"{name}_vs_V0": diff_stats(v0_scores, score_map(bundles[name]["rows"])) - for name in VARIANTS if name != "V0" - }, - "V0_varga_hits": dict(sorted(policies["V0"].hits.items())), - "V2_changing": sorted(policies["V2"].changing), - "V2_dropped_domain_prefixes": domain_prefix_drop(policies["V2"], events), - } - measured: dict[str, Any] = {} - for name in VARIANTS: - bundle = bundles[name] - row = run_variant( - request=bundle["request"], built=bundle["built"], rows=bundle["rows"], - true_time=true_time, gate="G0", precision=precision, - ) - row["engine_top1"] = engine_top1( - bundle["rows"], list(bundle["built"].get("static_contexts") or contexts), true_time, - ) - row["case_id"] = case["case_id"] - measured[name] = row - return {"case_id": case["case_id"], "radius": radius, "proof": proof, "measured": measured} - - -def proof_summary(case_rows: Sequence[dict[str, Any]]) -> dict[str, Any]: - out: dict[str, Any] = {} - for radius in sorted({row["radius"] for row in case_rows}): - rows = [row for row in case_rows if row["radius"] == radius] - block: dict[str, Any] = {} - for key in ["production_vs_V0_policy", *[f"{name}_vs_V0" for name in VARIANTS if name != "V0"]]: - stats = [row["proof"][key] for row in rows] - block[key] = { - "cases_with_any_change": sum(1 for item in stats if item["changed"]), - "cases": len(stats), - "candidates_changed": sum(item["changed"] for item in stats), - "candidates_total": sum(item["candidates"] for item in stats), - "max_abs_delta": max((item["max_abs"] for item in stats), default=0.0), - "cases_top_changed": sum(1 for item in stats if item["top_changed"]), - } - block["V2_cases_dropping_any_domain_prefix"] = sum( - 1 for row in rows if row["proof"]["V2_dropped_domain_prefixes"] - ) - hits: dict[str, int] = {} - for row in rows: - for prefix, count in row["proof"]["V0_varga_hits"].items(): - hits[prefix] = hits.get(prefix, 0) + int(count) - block["V0_varga_hits_total"] = dict(sorted(hits.items())) - out[str(radius)] = block - return out - - -def metric_summary(case_rows: Sequence[dict[str, Any]]) -> dict[str, Any]: - out: dict[str, Any] = {} - for radius in sorted({row["radius"] for row in case_rows}): - rows = [row for row in case_rows if row["radius"] == radius] - block: dict[str, Any] = {} - for name in VARIANTS: - measured = [row["measured"][name] for row in rows] - summary = summarize(measured) - summary["engine_top1"] = rate(measured, "engine_top1") - block[name] = summary - for name in VARIANTS: - if name == "V0": - continue - block[name]["verdict_vs_V0"] = gate_verdict(block["V0"], block[name]) - out[str(radius)] = block - return out - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument("--limit", type=int, default=0) - parser.add_argument("--radii", nargs="+", type=int, default=list(RADII)) - parser.add_argument("--no-write", action="store_true") - args = parser.parse_args() - holdout = json.loads(HOLDOUT.read_text(encoding="utf-8")) - cases = list(holdout["cases"])[: args.limit or None] - assert event_probes.MIN_BOUNDARY_DAYS == 45 and event_probes.REFRESH_MIN_BOUNDARY_DAYS == 30 - case_rows: list[dict[str, Any]] = [] - errors: list[dict[str, Any]] = [] - for case in cases: - for radius in args.radii: - try: - case_rows.append(run_case(case, radius)) - except Exception as exc: # noqa: BLE001 - errors.append({"case_id": case["case_id"], "radius": radius, - "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()}) - print(f"done {case['case_id']}", flush=True) - assert pgl.varga_factor is varga_factor, "research patch leaked" - payload = { - "generated_at": "2026-09-26", - "nature": "offline replay on the public AA open set (v4); not a blind test, not accuracy", - "ayanamsa": AYANAMSA, - "node_mode": NODE_MODE, - "holdout": str(HOLDOUT.relative_to(ROOT)), - "case_count": len(cases), - "radii": list(args.radii), - "minute_step": MINUTE_STEP, - "gate": "G0 production (45 / refresh 30)", - "factor_table_V1": factor_table(), - "factor_table_V1n": V1N_FACTORS, - "varga_minutes": {prefix: round(varga_minutes(prefix), 3) for prefix in PRODUCTION_VARGA_PREFIXES}, - "domain_prefixes": {domain: list(config[0]) for domain, config in DOMAIN_CONFIG.items()}, - "proof": proof_summary(case_rows), - "metrics": metric_summary(case_rows), - "per_case": [ - { - "case_id": row["case_id"], "radius": row["radius"], - "proof": row["proof"], - "measured": { - name: {key: row["measured"][name].get(key) for key in ( - "top1", "coverage", "width", "engine_top1", "probes", "refresh")} - for name in VARIANTS - }, - } - for row in case_rows - ], - "errors": errors, - "command": "python3 scripts/research/varga_sensitivity_rerun.py", - } - if not args.no_write: - REPORT_JSON.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") - print(json.dumps({"proof": payload["proof"], "errors": len(errors)}, ensure_ascii=False, indent=1)) - for radius, block in payload["metrics"].items(): - for name, summary in block.items(): - print(radius, name, {key: summary.get(key) for key in ( - "top1", "coverage", "width_median", "engine_top1", "verdict_vs_V0")}) - return 0 if not errors else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/run_quality_gate.py b/scripts/run_quality_gate.py index f13beb749..1175c65c9 100644 --- a/scripts/run_quality_gate.py +++ b/scripts/run_quality_gate.py @@ -69,7 +69,7 @@ CORE_PYTEST_TARGETS = [ # until listed here. "tests/test_rectification_*.py", "tests/test_varga_segments_api.py", - "tests/test_varga_resolution_research.py", + "tests/test_chart_choice.py", # This file regexes frontend source. Home-split and other page.tsx moves must keep it green. "tests/test_supabase_user_data_contract.py", # Consultation birth-accuracy invariants are pytest-style functions; unittest @@ -77,8 +77,6 @@ CORE_PYTEST_TARGETS = [ "tests/test_consultation_birth_accuracy.py", # Locks archive as PATCH archived_at, never HTTP DELETE (data-safety). "tests/test_session_management_entrypoints.py", - # Pure source/SQL regex for the birth-time journey; no runtime services. - "tests/test_birth_time_journey_contract.py", # Freeze scripts/jyotish_api_server.py growth; new features must be modules. "tests/test_api_server_growth_contract.py", # Silent-except and scripts-root budgets. New research scripts go under scripts/audit or scripts/research. diff --git a/scripts/timing_rectification_reviewer_freeze_status_2026_07_23.py b/scripts/timing_rectification_reviewer_freeze_status_2026_07_23.py deleted file mode 100644 index 4ac4caa68..000000000 --- a/scripts/timing_rectification_reviewer_freeze_status_2026_07_23.py +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env python3 -"""Record reviewer confirmation status for timing/rectification holdout candidates.""" -from __future__ import annotations - -import json -from datetime import date -from pathlib import Path -from typing import Any - - -ROOT = Path(__file__).resolve().parents[1] -CANDIDATES = ROOT / "references/real_case_calibration/timing_rectification_candidate_holdout_labels_2026_07_23.json" -DEFAULT_OUTPUT = ROOT / "references/real_case_calibration/timing_rectification_reviewer_freeze_status_2026_07_23.json" - - -def build_report(candidate_path: Path = CANDIDATES) -> dict[str, Any]: - candidates = json.loads(candidate_path.read_text(encoding="utf-8")) - cases = candidates.get("cases") or [] - reviewer_1 = { - "reviewer_id": "user_confirmed_business_owner", - "confirmation_text": "我确认这 3 个候选案例可以作为第一轮 holdout。", - "confirmed_at": "2026-07-23", - "independent_of_model_run": False, - "allowed_for_tuning": False, - "scope": "first_reviewer_acceptance_of_machine_prepared_candidates", - } - rows = [ - { - "case_id": case["case_id"], - "public_person": case["public_person"], - "positive_event_label": case["positive_event"]["label"], - "reviewer_1_status": "confirmed", - "reviewer_2_status": "missing", - "freeze_status": "one_reviewer_confirmed_second_required", - } - for case in cases - ] - return { - "scope": "timing_rectification_reviewer_freeze_status", - "created_at": date.today().isoformat(), - "claim_status": "one_reviewer_confirmed_second_required", - "truth_matrix_allowed": False, - "production_tuning_allowed": False, - "source_candidate_packet": str(candidate_path.relative_to(ROOT)), - "reviewer_1": reviewer_1, - "reviewer_2_required": True, - "summary": { - "case_count": len(rows), - "reviewer_1_confirmed_count": len(rows), - "reviewer_2_confirmed_count": 0, - "ready_for_blind_replay_count": 0, - }, - "rows": rows, - "next_action": "Collect a second independent reviewer confirmation before running blind timing/rectification replay.", - "boundary": "One reviewer confirmation advances candidate governance but does not satisfy the two-reviewer freeze requirement or upgrade timing claims.", - } - - -def main() -> int: - DEFAULT_OUTPUT.write_text(json.dumps(build_report(), ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") - print(json.dumps(build_report(), ensure_ascii=False, indent=2, sort_keys=True)) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tests/_baseline_rect_scoring_20261013.py b/tests/_baseline_rect_scoring_20261013.py deleted file mode 100644 index 1ae692a5d..000000000 --- a/tests/_baseline_rect_scoring_20261013.py +++ /dev/null @@ -1,245 +0,0 @@ -"""Baseline copies for TASK-rect-scoring-perf-20261013. - -Source commit: 77057a819 -git show 77057a819:scripts/rectification/event_probes.py sha256: 9bbadc246e6b8e94bb047522c3e5645613f508b3473ef40b38a207c77fdad58c -git show 77057a819:scripts/rectification/dasha_transition_proximity.py sha256: 0afba494aa12899621173c3cc941c6c1d0be9cec0bdf4c4a1c9bcd004ab22de8 - -The helpers these functions call are unchanged by this task and are imported -from the current modules. Only guided_collect_windows and -merge_transition_proximity differ from the copies below. -""" -from __future__ import annotations - -from datetime import date, datetime -from typing import Any, Sequence - -from scripts.rectification.dasha_transition_proximity import ( - _context_time as _proximity_context_time, - representative_event_date, - score_transition_proximity, -) -from scripts.rectification.event_probes import ( - GUIDED_ANY_DOMAIN, - GUIDED_COLLECT_LIMIT, - GUIDED_DOMAIN_ORDER, - _GUIDED_TRACK_DOMAIN, - _birth_year, - _context_time as _probe_context_time, - _guided_track_starts, - _guided_year_windows, - _narayana_start_dates, - _remaining_contexts, - _representative_pairs, - _scoreable, - _static_contexts, - _vim_start_dates, -) - -# Both copies call `_context_time`. They are rebound onto separate globals -# below so each keeps the helper it had in its source module. -_context_time = _probe_context_time - -def guided_collect_windows( - request: dict[str, Any], - built: dict[str, Any], - *, - candidate_times: Sequence[str], - today: date | None = None, -) -> list[dict[str, Any]]: - """Boundary windows for guided collect. Does not change auto probe generation.""" - birth_date = str(request.get("birth_date") or "").strip() - birth_year = _birth_year(birth_date) - if birth_year is None: - return [] - try: - datetime.strptime(birth_date, "%Y-%m-%d") - except ValueError: - return [] - remaining = _remaining_contexts(built, candidate_times) - if len(remaining) < 2: - remaining = _static_contexts(built) - work = [item for item in remaining if _scoreable(item)] - if len(work) < 2: - return [] - declined = { - str(item).strip() - for item in (request.get("declined_domains") or []) - if str(item).strip() in GUIDED_DOMAIN_ORDER - } - now = today or date.today() - lo, hi = birth_year + 5, min(now.year, birth_year + 80) - vim_cache: dict[tuple[Any, ...], list[date]] = {} - narayana_cache: dict[tuple[Any, ...], list[date] | None] = {} - starts_by_time: dict[str, dict[str, list[date]]] = {} - for context in work: - time = _context_time(context) - if not time: - continue - starts_by_time[time] = _guided_track_starts( - context, - birth_date=birth_date, - lo=lo, - hi=hi, - include_pratyantar=True, - varga_narayana=True, - vim_cache=vim_cache, - narayana_cache=narayana_cache, - ) - rows: list[dict[str, Any]] = [] - seen: set[tuple[int, int, int, str]] = set() - for left, right in _representative_pairs(work): - left_time = str(_context_time(left) or "") - right_time = str(_context_time(right) or "") - left_tracks = starts_by_time.get(left_time) or {} - right_tracks = starts_by_time.get(right_time) or {} - for track in ("vim", "nara", "nara:d9", "nara:d10"): - left_dates = left_tracks.get(track) or [] - right_dates = right_tracks.get(track) or [] - if not left_dates or not right_dates: - continue - for index, (one, two) in enumerate(zip(left_dates, right_dates)): - if one == two: - continue - gathered: list[date] = [] - for context in work: - time = _context_time(context) - dates = (starts_by_time.get(time or "") or {}).get(track) or [] - if index < len(dates): - gathered.append(dates[index]) - if len(gathered) < 2 or min(gathered) == max(gathered): - continue - ordered = sorted(gathered) - cut = ordered[0] + (ordered[-1] - ordered[0]) / 2 - left_n = sum(1 for item in gathered if item <= cut) - right_n = len(gathered) - left_n - if left_n < 1 or right_n < 1: - continue - # BUG-749: only the D9 / D10 Narayana tracks carry a domain. - # Vimshottari and natal Narayana boundaries say nothing about - # which area of life moved, so the window is asked open - # ("any") instead of being round-robined onto one domain. - track_domain = _GUIDED_TRACK_DOMAIN.get(track) - domain = ( - track_domain - if track_domain and track_domain not in declined - else GUIDED_ANY_DOMAIN - ) - for year, month_lo, month_hi in _guided_year_windows(gathered): - if year < lo or year > hi: - continue - key = (year, month_lo, month_hi, domain) - if key in seen: - continue - seen.add(key) - rows.append({ - "year": year, - "month_lo": month_lo, - "month_hi": month_hi, - "domain": domain, - "split": {"left": left_n, "right": right_n}, - }) - rows.sort(key=lambda row: ( - abs(row["split"]["left"] - row["split"]["right"]), - abs(now.year - int(row["year"])), - -int(row["year"]), - int(row["month_lo"]), - str(row["domain"]), - )) - return rows[:GUIDED_COLLECT_LIMIT] - - -def merge_transition_proximity( - matrix: dict[str, dict[str, dict[str, Any]]], - events: Sequence[dict[str, Any]], - static_contexts: Sequence[dict[str, Any]], - birth_date: str, - *, - public_technique_layers: Callable[[str, Sequence[str]], list[str]], -) -> None: - by_time = { - time: context - for context in static_contexts - if isinstance(context, dict) and (time := _context_time(context)) - } - vim_cache: dict[tuple[Any, ...], list[date]] = {} - pd_cache: dict[tuple[Any, ...], list[date]] = {} - narayana_cache: dict[tuple[Any, ...], list[date] | None] = {} - for event in events: - if not isinstance(event, dict): - continue - event_id = str(event.get("id") or "") - cells = matrix.get(event_id) - if not event_id or not isinstance(cells, dict): - continue - event_date = representative_event_date(event) - if event_date is None: - continue - precision = str(event.get("precision") or "") - lo, hi = event_date.year - 1, event_date.year + 1 - for time, cell in cells.items(): - context = by_time.get(str(time)[:5]) - if not isinstance(cell, dict) or not isinstance(context, dict): - continue - moon = (context.get("planet_longitudes") or {}).get("Moon") - if not isinstance(moon, (int, float)): - continue - # Native contexts retain the local date even when the window crosses midnight. - # Legacy time-only contexts still use the request's date. - candidate_at = context.get("candidate_at") - candidate_date = candidate_at.date().isoformat() if isinstance(candidate_at, datetime) else birth_date - vim_key = (candidate_date, round(float(moon), 6), lo, hi) - if vim_key not in vim_cache: - vim_cache[vim_key] = _vim_start_dates(candidate_date, float(moon), lo, hi) - pd_cache[vim_key] = _vim_start_dates( - candidate_date, - float(moon), - lo, - hi, - include_pratyantar=True, - ) - planets = context.get("planet_longitudes") or {} - asc = context.get("ascendant_index") - narayana_key = ( - candidate_date, - int(asc) if isinstance(asc, int) else None, - lo, - hi, - round(float(moon), 6), - ) - if narayana_key not in narayana_cache: - narayana_cache[narayana_key] = ( - _narayana_start_dates(int(asc), planets, candidate_date, lo, hi) - if isinstance(asc, int) and isinstance(planets, dict) - else None - ) - ad_starts = vim_cache[vim_key] - ad_set = set(ad_starts) - pd_only = [item for item in pd_cache[vim_key] if item not in ad_set] - scored = score_transition_proximity( - event_date=event_date, - precision=precision, - vim_starts=ad_starts, - vim_pd_starts=pd_only, - narayana_starts=narayana_cache[narayana_key] or [], - ) - if scored["points"] <= 0 and not scored["rule_ids"]: - continue - cell["points"] = round(float(cell.get("points") or 0) + float(scored["points"]), 4) - cell["rule_ids"] = sorted({ - *list(cell.get("rule_ids") or []), - *scored["rule_ids"], - }) - domain = str(event.get("domain") or cell.get("domain") or "") - cell["technique_layers"] = public_technique_layers(domain, cell["rule_ids"]) - - -import types as _types - -def _rebind(function, context_time): - globs = dict(function.__globals__) - globs["_context_time"] = context_time - return _types.FunctionType(function.__code__, globs, function.__name__) - - -guided_collect_windows = _rebind(guided_collect_windows, _probe_context_time) -merge_transition_proximity = _rebind(merge_transition_proximity, _proximity_context_time) diff --git a/tests/conftest.py b/tests/conftest.py index 12277cb03..668bbe110 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -54,9 +54,6 @@ def _isolate_vedastro_snapshot_cache(tmp_path_factory, monkeypatch) -> None: # Foreground failures are remembered for the day there too (issue #130). negative_dir = tmp_path_factory.mktemp("vedastro_snapshot_negative_cache") monkeypatch.setenv("JYOTISH_VEDASTRO_SNAPSHOT_NEGATIVE_CACHE_DIR", str(negative_dir)) - from scripts.rectification.vedastro_validate_cache import clear as clear_validate_memory - - clear_validate_memory() _FOREGROUND_EXECUTOR_MODULES = ( diff --git a/tests/test_active_rectification_events.py b/tests/test_active_rectification_events.py index 8972e6342..a2a021fd0 100644 --- a/tests/test_active_rectification_events.py +++ b/tests/test_active_rectification_events.py @@ -11,7 +11,6 @@ from scripts.active_rectification_events import ( precision_weight, score_life_events, ) -from scripts.rectification.scoring_service import build_event_contribution_matrix def _row(time: str, score: float) -> CandidateScoreRow: @@ -133,45 +132,6 @@ def test_date_precision_weights_are_fixed() -> None: assert precision_weight("year") == 0.5 -def test_matrix_legacy_adapter_preserves_event_kind() -> None: - seen = [] - - def rows(value): - event = value["events"][0] - seen.append(event["event_kind"]) - return [{ - "time": "05:13", - "score": 1.0, - "evidence": [{ - "event_id": event["id"], - "domain": event["domain"], - "candidate_time": "05:13", - "rule_ids": [f"event_kind:{event['event_kind']}"], - "points": 1.0, - }], - "missing_layers": [], - }] - - build_event_contribution_matrix({ - "birth_date": FIXTURE_BIRTH_DATE, - "start_time": "05:13", - "end_time": "05:13", - "lat": FIXTURE_BIRTH_LAT, - "lon": FIXTURE_BIRTH_LON, - "tz": 8.0, - "events": [{ - "id": "5cb071d6-6d99-46be-85dc-a9bf59ef6ac5", - "domain": "relationship", - "event_kind": "relationship_end", - "date_start": "2021-01-01", - "date_end": "2021-01-01", - "precision": "day", - }], - }, row_provider=rows) - - assert seen == ["relationship_end"] - - def test_relationship_event_kinds_reuse_activation_without_fake_offsets(monkeypatch) -> None: monkeypatch.setattr( event_engine.functional_benefics, diff --git a/tests/test_active_rectification_events_v4.py b/tests/test_active_rectification_events_v4.py deleted file mode 100644 index 41400df7a..000000000 --- a/tests/test_active_rectification_events_v4.py +++ /dev/null @@ -1,119 +0,0 @@ -from __future__ import annotations - -from datetime import date - -from scripts import active_rectification_events_v4 as v4 -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.scoring_service import calculation_spec, sha256 - - -def _row(candidate_time: str, event_id: str, points: float): - return { - "time": candidate_time, - "score": points, - "evidence": [{ - "event_id": event_id, - "domain": "education", - "candidate_time": candidate_time, - "rule_ids": ["test"], - "points": points, - }], - "missing_layers": [], - } - - -def test_v4_wrapper_uses_raman_spec_and_never_confirms_a_minute(monkeypatch) -> None: - calls = [] - - def fake_compute(request, static_contexts=None): - calls.append(request) - event_id = request["events"][0]["id"] - return [ - _row("05:13", event_id, 10), - _row("05:14", event_id, 9), - _row("05:15", event_id, 8), - ] - - monkeypatch.setattr("scripts.rectification.scoring_service.compute_event_candidate_rows", fake_compute) - monkeypatch.setattr("scripts.rectification.scoring_service.compute_candidate_static_contexts", lambda request: []) - result = v4.score_life_events_v4({ - "birth_date": "1997-08-08", - "start_time": "04:30", - "end_time": "05:30", - "lat": 36.419, - "lon": 114.213, - "tz": 8.0, - "events": [{ - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_milestone", - "date_start": "2016-09-01", - "date_end": "2016-09-30", - "precision": "month", - "summary": "大学入学", - }], - }) - assert [call["events"][0]["date"] for call in calls] == ["2016-09-01", "2016-09-15", "2016-09-30"] - assert result["can_confirm_exact_minute"] is False - assert result["calculation_spec"]["ayanamsa"] == "raman" - normalized = normalize_rectification_request({ - "birth_date": "1997-08-08", - "start_time": "04:30", - "end_time": "05:30", - "lat": 36.419, - "lon": 114.213, - "tz": 8.0, - "events": [{ - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_milestone", - "date_start": "2016-09-01", - "date_end": "2016-09-30", - "precision": "month", - "summary": "大学入学", - }], - }, today=date(2026, 7, 28)) - assert result["calculation_spec_hash"] == sha256(calculation_spec(normalized)) - - -def test_v4_api_validates_event_kind_and_date_boundaries(monkeypatch) -> None: - from scripts.jyotish_api_server import BadRequest, JyotishComputeService - - captured = {} - monkeypatch.setattr( - "scripts.rectification.api_service.score_candidates", - lambda request: captured.setdefault("request", request) or {}, - ) - handler = JyotishComputeService() - body = { - "birth_date": "1997-08-08", - "start_time": "05:00", - "end_time": "05:30", - "lat": 36.419, - "lon": 114.213, - "tz": 8, - "events": [{ - "id": "00000000-0000-4000-8000-000000000001", - "domain": "relationship", - "event_kind": "relationship_end", - "date_start": "2020-10-01", - "date_end": "2020-10-31", - "precision": "month", - "summary": "关系结束", - }], - } - result = handler._compute_active_rectification_events_v4(body) - assert result["endpoint"] == "active_rectification_events_v4" - assert captured["request"]["events"][0]["date_end"] == "2020-10-31" - - import pytest - with pytest.raises(BadRequest, match="event_kind does not match"): - handler._compute_active_rectification_events_v4({ - **body, - "events": [{**body["events"][0], "event_kind": "relationship_start", "domain": "career"}], - }) - with pytest.raises(BadRequest, match="date_start must not exceed"): - handler._compute_active_rectification_events_v4({ - **body, - "events": [{**body["events"][0], "date_start": "2020-11-01"}], - }) diff --git a/tests/test_active_rectification_selector.py b/tests/test_active_rectification_selector.py index 050ac1cb7..09a4f001f 100644 --- a/tests/test_active_rectification_selector.py +++ b/tests/test_active_rectification_selector.py @@ -1,11 +1,8 @@ from __future__ import annotations -import hashlib -import json -from scripts.active_rectification_questions import build_questionnaire, score_answers +from scripts.active_rectification_questions import build_questionnaire from scripts.active_rectification_selector import select_next_questions -from scripts.rectification.scoring_service import score_from_matrix def test_selector_asks_one_question_and_ranks_by_separation() -> None: @@ -206,94 +203,3 @@ def test_fictional_adaptive_interview_records_each_selected_question_and_minute_ ] assert select_next_questions(questionnaire, answers)["stop"] is True - -def test_selector_changes_do_not_change_legacy_or_v5_score_bytes() -> None: - questions = [ - {**_minute_question("relationship_split", "relationship", "D9"), "round": 1}, - {**_minute_question("career_split", "career", "D10"), "round": 2}, - ] - answers = {"relationship_split": "A", "career_split": "C"} - questionnaires = [ - { - "questions": questions, - "candidate_scan": {"candidate_count": 3, "minute_scan": _minute_window("D9")}, - }, - { - "questions": questions, - "candidate_scan": {"candidate_count": 3, "minute_scan": _minute_window("D10")}, - }, - ] - selections = [select_next_questions(questionnaire, {}) for questionnaire in questionnaires] - assert [selection["selected_questions"][0]["id"] for selection in selections] == [ - "relationship_split", - "career_split", - ] - - legacy_bytes = [] - for questionnaire in questionnaires: - scored = score_answers(questionnaire, answers) - legacy_contract = { - key: value - for key, value in scored.items() - if key not in {"calculation", "next_round_selection"} - } - legacy_bytes.append(json.dumps( - legacy_contract, - ensure_ascii=True, - sort_keys=True, - separators=(",", ":"), - ).encode()) - assert legacy_bytes[0] == legacy_bytes[1] - assert hashlib.sha256(legacy_bytes[0]).hexdigest() == "bb1a300606458357b2b8d94a487272f15d82c6f0b51847c660ba20153773fb63" - - v5_request = { - "birth_date": "1997-08-08", - "start_time": "05:13", - "end_time": "05:14", - "lat": 36.419, - "lon": 114.213, - "tz": 8.0, - "events": [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_start", - "date_start": "2016-09-01", - "date_end": "2016-09-30", - "precision": "month", - "summary": "fictional enrollment", - "subject": "self", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "career", - "event_kind": "career_entry", - "date_start": "2020-07-01", - "date_end": "2020-07-31", - "precision": "month", - "summary": "fictional first role", - "subject": "self", - }, - ], - } - built = { - "candidate_times": ["05:13", "05:14"], - "matrix": { - v5_request["events"][0]["id"]: { - "05:13": {"points": 4.0, "rule_ids": ["D24:fixture"]}, - "05:14": {"points": 1.0, "rule_ids": ["D24:fixture"]}, - }, - v5_request["events"][1]["id"]: { - "05:13": {"points": -1.0, "rule_ids": ["D10:fixture"]}, - "05:14": {"points": 3.0, "rule_ids": ["D10:fixture"]}, - }, - }, - "missing_layers": [], - } - v5_bytes = json.dumps( - score_from_matrix(v5_request, built), - ensure_ascii=True, - sort_keys=True, - separators=(",", ":"), - ).encode() - assert hashlib.sha256(v5_bytes).hexdigest() == "23171c47b9746f4b0a440c9b9ac6d8401d622672cd0d6d780789334b732e9d8f" diff --git a/tests/test_api_heavy_compute_gate.py b/tests/test_api_heavy_compute_gate.py index 8481bc07c..fe4475f24 100644 --- a/tests/test_api_heavy_compute_gate.py +++ b/tests/test_api_heavy_compute_gate.py @@ -111,7 +111,7 @@ def test_health_and_light_paths_are_not_gated() -> None: assert not is_heavy_compute_path("/api/location/resolve") assert not is_heavy_compute_path("/api/chart/jobs/abc") assert not is_heavy_compute_path("/api/high_rigor_workflow/jobs/abc") - assert not is_heavy_compute_path("/api/rectification/v5/versions") + assert not is_heavy_compute_path("/api/chart_choice/packet") assert is_heavy_compute_path("/api/high_rigor_workflow") assert is_heavy_compute_path("/api/professional_report_reference") assert is_heavy_compute_path("/api/rectification/sensitivity_scan") @@ -268,7 +268,7 @@ def _wait_until(predicate, timeout: float = 2.0) -> bool: def test_third_request_gets_the_slot_after_one_holder_releases() -> None: reset_heavy_compute_gate(limit=2, retry_after_seconds=2, wait_seconds=2, max_waiters=4) first = acquire_heavy_compute_slot("/api/consultation_workflow") - second = acquire_heavy_compute_slot("/api/rectification/v5/score") + second = acquire_heavy_compute_slot("/api/rectification/v5/range_reading") assert first is not None and second is not None found: dict = {} @@ -304,7 +304,7 @@ def test_waiter_overflow_rejects_immediately() -> None: assert _wait_until(lambda: heavy_compute_waiter_count() == 1) started = time.monotonic() with pytest.raises(HeavyComputeBusy) as caught: - acquire_heavy_compute_slot("/api/rectification/v5/score") + acquire_heavy_compute_slot("/api/rectification/v5/range_reading") assert time.monotonic() - started < 0.3 assert caught.value.retry_after_seconds == 2 assert caught.value.error_code == "ERR_COMPUTE_BUSY" diff --git a/tests/test_api_server_growth_contract.py b/tests/test_api_server_growth_contract.py index d8007a82b..2c7141195 100644 --- a/tests/test_api_server_growth_contract.py +++ b/tests/test_api_server_growth_contract.py @@ -175,9 +175,6 @@ _HTTP_METHOD_NAMES = frozenset({ "_error_json", "_get_chart_job", "_get_high_rigor_job", - "_require_dynamic_rectification_token", - "_compute_dynamic_rectification_score", - "_compute_dynamic_rectification_opportunities", }) diff --git a/tests/test_api_server_security.py b/tests/test_api_server_security.py index a8d870857..a4ee21ba5 100644 --- a/tests/test_api_server_security.py +++ b/tests/test_api_server_security.py @@ -1610,7 +1610,9 @@ def test_capability_audit_scans_registry_and_local_sources() -> None: # 原值: admin/products 后面直接是 admin/roles # 新值: 中间加入 admin/rectification-telemetry # 原因: 匿名校正统计的后台汇总页(TASK-rectification-telemetry-20260926)是新的 app 路由 - 'admin/rectification-telemetry', + # 原值: 'admin/rectification-telemetry' + # 新值: 删除 + # 原因: BUG-1644 下线对话式生时校正,匿名校正统计页随之删除 # 原值: admin/rectification-telemetry 后面直接是 admin/roles # 新值: 中间加入 admin/reply-quality # 原因: 「对话质量记录」后台页(点踩快照,2026-09-30 合规轮)是新的 app 路由 diff --git a/tests/test_birth_time_journey_contract.py b/tests/test_birth_time_journey_contract.py deleted file mode 100644 index 8aaa1e2c2..000000000 --- a/tests/test_birth_time_journey_contract.py +++ /dev/null @@ -1,313 +0,0 @@ -import re -from pathlib import Path - -MIGRATION = ( - Path(__file__).resolve().parents[1] - / "frontend" - / "supabase" - / "migrations" - / "20260717020000_birth_time_journey.sql" -) -FRONTEND = Path(__file__).resolve().parents[1] / "frontend" -EVIDENCE_MIGRATION = ( - MIGRATION.parent / "20260718010000_birth_time_evidence_rectification.sql" -) -AGENT_GUIDED_MIGRATION = ( - MIGRATION.parent / "20260718020000_agent_guided_birth_time_rectification.sql" -) -SCORING_JOB_MIGRATION = ( - MIGRATION.parent / "20260718030000_birth_time_scoring_job_lifecycle.sql" -) - - -def _sql() -> str: - return re.sub(r"\s+", " ", MIGRATION.read_text(encoding="utf-8").lower()).strip() - - -def test_birth_time_service_role_can_update_journey_profile_columns() -> None: - migrations = sorted(MIGRATION.parent.glob("*.sql")) - sql = re.sub( - r"\s+", - " ", - "\n".join(path.read_text(encoding="utf-8") for path in migrations).lower(), - ).strip() - - assert ( - "grant update ( reported_birth_time, active_birth_time, birth_time, " - "birth_time_source, birth_time_period, birth_time_clue, " - "uncertainty_before_minutes, uncertainty_after_minutes, " - "birth_time_status, rectification_confidence, rectification_case_id " - ") on table public.profiles to service_role" - ) in sql - - -def test_birth_time_profile_contract_separates_reported_and_active_times() -> None: - sql = _sql() - - for definition in ( - "reported_birth_time time without time zone", - "active_birth_time time without time zone", - "birth_time_source text", - "birth_time_period text", - "birth_time_clue text", - "uncertainty_before_minutes integer", - "uncertainty_after_minutes integer", - "birth_time_status text", - "rectification_confidence numeric(5, 2)", - "rectification_case_id uuid", - ): - assert f"add column if not exists {definition}" in sql - - assert "reported_birth_time = coalesce(reported_birth_time, birth_time)" in sql - assert "active_birth_time = coalesce(active_birth_time, birth_time)" in sql - assert "birth_time_source = coalesce(birth_time_source, 'legacy_import')" in sql - assert "birth_time_status = coalesce(birth_time_status, 'confirmed')" in sql - assert "old.reported_birth_time is not null" in sql - assert "new.reported_birth_time is distinct from old.reported_birth_time" in sql - assert "raise exception 'reported_birth_time_is_immutable'" in sql - assert "new.birth_time := new.active_birth_time" in sql - assert "revoke update (birth_time) on table public.profiles from authenticated" in sql - client_grant = sql.split("grant update ( reported_birth_time", 1)[1] - client_grant = client_grant.split(") on table public.profiles to authenticated", 1)[0] - assert "active_birth_time" not in client_grant - assert "birth_time_status" not in client_grant - assert "rectification_case_id" not in client_grant - - -def test_birth_time_profile_contract_constrains_deterministic_states() -> None: - sql = _sql() - - for value in ( - "hospital_record", - "family_exact", - "approximate", - "period_only", - "unknown", - "legacy_import", - ): - assert f"'{value}'" in sql - - for value in ("reported", "assessing", "rectifying", "candidate", "confirmed"): - assert f"'{value}'" in sql - - assert "uncertainty_before_minutes between 0 and 720" in sql - assert "uncertainty_after_minutes between 0 and 720" in sql - assert "rectification_confidence between 0 and 100" in sql - - -def test_rectification_cases_are_owner_scoped_and_auditable() -> None: - sql = _sql() - - assert "create table if not exists public.birth_time_rectification_cases" in sql - for definition in ( - "id uuid primary key default gen_random_uuid()", - "user_id uuid not null references auth.users(id) on delete cascade", - "questionnaire jsonb not null default '{}'::jsonb", - "journey_snapshot jsonb not null default '{}'::jsonb", - "answers jsonb not null default '{}'::jsonb", - "candidate_scan jsonb not null default '{}'::jsonb", - "scoring_result jsonb not null default '{}'::jsonb", - "algorithm_version text not null default 'birth-time-journey-v1'", - "ayanamsa text not null default 'lahiri'", - "node_mode text not null default 'true'", - "confirmed_at timestamptz", - ): - assert definition in sql - - assert "alter table public.birth_time_rectification_cases enable row level security" in sql - assert "birth_time_cases_select_own" in sql - assert "birth_time_cases_insert_own" in sql - assert "birth_time_cases_update_own" in sql - assert "using ((select auth.uid()) = user_id)" in sql - assert "with check ((select auth.uid()) = user_id)" in sql - assert "grant select on table public.birth_time_rectification_cases to authenticated" in sql - assert "grant insert" in sql - assert "grant update" in sql - assert "grant delete" not in sql - - -PAGE = FRONTEND / "src" / "app" / "(app)" / "page.tsx" -HOME_SURFACE_FILES = ( - PAGE, - FRONTEND / "src" / "lib" / "home-types.ts", - FRONTEND / "src" / "lib" / "home-profile.ts", - FRONTEND / "src" / "lib" / "home-cloud-sync.ts", - FRONTEND / "src" / "components" / "birth-location-fields.tsx", - FRONTEND / "src" / "components" / "profile-fields.tsx", - FRONTEND / "src" / "components" / "onboarding-chat-message.tsx", - FRONTEND / "src" / "components" / "home-onboarding-shell.tsx", - FRONTEND / "src" / "components" / "people" / "people-page.tsx", - FRONTEND / "src" / "components" / "starter-home.tsx", -) -OPTIONAL_HOME_HOOKS = ( - FRONTEND / "src" / "hooks" / "use-session-management.ts", - FRONTEND / "src" / "hooks" / "use-consultation-run.ts", - FRONTEND / "src" / "hooks" / "use-profile-onboarding.ts", - FRONTEND / "src" / "hooks" / "use-rectification-surface.ts", -) - - -def _home_surface() -> str: - parts = [path.read_text(encoding="utf-8") for path in HOME_SURFACE_FILES] - parts.extend( - path.read_text(encoding="utf-8") for path in OPTIONAL_HOME_HOOKS if path.exists() - ) - return "".join(parts) - - -def _mastra_consultation_surface() -> str: - return "".join( - path.read_text(encoding="utf-8") - for path in ( - FRONTEND / "src" / "mastra" / "index.ts", - FRONTEND / "src" / "mastra" / "consultation-workflow.ts", - ) - ) - - -def test_home_surface_requires_the_app_route_group_page() -> None: - assert PAGE.is_file() - assert PAGE.parts[-2:] == ("(app)", "page.tsx") - assert not FRONTEND.joinpath("src", "app", "page.tsx").exists() - - -def test_web_onboarding_uses_the_deterministic_free_journey() -> None: - page = _home_surface() - route = ( - FRONTEND / "src" / "app" / "api" / "birth-time-journey" / "route.ts" - ).read_text(encoding="utf-8") - mastra = _mastra_consultation_surface() - - assert " None: - sql = re.sub( - r"\s+", - " ", - EVIDENCE_MIGRATION.read_text(encoding="utf-8").lower(), - ).strip() - - for definition in ( - "life_events jsonb not null default '[]'::jsonb", - "candidate_result jsonb not null default '{}'::jsonb", - "event_scoring_version text", - "candidate_result_id uuid", - "candidate_saved_at timestamptz", - ): - assert f"add column if not exists {definition}" in sql - - assert "'confirming'" in sql - assert ( - "revoke update ( life_events, candidate_result, event_scoring_version, " - "candidate_result_id, candidate_saved_at, confirmed_time, confirmed_at " - ") on table public.birth_time_rectification_cases from authenticated" - ) in sql - assert "grant all on table public.birth_time_rectification_cases to service_role" in sql - - -def test_agent_guided_rectification_migration_versions_turns_and_jobs() -> None: - sql = re.sub( - r"\s+", " ", AGENT_GUIDED_MIGRATION.read_text(encoding="utf-8").lower() - ).strip() - - for definition in ( - "turn_version bigint not null default 0", - "turn_state jsonb not null default '{}'::jsonb", - "evidence_draft jsonb", - "processed_action_ids uuid[] not null default '{}'::uuid[]", - "adaptive_round integer not null default 0", - "asked_domains text[] not null default '{}'::text[]", - ): - assert f"add column if not exists {definition}" in sql - - assert "jsonb_typeof(turn_state) = 'object'" in sql - assert "evidence_draft is null or jsonb_typeof(evidence_draft) = 'object'" in sql - assert "cardinality(processed_action_ids) <= 100" in sql - assert "adaptive_round between 0 and 3" in sql - assert "birth_time_rectification_scoring_jobs" in sql - assert "id uuid primary key default gen_random_uuid()" in sql - assert "case_id uuid not null references public.birth_time_rectification_cases(id) on delete cascade" in sql - assert "status text not null default 'pending'" in sql - assert "expires_at timestamptz not null" in sql - assert "unique (case_id, evidence_fingerprint, algorithm_version)" in sql - assert "revoke all on table public.birth_time_rectification_scoring_jobs from anon, authenticated" in sql - assert "grant all on table public.birth_time_rectification_scoring_jobs to service_role" in sql - - -def test_scoring_job_lifecycle_is_atomic_and_service_role_only() -> None: - sql = re.sub( - r"\s+", " ", SCORING_JOB_MIGRATION.read_text(encoding="utf-8").lower() - ).strip() - - for function_name in ( - "create_birth_time_scoring_job", - "claim_birth_time_scoring_job", - "complete_birth_time_scoring_job", - "fail_birth_time_scoring_job", - ): - assert f"create or replace function public.{function_name}" in sql - assert f"revoke all on function public.{function_name}" in sql - assert f"grant execute on function public.{function_name}" in sql - - create_body = sql.split("create or replace function public.create_birth_time_scoring_job", 1)[1] - create_body = create_body.split("create or replace function public.claim_birth_time_scoring_job", 1)[0] - assert "update public.birth_time_rectification_cases" in create_body - assert "insert into public.birth_time_rectification_scoring_jobs" in create_body - assert "and user_id = p_user_id" in create_body - assert "and turn_version = p_expected_version" in create_body - - claim_body = sql.split("create or replace function public.claim_birth_time_scoring_job", 1)[1] - claim_body = claim_body.split("create or replace function public.complete_birth_time_scoring_job", 1)[0] - assert "j.case_id = p_case_id" in claim_body - assert "j.user_id = p_user_id" in claim_body - assert "v_job.evidence_fingerprint is distinct from p_evidence_fingerprint" in claim_body - assert "v_job.algorithm_version is distinct from p_algorithm_version" in claim_body - assert claim_body.index( - "v_job.algorithm_version is distinct from p_algorithm_version" - ) < claim_body.index("update public.birth_time_rectification_scoring_jobs") - assert "#>> '{nextaction,jobid}' is distinct from p_job_id::text" in claim_body - assert "#>> '{nextaction,kind}' is distinct from" in claim_body - assert "status in ('pending', 'failed', 'processing')" in claim_body - assert "status = 'processing'" in claim_body - assert "v_job.updated_at <= p_now - interval '60 seconds'" in claim_body - assert "expires_at = p_now + interval '15 minutes'" in claim_body - assert "birth_time_scoring_job_expired" not in claim_body - assert "v_candidate_result is distinct from v_job.result" in claim_body - assert "birth_time_scoring_result_inconsistent" in claim_body - - complete_body = sql.split("create or replace function public.complete_birth_time_scoring_job", 1)[1] - complete_body = complete_body.split("create or replace function public.fail_birth_time_scoring_job", 1)[0] - assert "update public.birth_time_rectification_scoring_jobs" in complete_body - assert "update public.birth_time_rectification_cases" in complete_body - - fail_body = sql.split("create or replace function public.fail_birth_time_scoring_job", 1)[1] - assert "update public.birth_time_rectification_scoring_jobs" in fail_body - assert "update public.birth_time_rectification_cases" in fail_body - assert "security definer" in sql - assert "to service_role" in sql - - -def test_poll_scoring_route_authenticates_before_parsing() -> None: - route = ( - FRONTEND / "src" / "app" / "api" / "birth-time-journey" / "route.ts" - ).read_text(encoding="utf-8") - - assert route.index("supabase.auth.getUser()") < route.index( - "birthTimeJourneyRequestSchema.safeParse" - ) - assert 'case "poll_scoring"' in route - assert "service.pollScoringJob(" in route diff --git a/tests/test_candidate_discriminator_contract.py b/tests/test_candidate_discriminator_contract.py index 23cc804bf..f311239b8 100644 --- a/tests/test_candidate_discriminator_contract.py +++ b/tests/test_candidate_discriminator_contract.py @@ -103,452 +103,5 @@ def _gate_events() -> list[dict]: ] -def _request(**extra: object) -> dict: - return { - "birth_date": "1997-08-08", - "events": _gate_events(), - **extra, - } - - -class DiscriminatorContractTest(unittest.TestCase): - def test_ci_forbids_invalid_distinguish_payloads(self) -> None: - self.assertEqual( - distinguish_contract_errors({ - "role": "distinguish", - "information_gain": 0, - "candidate_ids": ["05:00", "05:20"], - "expected_outcomes": [ - {"answer_class": "yes", "supports": ["05:00"], "conflicts": ["05:20"]}, - {"answer_class": "no", "supports": ["05:20"], "conflicts": ["05:00"]}, - ], - }), - ["distinguish_non_positive_information_gain"], - ) - self.assertEqual( - distinguish_contract_errors({ - "role": "distinguish", - "information_gain": 0.4, - "candidate_ids": [], - "expected_outcomes": [ - {"answer_class": "yes", "supports": [], "conflicts": []}, - {"answer_class": "no", "supports": [], "conflicts": []}, - ], - }), - ["distinguish_empty_candidate_ids"], - ) - self.assertEqual( - distinguish_contract_errors({ - "role": "distinguish", - "information_gain": 0.4, - "candidate_ids": ["05:00", "05:20"], - "expected_outcomes": [], - }), - ["distinguish_empty_expected_outcomes"], - ) - - def test_quality_clarify_stays_and_anchored_distinguish_is_gated(self) -> None: - built = { - "static_contexts": [ - _context("05:13", d4_asc=1, d9_asc=1), - _context("05:40", d4_asc=2, d9_asc=4), - ] - } - events = _gate_events() + [{ - "id": "exam", - "domain": "education", - "event_kind": "education_milestone", - "summary": "入学考试", - "date": "2015-06-01", - "precision": "year", - }] - request = _request(events=events) - probes = discriminating_event_probes( - request, - built, - scan=window_scan(built), - candidate_times=["05:13", "05:40"], - representative_time="05:13", - today=date(2026, 8, 22), - ) - self.assertFalse(any(item.get("role") == "distinguish" and distinguish_contract_errors(item) for item in probes)) - quality = [item for item in probes if item.get("source") == "known_event_quality"] - for item in quality: - self.assertEqual(item.get("role"), "distinguish") - self.assertTrue(item.get("target_evidence_id")) - self.assertEqual(item.get("choice_kind"), "event_quality") - clarification = event_clarification_probes(request) - self.assertTrue(any(item.get("source") == "known_event_quality" for item in clarification)) - self.assertTrue(all(item.get("phase") == "event_clarification" for item in clarification)) - self.assertFalse(any(item.get("role") == "distinguish" for item in clarification)) - - def test_gate_blocks_discriminator_until_three_events_two_domains(self) -> None: - built = { - "static_contexts": [ - _context("05:13", d4_asc=1), - _context("05:40", d4_asc=2), - ] - } - too_few = discriminating_event_probes( - {"birth_date": "1997-08-08", "events": _gate_events()[:2]}, - built, - scan=window_scan(built), - candidate_times=["05:13", "05:40"], - representative_time="05:13", - today=date(2026, 8, 22), - ) - self.assertEqual(too_few, []) - collection = evidence_collection_probes({"birth_date": "1997-08-08", "events": _gate_events()[:2]}) - self.assertTrue(collection) - self.assertTrue(all(item.get("phase") == "evidence_collection" for item in collection)) - self.assertGreaterEqual(MIN_DISCRIMINATOR_EVENTS, 3) - self.assertGreaterEqual(MIN_DISCRIMINATOR_DOMAINS, 2) - - def test_training_gate_opens_at_three_events_when_holdout_is_not_reserved(self) -> None: - two = _gate_events()[:2] - three = _gate_events()[:3] - four = _gate_events() - # 原值: 3 件留 holdout 后门关;4 件才开 - # 新值: 3 件全训练、门开;4 件才留 1 件 holdout - # 原因: BUG-647 - self.assertFalse(discriminator_gate_open(two)) - self.assertTrue(discriminator_gate_open(three)) - two_count, _, _ = training_scoreable_stats(two) - three_count, three_domains, _ = training_scoreable_stats(three) - four_count, four_domains, _ = training_scoreable_stats(four) - self.assertLess(two_count, MIN_DISCRIMINATOR_EVENTS) - self.assertGreaterEqual(three_count, MIN_DISCRIMINATOR_EVENTS) - self.assertGreaterEqual(four_count, MIN_DISCRIMINATOR_EVENTS) - self.assertGreaterEqual(three_domains, MIN_DISCRIMINATOR_DOMAINS) - self.assertGreaterEqual(four_domains, MIN_DISCRIMINATOR_DOMAINS) - from scripts.rectification.case_holdout import holdout_event_ids, holdout_reservation_status - self.assertEqual(holdout_reservation_status(three), "not_reserved_min_events") - self.assertEqual(len(holdout_event_ids(three)), 0) - self.assertEqual(holdout_reservation_status(four), "reserved") - self.assertEqual(len(holdout_event_ids(four)), 1) - built = { - "static_contexts": [ - _context("05:13", d4_asc=0, sun_house=4, sun_varga_sign=3), - _context("05:40", d4_asc=1, sun_house=10, sun_varga_sign=9), - ] - } - three_probes = discriminating_event_probes( - {"birth_date": "1997-08-08", "events": three}, - built, - scan=window_scan(built), - candidate_times=["05:13", "05:40"], - representative_time="05:13", - today=date(2026, 8, 22), - ) - four_probes = discriminating_event_probes( - {"birth_date": "1997-08-08", "events": four}, - built, - scan=window_scan(built), - candidate_times=["05:13", "05:40"], - representative_time="05:13", - today=date(2026, 8, 22), - ) - self.assertTrue(three_probes) - self.assertTrue(four_probes) - self.assertGreater(three_domains, 0) - - def test_signature_clusters_are_not_three_adjacent_minutes(self) -> None: - rows = [ - {"time": "05:13", "score": 20}, - {"time": "05:14", "score": 19}, - {"time": "05:15", "score": 18}, - {"time": "05:40", "score": 12}, - ] - contexts = [ - _context("05:13", d4_asc=1, d9_asc=1), - _context("05:14", d4_asc=1, d9_asc=1), - _context("05:15", d4_asc=1, d9_asc=1), - _context("05:40", d4_asc=2, d9_asc=4), - ] - public = select_signature_representatives(rows, contexts) - times = [row["time"] for row in public] - self.assertIn("05:40", times) - self.assertLessEqual(sum(1 for time in times if time in {"05:13", "05:14", "05:15"}), 1) - self.assertNotEqual(feature_signature(contexts[0]), feature_signature(contexts[3])) - self.assertEqual(SIGNATURE_LAYERS[:6], ("d1", "d9", "d10", "d24", "d4", "d12")) - self.assertIn("md", SIGNATURE_LAYERS) - - def test_staging_quick_gate_runs_this_contract(self) -> None: - from pathlib import Path - text = Path("scripts/run_quality_gate.py").read_text(encoding="utf-8") - self.assertIn('"tests/test_candidate_discriminator_contract.py"', text) - - def test_randomized_hidden_mutated_splits_keep_mapping_and_gain(self) -> None: - rng = random.Random(20260826) - built = { - "static_contexts": [ - _context("04:50", d4_asc=0, d9_asc=1, d10_asc=2, moon=99.0), - _context("05:20", d4_asc=3, d9_asc=6, d10_asc=8, moon=101.5), - ] - } - for _ in range(12): - events = list(_gate_events()) - rng.shuffle(events) - for event in events: - event = dict(event) - event["summary"] = rng.choice(["记不清细节", "家里提过", "档案上有"]) - request = _request(events=events) - probes = discriminating_event_probes( - request, - built, - scan=window_scan(built), - candidate_times=["04:50", "05:20"], - representative_time="04:50", - today=date(2026, 8, 22), - ) - self.assertFalse(any( - item.get("source") == "known_event_quality" - and not item.get("target_evidence_id") - for item in probes - )) - for probe in probes: - self.assertEqual(distinguish_contract_errors(probe), []) - self.assertGreater(float(probe["information_gain"]), 0) - self.assertGreaterEqual(len(probe["candidate_ids"]), 2) - self.assertGreaterEqual(len(probe["expected_outcomes"]), 2) - self.assertTrue(probe["candidate_set_version"]) - self.assertTrue(probe["candidate_split_hash"]) - self.assertNotEqual(probe["candidate_split_hash"], f"{probe['domain']}:{probe['year']}") - opportunities = candidate_contrast_opportunities( - request, - built, - scan=window_scan(built), - candidate_times=["04:50", "05:20"], - representative_time="04:50", - today=date(2026, 8, 22), - ) - for opportunity in opportunities: - self.assertGreater(float(opportunity["information_gain"]), 0) - self.assertGreaterEqual(len(opportunity["candidate_groups"]), 2) - self.assertGreaterEqual(len(opportunity["expected_outcomes"]), 2) - self.assertTrue(opportunity["domain"]) - self.assertTrue(opportunity["source_features"]) - - def test_collection_reserves_holdout_out_of_scoring_and_probes(self) -> None: - from scripts.rectification.case_holdout import holdout_domain_years, holdout_event_ids - from scripts.rectification.scoring_service import score_from_matrix - - events = _gate_events() - holdout = holdout_event_ids(events) - self.assertEqual(len(holdout), 1) - holdout_id = next(iter(holdout)) - built = { - "candidate_times": ["05:00", "05:20"], - "matrix": { - "e1": { - "05:00": {"points": 10, "rule_ids": []}, - "05:20": {"points": 1, "rule_ids": []}, - }, - "e2": { - "05:00": {"points": 10, "rule_ids": []}, - "05:20": {"points": 1, "rule_ids": []}, - }, - "e3": { - "05:00": {"points": 100, "rule_ids": []}, - "05:20": {"points": 0, "rule_ids": []}, - }, - "e4": { - "05:00": {"points": 4, "rule_ids": []}, - "05:20": {"points": 1, "rule_ids": []}, - }, - }, - "missing_layers": [], - } - request = { - "birth_date": "1997-08-08", - "start_time": "04:50", - "end_time": "05:30", - "lat": 31.2, - "lon": 121.5, - "tz": 8.0, - "events": [ - { - "id": event["id"], - "domain": event["domain"], - "event_kind": event["event_kind"], - "date_start": event["date"], - "date_end": event["date"], - "precision": event["precision"], - "summary": "dated", - } - for event in events - ], - } - rows = score_from_matrix(request, built) - by_time = {row["time"]: row for row in rows} - training_ids = {event["id"] for event in events} - holdout - expected = sum( - built["matrix"][event_id]["05:00"]["points"] - for event_id in training_ids - if event_id in built["matrix"] - ) - self.assertEqual(by_time["05:00"]["score"], expected) - self.assertFalse(any(item["event_id"] == holdout_id for item in by_time["05:00"]["evidence"])) - self.assertIn(holdout_id, {event["id"] for event in events}) - - probes = discriminating_event_probes( - _request(events=events), - { - "static_contexts": [ - _context("05:13", d4_asc=1, d9_asc=1), - _context("05:40", d4_asc=2, d9_asc=4), - ] - }, - scan=window_scan({ - "static_contexts": [ - _context("05:13", d4_asc=1, d9_asc=1), - _context("05:40", d4_asc=2, d9_asc=4), - ] - }), - candidate_times=["05:13", "05:40"], - representative_time="05:13", - today=date(2026, 8, 22), - ) - blocked = holdout_domain_years(events) - self.assertTrue(blocked) - for probe in probes: - self.assertNotIn(f"{probe['domain']}:{probe['year']}", blocked) - - def test_refresh_caps_rise_only_for_five_or_fewer_remaining(self) -> None: - self.assertEqual(_probe_caps(refresh=False, remaining_count=5), (8, 3)) - self.assertEqual(_probe_caps(refresh=True, remaining_count=6), (8, 3)) - self.assertEqual( - _probe_caps(refresh=True, remaining_count=5), - (REFRESH_MAX_PROBES, REFRESH_MAX_PROBES_PER_DOMAIN), - ) - - def test_monthly_family_dasha_boundary_is_ranked_not_dropped(self) -> None: - priors = dict(ANSWER_PRIORS[("family", "existence")]) - probe = { - "role": "distinguish", - "phase": PROBE_PHASE_CANDIDATE_DISCRIMINATOR, - "source": "dasha_boundary", - "domain": "family", - "year": 2018, - "month": 5, - "choice_kind": "existence", - "information_gain": 0.4, - "semantic_key": "family.2018.05", - "candidate_ids": ["04:50", "05:06"], - "expected_outcomes": [ - {"answer_class": "yes", "supports": ["04:50"], "conflicts": ["05:06"]}, - {"answer_class": "no", "supports": ["05:06"], "conflicts": ["04:50"]}, - ], - } - self.assertFalse(_dominant_existence_prior(probe, priors)) - public, dropped = _partition_ranked_probes([probe]) - self.assertEqual([item["semantic_key"] for item in public], ["family.2018.05"]) - self.assertFalse(any(item.get("reason") == "dominant_answer_prior" for item in dropped)) - yearless = {**probe, "month": None, "source": "age_band", "year": 0, "semantic_key": "family.age"} - self.assertTrue(_dominant_existence_prior(yearless, priors)) - - def test_remaining_five_cluster_refresh_keeps_family_monthly_boundary(self) -> None: - asked = [ - "career.2020", - "career.2023", - "education.2016", - "education.2020", - "relationship.2023", - "relocation.2015", - ] - built = { - "static_contexts": [ - _context("04:48", d4_asc=1, d9_asc=1, d10_asc=1, d12_asc=1, d24_asc=1), - _context("04:53", d4_asc=1, d9_asc=2, d10_asc=1, d12_asc=1, d24_asc=1), - _context("04:59", d4_asc=1, d9_asc=2, d10_asc=1, d12_asc=1, d24_asc=1), - _context("05:06", d4_asc=2, d9_asc=2, d10_asc=3, d12_asc=4, d24_asc=2), - _context("05:07", d4_asc=2, d9_asc=2, d10_asc=3, d12_asc=4, d24_asc=3), - ] - } - times = ["04:48", "04:53", "04:59", "05:06", "05:07"] - request = _request(asked_probe_keys=asked, refresh_probes=True) - probes = discriminating_event_probes( - request, - built, - scan=window_scan(built), - candidate_times=times, - representative_time="04:53", - today=date(2026, 9, 11), - ) - self.assertIsInstance(probes, list) - family_probe = { - "role": "distinguish", - "phase": PROBE_PHASE_CANDIDATE_DISCRIMINATOR, - "source": "dasha_boundary", - "domain": "family", - "year": 2018, - "month": 5, - "choice_kind": "existence", - "information_gain": 0.42, - "semantic_key": "family.2018.05.dasha_boundary", - "candidate_ids": times, - "expected_outcomes": [ - {"answer_class": "yes", "supports": ["04:48", "04:53"], "conflicts": ["05:06", "05:07"]}, - {"answer_class": "no", "supports": ["05:06", "05:07"], "conflicts": ["04:48", "04:53"]}, - ], - } - public, dropped = _partition_ranked_probes( - [family_probe, *probes], - max_probes=REFRESH_MAX_PROBES, - ) - family = [ - item - for item in public - if item.get("domain") == "family" - and item.get("source") == "dasha_boundary" - and isinstance(item.get("month"), int) - ] - self.assertTrue(family, [item.get("semantic_key") for item in public]) - self.assertTrue(all(1 <= int(item["month"]) <= 12 for item in family)) - self.assertFalse(any( - item.get("semantic_key") == "family.2018.05.dasha_boundary" - and item.get("reason") == "dominant_answer_prior" - for item in dropped - )) - - def test_refresh_packet_uses_column_times_not_full_grid(self) -> None: - remaining = ["04:48", "04:53", "04:59", "05:06", "05:07"] - start = datetime(1997, 8, 8, 4, 40) - grid = [(start + timedelta(minutes=index)).strftime("%H:%M") for index in range(31)] - self.assertEqual(len(grid), 31) - contexts = [] - for time in grid: - if time in remaining[:2]: - contexts.append(_context(time, d4_asc=1, d9_asc=1, d10_asc=1, d12_asc=1, d24_asc=1)) - elif time in remaining[2:]: - contexts.append(_context(time, d4_asc=2, d9_asc=2, d10_asc=3, d12_asc=4, d24_asc=2)) - else: - contexts.append(_context(time, d4_asc=1, d9_asc=1, d10_asc=1, d12_asc=1, d24_asc=1)) - built = {"static_contexts": contexts, "candidate_times": grid} - packet = build_refinement_packet( - _request(asked_probe_keys=[ - "career.2020", - "career.2023", - "education.2016", - "education.2020", - "relationship.2023", - "relocation.2015", - ], refresh_probes=True, column_times=remaining), - built, - representative_time="04:53", - candidate_times=grid, - column_times=remaining, - ) - probes = packet.get("discriminating_event_probes") or [] - allowed = set(remaining) - for probe in probes: - ids = {str(item)[:5] for item in (probe.get("candidate_ids") or [])} - self.assertTrue(ids <= allowed, probe.get("semantic_key")) - if not probes: - self.assertEqual(packet.get("refresh_result"), "no_new_probes") - else: - self.assertEqual(packet.get("refresh_result"), "new_probes") - - if __name__ == "__main__": unittest.main() diff --git a/tests/test_cluster_width_research.py b/tests/test_cluster_width_research.py deleted file mode 100644 index f425c97a3..000000000 --- a/tests/test_cluster_width_research.py +++ /dev/null @@ -1,202 +0,0 @@ -from __future__ import annotations - -from scripts.research.cluster_width_lib import ( - DEFAULT_MAX_CLUSTERS, - delivery_from_public, - merge_adjacent_traced, - metrics_bundle, - minute_mass_from_public, - public_from_clusters, - range_width, - smallest_mass_interval, - still_valid_public, - time_in_delivery, - truth_cluster_independent, -) -from scripts.research.cluster_width_probe import previous_sweep_width_is_full_window, verdict - - -def _cluster(key: str, times: list[str]) -> dict: - return { - "signature_key": key, - "times": times, - "contexts": [], - "representative_time": times[len(times) // 2], - "representative": None, - } - - -def _rows(scores: dict[str, float]) -> list[dict]: - return [{"time": time, "score": score} for time, score in scores.items()] - - -def test_union_of_clusters_equals_the_window_even_after_merge() -> None: - times = [f"04:{minute:02d}" for minute in range(0, 21)] - clusters = [_cluster(str(index), [time]) for index, time in enumerate(times)] - by_time = {time: {"time": time, "score": 20 if index < 19 else 1} for index, time in enumerate(times)} - merged, trace = merge_adjacent_traced(clusters, by_time, max_clusters=10) - covered = {item for cluster in merged for item in cluster["times"]} - assert covered == set(times) - assert range_width([item for cluster in merged for item in cluster["times"]]) == 21 - assert len(merged) == 10 - assert len(trace) == 11 - - -def test_w2_refuses_high_delta_merge_and_may_exceed_the_cap() -> None: - times = [f"05:{minute:02d}" for minute in range(0, 8)] - clusters = [_cluster(str(index), [time]) for index, time in enumerate(times)] - by_time = { - time: {"time": time, "score": 30 if index % 2 == 0 else 1} - for index, time in enumerate(times) - } - merged, trace = merge_adjacent_traced( - clusters, by_time, max_clusters=3, max_peak_delta=2.0, - ) - assert len(merged) == 8 - assert trace == [] - - -def test_w2_still_merges_close_scores() -> None: - times = [f"06:{minute:02d}" for minute in range(0, 6)] - clusters = [_cluster(str(index), [time]) for index, time in enumerate(times)] - by_time = {time: {"time": time, "score": 10 + index * 0.1} for index, time in enumerate(times)} - merged, trace = merge_adjacent_traced( - clusters, by_time, max_clusters=3, max_peak_delta=2.0, - ) - assert len(merged) == 3 - assert len(trace) == 3 - assert all(item["delta"] <= 2.0 for item in trace) - - -def test_no_cap_keeps_raw_clusters() -> None: - times = [f"07:{minute:02d}" for minute in range(0, 5)] - clusters = [_cluster(str(index), [time]) for index, time in enumerate(times)] - by_time = {time: {"time": time, "score": 8} for time in times} - merged, trace = merge_adjacent_traced(clusters, by_time, max_clusters=None) - assert len(merged) == 5 - assert trace == [] - - -def test_truth_independence_is_lost_when_the_true_cluster_is_merged() -> None: - raw = [ - _cluster("a", ["08:00", "08:01"]), - _cluster("b", ["08:02"]), - _cluster("c", ["08:03"]), - ] - by_time = { - "08:00": {"score": 1}, - "08:01": {"score": 1}, - "08:02": {"score": 1}, - "08:03": {"score": 20}, - } - merged, _trace = merge_adjacent_traced(raw, by_time, max_clusters=2) - assert truth_cluster_independent("08:03", raw, merged) is True - assert truth_cluster_independent("08:00", raw, merged) is False - - -def test_mass_interval_shrinks_from_the_weak_tail() -> None: - mass = { - "04:50": 10.0, - "04:51": 10.0, - "04:52": 10.0, - "04:53": 1.0, - "04:54": 1.0, - "04:55": 1.0, - } - interval = smallest_mass_interval(mass, 0.80) - assert interval["start"] == "04:50" - assert interval["end"] == "04:52" - assert interval["width"] == 3 - assert time_in_delivery("04:51", interval["times"]) is True - assert time_in_delivery("04:55", interval["times"]) is False - - -def test_mass_interval_does_not_drop_a_peak_in_the_middle() -> None: - mass = {"10:00": 1.0, "10:05": 20.0, "10:10": 1.0} - interval = smallest_mass_interval(mass, 0.80) - assert interval["start"] == "10:05" - assert interval["end"] == "10:05" - assert time_in_delivery("10:05", interval["times"]) is True - - -def test_lead_filter_drops_clusters_eight_or_more_behind() -> None: - public = [ - {"time": "11:00", "score": 20, "cluster_times": ["11:00", "11:01"]}, - {"time": "11:04", "score": 13, "cluster_times": ["11:04"]}, - {"time": "11:08", "score": 11, "cluster_times": ["11:08"]}, - ] - scores = {"11:00": 20.0, "11:04": 13.0, "11:08": 11.0} - valid = still_valid_public(public, scores, set(), lead=8) - times = delivery_from_public(valid)["times"] - assert "11:00" in times - assert "11:04" in times - assert "11:08" not in times - - -def test_eliminated_cluster_leaves_the_union() -> None: - public = [ - {"time": "12:00", "score": 16, "cluster_times": ["12:00", "12:01", "12:02"]}, - {"time": "12:10", "score": 16, "cluster_times": ["12:10", "12:11"]}, - ] - scores = {"12:00": 16.0, "12:10": 16.0} - valid = still_valid_public(public, scores, {"12:10"}, lead=8) - delivered = delivery_from_public(valid) - assert delivered["start"] == "12:00" - assert delivered["end"] == "12:02" - assert delivered["width"] == 3 - - -def test_public_from_clusters_keeps_the_peak_minute() -> None: - clusters = [_cluster("x", ["13:00", "13:01", "13:02"])] - rows = _rows({"13:00": 4, "13:01": 9, "13:02": 5}) - public = public_from_clusters(clusters, rows) - assert len(public) == 1 - assert public[0]["time"] == "13:01" - assert public[0]["cluster_times"] == ["13:00", "13:01", "13:02"] - - -def test_minute_mass_uses_the_cluster_peak() -> None: - public = [{"time": "14:00", "score": 7, "cluster_times": ["14:00", "14:01"]}] - mass = minute_mass_from_public(public, {"14:00": 7}) - assert mass["14:00"] == 7 - assert mass["14:01"] == 7 - - -def test_metrics_mark_a_squeezed_true_minute() -> None: - public = [{"time": "15:00", "score": 5, "cluster_times": ["15:00"]}] - metrics = metrics_bundle( - public=public, - true_time="15:10", - window_times=["15:00", "15:10"], - delivery_times=["15:00"], - delivery_width=1, - independent=True, - ) - assert metrics["coverage"] is False - assert metrics["truth_squeezed"] is True - assert metrics["top1_hit"] is False - - -def test_previous_sweep_width_is_the_full_window() -> None: - assert previous_sweep_width_is_full_window({ - "10": {"width_median": 21, "n": 20}, - "30": {"width_median": 61, "n": 20}, - "60": {"width_median": 121, "n": 20}, - }) is True - assert previous_sweep_width_is_full_window({ - "10": {"width_median": 12, "n": 20}, - }) is False - - -def test_verdict_blocks_a_coverage_drop() -> None: - baseline = { - "n": 10, "top1": 0.3, "coverage": 1.0, "width_median": 21, "tie": 0.2, - "squeezed": 0, "independent": 0.5, "entropy0": 2.0, "entropy6": 1.5, - } - narrower = {**baseline, "width_median": 9, "coverage": 0.8, "squeezed": 2} - better = {**baseline, "width_median": 9, "independent": 0.8} - same = {**baseline} - assert verdict(baseline, narrower) == "no_benefit" - assert verdict(baseline, better) == "benefit" - assert verdict(baseline, same) == "no_benefit" - assert DEFAULT_MAX_CLUSTERS == 64 diff --git a/tests/test_dasha_transition_proximity_cross_midnight.py b/tests/test_dasha_transition_proximity_cross_midnight.py deleted file mode 100644 index 690035763..000000000 --- a/tests/test_dasha_transition_proximity_cross_midnight.py +++ /dev/null @@ -1,194 +0,0 @@ -"""Candidate-local dasha dates; public AA replay and synthetic cache boundaries.""" -from __future__ import annotations - -import json -from datetime import date, datetime, timedelta - -import pytest - -from scripts.active_rectification_event_engine import compute_candidate_static_contexts -from scripts.rectification import dasha_transition_proximity as proximity -from scripts.rectification.scoring_service import ( - build_event_contribution_matrix, - public_technique_layers, - score_from_matrix, -) -from scripts.research.reported_offset_sweep import shifted_window -from scripts.research.sealed_holdout_rerun import DATASET - - -def _canonical(value): - return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() - - -def _cases(): - return json.loads(DATASET.read_text(encoding="utf-8"))["cases"] - - -def test_fixed_scoring_identity_is_exposed_without_changing_input_contract(): - from scripts.rectification.api_service import engine_scoring_versions - from scripts.rectification.scoring_service import ( - ALGORITHM_VERSION, INPUT_CONTRACT_VERSION, calculation_spec, sha256, - ) - - # 原值: "rectification-v5-matrix-scoring-11";新值: "...-scoring-12";原因: 恒星黄道补上章动后同输入分数变了 - # (BUG-1275),按 BUG-1181 升算法身份;输入合同 v5 与日期窗合同不变。 - # 原值: "rectification-v5-matrix-scoring-12";新值: "...-scoring-13";原因: varga.py 偶数星座 D30 按 BPHS 改正、 - # 白羊 / 天蝎上升金星判功能凶(BUG-1560 / BUG-1570,产品 2026-11-04 决定),同输入分数变了,按 BUG-1181 升算法身份。 - # 原值: "rectification-v5-matrix-scoring-13";新值: "...-scoring-14";原因: 同输入分数变了(#166 占星师裁定:Shadbala Sthana / Drik 按具名 BPHS 口径、jaimini.py Arudha 例外从初算落点数,BUG-1583~1588),按 BUG-1181 升算法身份。 - # 原值: "...-scoring-14";新值: "...-scoring-15";原因: #166 第二批(第 4 条:双子 / 处女上升土星改为混合,BUG-1590)改变同输入分数,按 BUG-1181 升算法身份。 - assert engine_scoring_versions()["algorithm_version"] == ALGORITHM_VERSION == "rectification-v5-matrix-scoring-15" - assert INPUT_CONTRACT_VERSION == "rectification-calculation-spec-v5" - request = {"birth_date": "2000-03-01", "start_time": "00:00", "end_time": "00:02", - "lat": 0.0, "lon": 0.0, "tz": 0.0, "events": []} - legacy_spec = calculation_spec(request) - assert legacy_spec["version"] == "rectification-calculation-spec-v4" - # Computed from unchanged baseline 3be740f8, not from the helper under test. - assert sha256(legacy_spec) == "bfdee46405a38f2508a2071929b60d79d15a78ca0e1e81f6c7ffd1652e301a08" - dated_spec = calculation_spec({**request, "candidate_intervals": [ - {"start_at": "2000-03-01T00:00", "end_at": "2000-03-01T00:02"}, - ]}) - assert dated_spec == {**legacy_spec, "version": "rectification-calculation-spec-v5", - "candidateIntervals": [{"start_at": "2000-03-01T00:00", "end_at": "2000-03-01T00:02"}]} - assert sha256(dated_spec) != sha256(legacy_spec) - - -@pytest.mark.parametrize("start", ["2000-01-01", "2000-02-29", "2000-12-31"]) -def test_every_candidate_uses_own_date_and_caches_do_not_cross_dates(monkeypatch, start): - # Intentionally identical synthetic chart values: only date distinguishes caches. - anchor = date.fromisoformat(start) - moments = [datetime.combine(anchor, datetime.min.time()) + timedelta(hours=23, minutes=50+i) - for i in range(21)] - contexts = [{"candidate_at": at, "feature": {"time": at.strftime("%H:%M")}, - "planet_longitudes": {"Moon": 42.0}, "ascendant_index": 1} - for at in moments] - event_date = date(2020, 1, 10) - calls = {"ad": [], "pd": [], "narayana": []} - - def vim(birth_date, moon, lo, hi, *, include_pratyantar=False): - calls["pd" if include_pratyantar else "ad"].append(birth_date) - delta = (date.fromisoformat(birth_date) - anchor).days - return [event_date + timedelta(days=delta + (3 if include_pratyantar else 2))] - - def narayana(asc, planets, birth_date, lo, hi): - calls["narayana"].append(birth_date) - delta = (date.fromisoformat(birth_date) - anchor).days - return [event_date + timedelta(days=delta + 4)] - - monkeypatch.setattr(proximity, "_vim_start_dates", vim) - monkeypatch.setattr(proximity, "_narayana_start_dates", narayana) - # Two events sharing the year band exercise cache reuse, not merely a new call. - events = [{"id": precision, "domain": "career", "precision": precision, - "date_start": event_date.isoformat(), "date_end": event_date.isoformat()} - for precision in ("day", "month")] - matrix = {event["id"]: {at.strftime("%H:%M"): {"points": 2.0, "rule_ids": []} - for at in moments} for event in events} - proximity.merge_transition_proximity(matrix, events, contexts, start, - public_technique_layers=public_technique_layers) - for at in moments: - delta = (at.date() - anchor).days - for precision in ("day", "month"): - expected = proximity.score_transition_proximity( - event_date=event_date, precision=precision, - vim_starts=[event_date + timedelta(days=delta + 2)], - vim_pd_starts=[event_date + timedelta(days=delta + 3)], - narayana_starts=[event_date + timedelta(days=delta + 4)], - ) - actual = matrix[precision][at.strftime("%H:%M")] - assert actual["points"] == round(2.0 + expected["points"], 4) - assert actual["rule_ids"] == sorted(expected["rule_ids"]) - expected_dates = [anchor.isoformat(), (anchor + timedelta(days=1)).isoformat()] - assert calls == {kind: expected_dates for kind in calls} - - -def test_legacy_context_without_candidate_at_retains_request_date(monkeypatch): - calls = [] - - def vim(birth_date, moon, lo, hi, **kwargs): - calls.append(birth_date) - return [] - - monkeypatch.setattr(proximity, "_vim_start_dates", vim) - monkeypatch.setattr(proximity, "_narayana_start_dates", lambda *args: []) - proximity.merge_transition_proximity( - {"event": {"12:00": {"points": 2.0}}}, - [{"id": "event", "precision": "day", "date": "2020-01-10"}], - [{"feature": {"time": "12:00"}, "planet_longitudes": {"Moon": 42.0}}], - "2000-01-01", public_technique_layers=public_technique_layers, - ) - assert calls == ["2000-01-01", "2000-01-01"] - - -@pytest.mark.parametrize("ordinal", [1, 2, 3]) -def test_same_day_public_aa_scores_keep_pre_fix_bytes(monkeypatch, ordinal): - from scripts.rectification import scoring_service - - # BUG-985 / BUG-733: equivalence is same-process, not a cross-machine float golden. - request, moments = shifted_window(_cases()[ordinal - 1], 0, 60) - assert {moment.date().isoformat() for moment in moments} == {request["birth_date"]} - contexts = compute_candidate_static_contexts(request) - assert [context["candidate_at"] for context in contexts] == moments - built = build_event_contribution_matrix(request, static_contexts=contexts) - scores = [row["score"] for row in score_from_matrix(request, built)] - legacy_calls = [] - - def legacy_merge(matrix, events, static_contexts, birth_date, **kwargs): - # Strip only at the helper boundary; the main event engine needs candidate_at. - assert static_contexts is contexts - legacy_contexts = [ - {key: value for key, value in context.items() if key != "candidate_at"} - for context in static_contexts - ] - legacy_calls.append(len(legacy_contexts)) - return proximity.merge_transition_proximity( - matrix, events, legacy_contexts, birth_date, **kwargs, - ) - - with monkeypatch.context() as legacy: - legacy.setattr(scoring_service, "merge_transition_proximity", legacy_merge) - legacy_built = build_event_contribution_matrix(request, static_contexts=contexts) - legacy_scores = [row["score"] for row in score_from_matrix(request, legacy_built)] - assert legacy_calls == [121] - assert len(scores) == len(legacy_scores) == 121 - assert _canonical(scores) == _canonical(legacy_scores) - assert _canonical(built["matrix"]) == _canonical(legacy_built["matrix"]) - - -def test_real_cross_midnight_all_candidates_match_independent_dated_calculation(monkeypatch): - # Existing public AA case naturally crosses midnight at radius 60; no birth mutation. - request, moments = shifted_window(_cases()[5], 0, 60) - contexts = compute_candidate_static_contexts(request) - assert [context["candidate_at"] for context in contexts] == moments - assert len({moment.date() for moment in moments}) == 2 - original_vim, original_narayana = proximity._vim_start_dates, proximity._narayana_start_dates - seen_vim, seen_narayana = set(), set() - - def vim(birth_date, moon, lo, hi, *, include_pratyantar=False): - seen_vim.add((birth_date, round(moon, 6), include_pratyantar)) - return original_vim(birth_date, moon, lo, hi, include_pratyantar=include_pratyantar) - - def narayana(asc, planets, birth_date, lo, hi): - seen_narayana.add((birth_date, asc, round(planets["Moon"], 6))) - return original_narayana(asc, planets, birth_date, lo, hi) - - with monkeypatch.context() as capture: - capture.setattr(proximity, "_vim_start_dates", vim) - capture.setattr(proximity, "_narayana_start_dates", narayana) - actual = build_event_contribution_matrix(request, static_contexts=contexts) - expected_rows, expected_matrix = [], {} - for context in contexts: - candidate_date = context["candidate_at"].date().isoformat() - dated_request = {**request, "birth_date": candidate_date} - # One correctly dated candidate per independent matrix, with fresh local caches. - built = build_event_contribution_matrix(dated_request, static_contexts=[context]) - expected_rows.extend(score_from_matrix(dated_request, built)) - for event_id, cells in built["matrix"].items(): - expected_matrix.setdefault(event_id, {}).update(cells) - assert _canonical(actual["matrix"]) == _canonical(expected_matrix) - assert _canonical(score_from_matrix(request, actual)) == _canonical(expected_rows) - for context in contexts: - candidate_date = context["candidate_at"].date().isoformat() - moon = round(context["planet_longitudes"]["Moon"], 6) - assert (candidate_date, moon, False) in seen_vim - assert (candidate_date, moon, True) in seen_vim - assert (candidate_date, context["ascendant_index"], moon) in seen_narayana diff --git a/tests/test_dynamic_rectification.py b/tests/test_dynamic_rectification.py deleted file mode 100644 index cdb691f4f..000000000 --- a/tests/test_dynamic_rectification.py +++ /dev/null @@ -1,351 +0,0 @@ -from __future__ import annotations - -from tests.conftest import FIXTURE_BIRTH_DATE, FIXTURE_BIRTH_LAT, FIXTURE_BIRTH_LON - -from datetime import date, datetime - -import pytest - -from scripts import dynamic_rectification -from scripts import dynamic_rectification_opportunities - - -def _base_request() -> dict: - return { - "case_id": "case-1", - "birth_date": "1990-01-01", - "as_of_date": "2026-07-18", - "start_time": "05:30", - "end_time": "05:33", - "lat": 31.23, - "lon": 121.47, - "tz": 8.0, - "evidence": [], - "dismissed_opportunity_ids": [], - "question_fingerprints": [], - "partition_fingerprints": [], - "recent_ranges": [], - "events": [], - } - - -def _fake_rows(_request: dict) -> list[dict]: - return [ - { - "window_group": "periods-3", - "dimension_code": "career", - "window_start": "2014-01-01", - "window_end": "2017-12-31", - "activations": {"05:30": 5.0, "05:31": 1.0, "05:32": 0.0, "05:33": 0.0}, - "missing_layers": [], - "fact_selection_priority": 0.0, - "fact_priority_version": "birth-time-question-fact-priority-v1", - "event_fact_selection_priority": 0.0, - "event_fact_priority_version": "birth-time-question-event-fact-priority-v1", - }, - { - "window_group": "periods-3", - "dimension_code": "career", - "window_start": "2018-01-01", - "window_end": "2021-12-31", - "activations": {"05:30": 0.0, "05:31": 5.0, "05:32": 4.0, "05:33": 0.0}, - "missing_layers": [], - "fact_selection_priority": 0.0, - "fact_priority_version": "birth-time-question-fact-priority-v1", - "event_fact_selection_priority": 0.0, - "event_fact_priority_version": "birth-time-question-event-fact-priority-v1", - }, - { - "window_group": "periods-3", - "dimension_code": "career", - "window_start": "2022-01-01", - "window_end": "2026-07-18", - "activations": {"05:30": 0.0, "05:31": 0.0, "05:32": 1.0, "05:33": 5.0}, - "missing_layers": [], - "fact_selection_priority": 0.0, - "fact_priority_version": "birth-time-question-fact-priority-v1", - "event_fact_selection_priority": 0.0, - "event_fact_priority_version": "birth-time-question-event-fact-priority-v1", - }, - ] - - -def _fake_model() -> dict: - return { - "version": "birth-time-choice-scoring-v2", - "opportunity_model_version": "birth-time-opportunity-model-v4", - "historical_event_fingerprint": dynamic_rectification_opportunities.historical_event_fingerprint(_base_request()), - "birth_date": "1990-01-01", - "as_of_date": "2026-07-18", - "range": {"start_time": "05:30", "end_time": "05:33"}, - "location": {"lat": 31.23, "lon": 121.47, "tz": 8.0}, - "candidate_times": ["05:30", "05:31", "05:32", "05:33"], - "windows": _fake_rows({}), - } - - -def test_packet_contains_only_candidate_backed_high_gain_opportunities(monkeypatch) -> None: - monkeypatch.setattr(dynamic_rectification, "_candidate_window_rows", _fake_rows) - - packet = dynamic_rectification.build_difference_packet(_base_request()) - - assert packet["scoring_version"] == "birth-time-choice-scoring-v2" - assert packet["current_range"] == {"start_time": "05:30", "end_time": "05:33"} - assert packet["opportunities"] - for opportunity in packet["opportunities"]: - assert opportunity["estimated_information_gain"] >= 0.15 - assert 2 <= len(opportunity["partitions"]) <= 4 - assert len({item["partition_id"] for item in opportunity["partitions"]}) == len( - opportunity["partitions"] - ) - for partition in opportunity["partitions"]: - assert set(partition["candidate_scores"]) == { - "05:30", "05:31", "05:32", "05:33", - } - - -def test_period_range_offers_multiple_distinct_evidence_domains() -> None: - packet = dynamic_rectification.build_difference_packet({ - **_base_request(), - "birth_date": "1997-08-09", - "as_of_date": "2026-07-19", - "start_time": "04:00", - "end_time": "07:59", - "lat": 36.6, - "lon": 114.5, - }) - - dimensions = {item["dimension_code"] for item in packet["opportunities"]} - assert len(dimensions) >= 4 - - -def test_real_historical_event_changes_next_question_order_not_public_gain() -> None: - request = { - **_base_request(), - "birth_date": FIXTURE_BIRTH_DATE, - "as_of_date": "2026-07-21", - "start_time": "14:20", - "end_time": "14:40", - "lat": FIXTURE_BIRTH_LAT, - "lon": FIXTURE_BIRTH_LON, - "tz": 8.0, - } - without_event = dynamic_rectification.build_difference_packet(request) - with_event = dynamic_rectification.build_difference_packet({ - **request, - "events": [{ - "id": "11111111-1111-4111-8111-111111111111", - "domain": "education", - "date": "2018", - "precision": "year", - }], - }) - - assert without_event["opportunities"][0]["dimension_code"] == "career" - assert with_event["opportunities"][0]["dimension_code"] == "education" - gains_without = { - item["opportunity_id"]: item["estimated_information_gain"] - for item in without_event["opportunities"] - } - gains_with = { - item["opportunity_id"]: item["estimated_information_gain"] - for item in with_event["opportunities"] - } - assert gains_with == gains_without - - -def test_packet_excludes_used_opportunity_and_partition_fingerprints(monkeypatch) -> None: - monkeypatch.setattr(dynamic_rectification, "_candidate_window_rows", _fake_rows) - first = dynamic_rectification.build_difference_packet(_base_request()) - used = first["opportunities"][0] - request = _base_request() - request["dismissed_opportunity_ids"] = [used["opportunity_id"]] - request["partition_fingerprints"] = [used["candidate_partition_fingerprint"]] - - second = dynamic_rectification.build_difference_packet(request) - - assert all(item["opportunity_id"] != used["opportunity_id"] for item in second["opportunities"]) - assert all( - item["candidate_partition_fingerprint"] != used["candidate_partition_fingerprint"] - for item in second["opportunities"] - ) - - -def test_packet_reuses_the_persisted_candidate_model(monkeypatch) -> None: - calls: list[dict] = [] - monkeypatch.setattr( - dynamic_rectification, - "_compute_candidate_model", - lambda request: calls.append(request) or _fake_model(), - ) - first = dynamic_rectification.build_difference_packet(_base_request()) - - second = dynamic_rectification.build_difference_packet( - {**_base_request(), "candidate_model": first["candidate_model"]} - ) - - assert len(calls) == 1 - assert second["candidate_model"] == first["candidate_model"] - - -def test_legacy_v2_candidate_model_is_recomputed_instead_of_blocking_resume(monkeypatch) -> None: - calls: list[dict] = [] - replacement = _fake_model() - legacy = {**replacement, "opportunity_model_version": "birth-time-opportunity-model-v2"} - monkeypatch.setattr( - dynamic_rectification, - "_compute_candidate_model", - lambda request: calls.append(request) or replacement, - ) - - packet = dynamic_rectification.build_difference_packet({ - **_base_request(), "candidate_model": legacy, - }) - - assert len(calls) == 1 - assert packet["candidate_model"]["opportunity_model_version"] == "birth-time-opportunity-model-v4" - - -def test_new_or_corrected_historical_event_recomputes_the_private_candidate_model(monkeypatch) -> None: - changed_request = { - **_base_request(), - "events": [{ - "id": "11111111-1111-4111-8111-111111111111", - "domain": "career", - "date": "2020", - "precision": "year", - }], - } - replacement = { - **_fake_model(), - "historical_event_fingerprint": dynamic_rectification_opportunities.historical_event_fingerprint( - changed_request, - ), - } - calls: list[dict] = [] - monkeypatch.setattr( - dynamic_rectification, - "_compute_candidate_model", - lambda request: calls.append(request) or replacement, - ) - - packet = dynamic_rectification.build_difference_packet({ - **changed_request, - "candidate_model": _fake_model(), - }) - - assert len(calls) == 1 - assert packet["candidate_model"]["historical_event_fingerprint"] == replacement[ - "historical_event_fingerprint" - ] - - -def test_candidate_model_rejects_wrong_range_and_non_finite_activation() -> None: - model = _fake_model() - model["range"] = {"start_time": "05:31", "end_time": "05:33"} - with pytest.raises(ValueError, match="candidate model"): - dynamic_rectification.build_difference_packet({**_base_request(), "candidate_model": model}) - - model = _fake_model() - model["windows"][0]["activations"]["05:30"] = float("nan") - with pytest.raises(ValueError, match="candidate model"): - dynamic_rectification.build_difference_packet({**_base_request(), "candidate_model": model}) - - -def test_candidate_model_rejects_out_of_bounds_windows_and_boolean_activations() -> None: - model = _fake_model() - model["windows"][0]["window_end"] = "2027-01-01" - with pytest.raises(ValueError, match="candidate model"): - dynamic_rectification.build_difference_packet({**_base_request(), "candidate_model": model}) - - model = _fake_model() - model["windows"][0]["activations"]["05:30"] = True - with pytest.raises(ValueError, match="candidate model"): - dynamic_rectification.build_difference_packet({**_base_request(), "candidate_model": model}) - - -@pytest.mark.parametrize(("field", "changed"), [("lat", 30.0), ("lon", 120.0), ("tz", 7.0)]) -def test_candidate_model_reuse_rejects_location_or_timezone_change(field, changed) -> None: - with pytest.raises(ValueError, match="candidate model"): - dynamic_rectification.build_difference_packet({ - **_base_request(), field: changed, "candidate_model": _fake_model(), - }) - - -def test_existing_evidence_summary_must_be_effective_partition_evidence(monkeypatch) -> None: - monkeypatch.setattr(dynamic_rectification, "_candidate_window_rows", _fake_rows) - - with pytest.raises(ValueError, match="partition evidence"): - dynamic_rectification.build_difference_packet( - {**_base_request(), "evidence": [{"kind": "unmatched", "note": "free text"}]} - ) - - -def test_candidate_charts_are_computed_once_and_missing_layers_are_dimension_scoped( - monkeypatch, -) -> None: - from scripts import active_rectification_event_engine - - candidates = [datetime(1990, 1, 1, 5, 30), datetime(1990, 1, 1, 5, 31)] - calls: list[datetime] = [] - monkeypatch.setattr(active_rectification_event_engine, "_candidate_datetimes", lambda _: candidates) - - def fake_candidate_row(request: dict, candidate: datetime) -> dict: - calls.append(candidate) - return { - "time": candidate.strftime("%H:%M"), - "score": 0.0, - "evidence": [ - { - "event_id": event["id"], - "domain": event["domain"], - "candidate_time": candidate.strftime("%H:%M"), - "rule_ids": ["fixture"], - "points": 1.0, - } - for event in request["events"] if event["domain"] != "career" - ], - "missing_layers": ["D10"], - } - - monkeypatch.setattr(active_rectification_event_engine, "_candidate_row", fake_candidate_row) - monkeypatch.setattr( - "scripts.dynamic_rectification_opportunities.build_domain_fact_priorities", - lambda _: { - dimension: {"selection_priority": 0.0} - for dimension in ["education", "relocation", "relationship", "career", "health_pressure"] - }, - ) - monkeypatch.setattr( - "scripts.dynamic_rectification_opportunities.build_historical_event_priorities", - lambda _: { - dimension: {"selection_priority": 0.0} - for dimension in ["education", "relocation", "relationship", "career", "health_pressure"] - }, - ) - rows = dynamic_rectification._candidate_window_rows(_base_request()) - - assert calls == candidates - assert {tuple(row["missing_layers"]) for row in rows if row["dimension_code"] == "career"} == {("D10",)} - assert {tuple(row["missing_layers"]) for row in rows if row["dimension_code"] != "career"} == {()} - assert {row["fact_priority_version"] for row in rows} == {"birth-time-question-fact-priority-v1"} - assert {row["event_fact_priority_version"] for row in rows} == { - "birth-time-question-event-fact-priority-v1", - } - - -def test_window_edges_and_under_age_cases_do_not_create_invalid_calculation(monkeypatch) -> None: - assert dynamic_rectification._experience_windows("2000-01-01", "2012-01-01") == [ - (date(2012, 1, 1), date(2012, 1, 1)), - ] - - from scripts import active_rectification_event_engine - - monkeypatch.setattr( - active_rectification_event_engine, - "_candidate_row", - lambda *_: pytest.fail("candidate chart should not be computed"), - ) - assert dynamic_rectification._candidate_window_rows({ - **_base_request(), "birth_date": "2020-01-01", - }) == [] diff --git a/tests/test_dynamic_rectification_fact_priority.py b/tests/test_dynamic_rectification_fact_priority.py deleted file mode 100644 index 1e2e7ac14..000000000 --- a/tests/test_dynamic_rectification_fact_priority.py +++ /dev/null @@ -1,52 +0,0 @@ -from tests.conftest import FIXTURE_BIRTH_DATE, FIXTURE_BIRTH_LAT, FIXTURE_BIRTH_LON - -from scripts.dynamic_rectification_fact_priority import ( - EVENT_FACT_PRIORITY_VERSION, - FACT_PRIORITY_VERSION, - build_domain_fact_priorities, - build_historical_event_priorities, -) - - -def test_real_domain_fact_priorities_are_shadow_only_and_bounded() -> None: - priorities = build_domain_fact_priorities({ - "birth_date": FIXTURE_BIRTH_DATE, - "start_time": "14:29", - "end_time": "14:31", - "lat": FIXTURE_BIRTH_LAT, - "lon": FIXTURE_BIRTH_LON, - "tz": 8.0, - "events": [], - }) - - assert set(priorities) == { - "education", "relocation", "relationship", "career", "health_pressure", - } - assert all(item["fact_priority_version"] == FACT_PRIORITY_VERSION for item in priorities.values()) - assert all(0 <= item["selection_priority"] <= 1 for item in priorities.values()) - assert all(item["shadow_only"] is True for item in priorities.values()) - assert all(item["may_affect_candidate_score"] is False for item in priorities.values()) - - -def test_historical_event_priority_preserves_vimshottari_actor_difference() -> None: - priorities = build_historical_event_priorities({ - "birth_date": "1879-03-14", - "start_time": "11:24", - "end_time": "11:25", - "lat": 48.4011, - "lon": 9.9876, - "tz": 0.66584, - "historical_events": [{ - "id": "11111111-1111-4111-8111-111111111111", - "domain": "career", - "date": "1922", - "precision": "year", - }], - }) - - career = priorities["career"] - assert career["event_fact_priority_version"] == EVENT_FACT_PRIORITY_VERSION - assert career["selection_priority"] > 0 - assert career["discriminating_event_ids"] == ["11111111-1111-4111-8111-111111111111"] - assert career["shadow_only"] is True - assert career["may_affect_candidate_score"] is False diff --git a/tests/test_dynamic_rectification_opportunities.py b/tests/test_dynamic_rectification_opportunities.py deleted file mode 100644 index 842ae5cb3..000000000 --- a/tests/test_dynamic_rectification_opportunities.py +++ /dev/null @@ -1,166 +0,0 @@ -from __future__ import annotations - -import json -import re -import unicodedata -from pathlib import Path - -from scripts.dynamic_rectification_opportunities import _dimension_opportunity, opportunities - -TASK2_PACKET_FIXTURE = ( - Path(__file__).parents[1] - / "frontend/tests/fixtures/task2-dynamic-rectification-packet.json" -) - - -def test_every_supported_dimension_emits_distinct_validator_safe_copy() -> None: - windows = [ - { - "window_start": "2018-01-01", - "window_end": "2020-12-31", - "activations": {"04:00": 1.0, "04:01": 0.0}, - }, - { - "window_start": "2021-01-01", - "window_end": "2023-12-31", - "activations": {"04:00": 0.0, "04:01": 1.0}, - }, - ] - - dimensions = ["education", "relocation", "relationship", "career", "health_pressure"] - opportunities = [ - _dimension_opportunity(dimension, windows, ["04:00", "04:01"]) - for dimension in dimensions - ] - - assert all(opportunity is not None for opportunity in opportunities) - contexts = [opportunity["neutral_context"] for opportunity in opportunities if opportunity] - assert len(contexts) == len(set(contexts)) == len(dimensions) - for dimension, opportunity in zip(dimensions, opportunities, strict=True): - assert opportunity is not None - context = opportunity["neutral_context"] - prompt = opportunity["fallback_prompt"] - labels = [item["fallback_label"] for item in opportunity["partitions"]] - assert dimension not in context - assert re.search(r"[\u3400-\u9fff]", context) - assert re.search(r"[A-Za-z]", context + prompt) is None - assert prompt.endswith("?") and prompt.count("?") == 1 - assert len(labels) == len(set(re.sub(r"\s+", "", label) for label in labels)) - assert all(re.search(r"[\u3400-\u9fff]", label) for label in labels) - - -def test_frontend_adapter_fixture_is_real_task2_opportunity_output() -> None: - packet = json.loads(TASK2_PACKET_FIXTURE.read_text(encoding="utf-8")) - windows = [ - { - "window_start": "2018-01-01", - "window_end": "2020-12-31", - "activations": {"04:00": 1.0, "04:01": 0.0}, - }, - { - "window_start": "2021-01-01", - "window_end": "2023-12-31", - "activations": {"04:00": 0.0, "04:01": 1.0}, - }, - ] - - opportunity = _dimension_opportunity("career", windows, ["04:00", "04:01"]) - - fixture = packet["opportunities"][0] - assert fixture["opportunity_id"] == opportunity["opportunity_id"] - assert fixture["candidate_partition_fingerprint"] == opportunity[ - "candidate_partition_fingerprint" - ] - assert [item["partition_id"] for item in fixture["partitions"]] == [ - item["partition_id"] for item in opportunity["partitions"] - ] - assert fixture["dimension_code"] == "career" - assert "career" not in fixture["neutral_context"] - assert len(fixture["partitions"]) == len(opportunity["partitions"]) - assert re.search(r"[A-Za-z]", fixture["neutral_context"] + fixture["fallback_prompt"]) is None - fixture_labels = [item["fallback_label"] for item in fixture["partitions"]] - assert len(fixture_labels) == len( - set(re.sub(r"\s+", "", label) for label in fixture_labels) - ) - - -def test_same_year_windows_receive_distinct_visible_labels() -> None: - windows = [ - { - "window_start": "2012-01-01", - "window_end": "2012-03-31", - "activations": {"04:00": 1.0, "04:01": 0.0}, - }, - { - "window_start": "2012-04-01", - "window_end": "2012-06-30", - "activations": {"04:00": 0.0, "04:01": 1.0}, - }, - ] - - opportunity = _dimension_opportunity("career", windows, ["04:00", "04:01"]) - - assert opportunity is not None - labels = [item["fallback_label"] for item in opportunity["partitions"]] - normalized = [ - re.sub(r"\s+", "", unicodedata.normalize("NFKC", label)) for label in labels - ] - assert len(normalized) == len(set(normalized)) - assert all(len(re.findall(r"\d+", label)) >= 3 for label in labels) - - -def test_same_month_windows_receive_distinct_day_precision_labels() -> None: - windows = [ - { - "window_start": "2012-01-01", - "window_end": "2012-01-10", - "activations": {"04:00": 1.0, "04:01": 0.0}, - }, - { - "window_start": "2012-01-11", - "window_end": "2012-01-20", - "activations": {"04:00": 0.0, "04:01": 1.0}, - }, - ] - - opportunity = _dimension_opportunity("career", windows, ["04:00", "04:01"]) - - assert opportunity is not None - labels = [item["fallback_label"] for item in opportunity["partitions"]] - normalized = [ - re.sub(r"\s+", "", unicodedata.normalize("NFKC", label)) for label in labels - ] - assert len(normalized) == len(set(normalized)) - assert all(len(re.findall(r"\d+", label)) >= 4 for label in labels) - - -def test_fact_priority_changes_question_order_without_changing_public_information_gain() -> None: - candidates = ["04:00", "04:01"] - windows = [] - for dimension, priority in (("career", 0.0), ("relationship", 1.0)): - for index, (start, end) in enumerate(( - ("2018-01-01", "2020-12-31"), - ("2021-01-01", "2023-12-31"), - )): - windows.append({ - "window_group": "periods-2", - "dimension_code": dimension, - "window_start": start, - "window_end": end, - "activations": { - "04:00": 1.0 if index == 0 else 0.0, - "04:01": 0.0 if index == 0 else 1.0, - }, - "missing_layers": [], - "fact_selection_priority": priority, - "fact_priority_version": "birth-time-question-fact-priority-v1", - "event_fact_selection_priority": 1.0 if dimension == "career" else 0.0, - "event_fact_priority_version": "birth-time-question-event-fact-priority-v1", - }) - - result = opportunities({"candidate_times": candidates, "windows": windows}) - - assert [item["dimension_code"] for item in result] == ["career", "relationship"] - assert [item["estimated_information_gain"] for item in result] == [1.0, 1.0] - assert all("_fact_selection_priority" not in item for item in result) - assert all("_event_fact_selection_priority" not in item for item in result) diff --git a/tests/test_dynamic_rectification_scoring.py b/tests/test_dynamic_rectification_scoring.py deleted file mode 100644 index ea8269722..000000000 --- a/tests/test_dynamic_rectification_scoring.py +++ /dev/null @@ -1,350 +0,0 @@ -from __future__ import annotations - -from types import SimpleNamespace -from uuid import uuid4 - -import pytest - -from scripts import dynamic_rectification -from scripts import jyotish_api_server as api_server - - -def _score_request() -> dict: - return { - "birth_date": "1990-01-01", - "start_time": "05:30", - "end_time": "05:33", - "lat": 31.23, - "lon": 121.47, - "tz": 8.0, - "choice_evidence": [], - } - - -def _opportunity_request(**changes) -> dict: - return { - "case_id": str(uuid4()), - "birth_date": "1990-01-01", - "as_of_date": "2026-07-21", - "start_time": "05:30", - "end_time": "05:33", - "lat": 31.23, - "lon": 121.47, - "tz": 8.0, - "candidate_model": None, - "evidence": [], - "dismissed_opportunity_ids": [], - "question_fingerprints": [], - "partition_fingerprints": [], - "recent_ranges": [], - **changes, - } - - -def _decisive_rows() -> list[dict]: - return [ - {"time": "05:30", "score": 20.0}, - {"time": "05:31", "score": 20.0}, - {"time": "05:32", "score": 20.0}, - {"time": "05:33", "score": 10.0}, - ] - - -def _evidence(**changes) -> dict: - return { - "question_id": str(uuid4()), - "opportunity_id": "career-window", - "partition_id": "career-2020-2022", - "dimension_code": "career", - "candidate_scores": {"05:30": 0.0, "05:31": 1.0, "05:32": 1.0, "05:33": 0.0}, - "information_gain": 0.5, - **changes, - } - - -def _handler() -> api_server.JyotishAPIHandler: - handler = api_server.JyotishAPIHandler.__new__(api_server.JyotishAPIHandler) - handler.headers = {} - return handler - - -def test_dynamic_routes_fail_closed_and_compare_wrong_bearers_in_constant_time( - monkeypatch, -) -> None: - handler = _handler() - monkeypatch.delenv("JYOTISH_DYNAMIC_RECTIFICATION_TOKEN", raising=False) - with pytest.raises(api_server.Forbidden, match="token"): - handler._compute_dynamic_rectification_score({}) - - calls: list[tuple[str, str]] = [] - original = api_server.secrets.compare_digest - monkeypatch.setattr( - api_server.secrets, - "compare_digest", - lambda supplied, configured: calls.append((supplied, configured)) - or original(supplied, configured), - ) - monkeypatch.setenv("JYOTISH_DYNAMIC_RECTIFICATION_TOKEN", "server-secret") - handler.headers = {"Authorization": "Bearer wrong-secret"} - with pytest.raises(api_server.Forbidden, match="token"): - handler._compute_dynamic_rectification_opportunities({}) - assert calls == [("wrong-secret", "server-secret")] - - -def test_unauthenticated_forged_scores_cannot_obtain_an_applicable_result(monkeypatch) -> None: - monkeypatch.setenv("JYOTISH_DYNAMIC_RECTIFICATION_TOKEN", "server-secret") - scores = {"05:30": 10_000.0, "05:31": 0.0, "05:32": 0.0, "05:33": 0.0} - evidence = [ - _evidence( - question_id=f"question-{index}", - opportunity_id=f"opportunity-{index}", - partition_id=f"partition-{index}", - dimension_code=dimension, - candidate_scores=scores, - information_gain=1.0, - ) - for index, dimension in enumerate( - ["career", "relationship", "education", "career"], start=1 - ) - ] - with pytest.raises(api_server.Forbidden, match="token"): - _handler()._compute_dynamic_rectification_score({ - **_score_request(), "choice_evidence": evidence, - }) - - -def test_authenticated_dynamic_questionnaire_cannot_open_minute_confirmation(monkeypatch) -> None: - monkeypatch.setenv("JYOTISH_DYNAMIC_RECTIFICATION_TOKEN", "server-secret") - handler = _handler() - handler.headers = {"Authorization": "Bearer server-secret"} - scores = {"05:30": 10_000.0, "05:31": 0.0, "05:32": 0.0, "05:33": 0.0} - evidence = [ - _evidence( - question_id=f"question-{index}", - opportunity_id=f"opportunity-{index}", - partition_id=f"partition-{index}", - dimension_code=dimension, - candidate_scores=scores, - information_gain=1.0, - ) - for index, dimension in enumerate( - ["career", "relationship", "education", "relocation"], start=1 - ) - ] - - result = handler._compute_dynamic_rectification_score({ - **_score_request(), "choice_evidence": evidence, - }) - - assert result["confidence"] == "high" - assert result["can_apply"] is False - assert "vedastro_validation_required" in result["reasons"] - - -def test_opportunity_route_defaults_legacy_missing_events_to_empty(monkeypatch) -> None: - monkeypatch.setenv("JYOTISH_DYNAMIC_RECTIFICATION_TOKEN", "server-secret") - handler = _handler() - handler.headers = {"Authorization": "Bearer server-secret"} - received = [] - monkeypatch.setattr(api_server, "_load_local_module", lambda _name: SimpleNamespace( - build_difference_packet=lambda request: received.append(request) - or {"packet": {}, "candidate_model": {}}, - )) - - handler._compute_dynamic_rectification_opportunities(_opportunity_request()) - - assert received[0]["events"] == [] - - -def test_opportunity_route_validates_and_forwards_historical_events(monkeypatch) -> None: - monkeypatch.setenv("JYOTISH_DYNAMIC_RECTIFICATION_TOKEN", "server-secret") - handler = _handler() - handler.headers = {"Authorization": "Bearer server-secret"} - event_id = str(uuid4()) - received = [] - monkeypatch.setattr(api_server, "_load_local_module", lambda _name: SimpleNamespace( - build_difference_packet=lambda request: received.append(request) - or {"packet": {}, "candidate_model": {}}, - )) - - handler._compute_dynamic_rectification_opportunities(_opportunity_request(events=[{ - "id": event_id, - "domain": "career", - "date": "2020-06", - "precision": "month", - }])) - - assert received[0]["events"] == [{ - "id": event_id, - "domain": "career", - "date": "2020-06", - "precision": "month", - }] - with pytest.raises(api_server.BadRequest, match="date does not match"): - handler._compute_dynamic_rectification_opportunities(_opportunity_request(events=[{ - "id": event_id, - "domain": "career", - "date": "2020", - "precision": "month", - }])) - - -def test_dynamic_routes_are_not_browser_runnable_technique_examples() -> None: - endpoints = { - "/api/dynamic_rectification_opportunities", - "/api/dynamic_rectification_score", - } - assert endpoints.isdisjoint(api_server.TECHNIQUE_EXAMPLE_ENDPOINTS) - assert endpoints.isdisjoint(api_server.API_COMMAND_MAP.values()) - for endpoint in endpoints: - with pytest.raises(KeyError): - _handler()._dispatch_technique_endpoint(endpoint, {}) - - -def test_primary_choice_changes_rankings_and_returns_a_real_range() -> None: - result = dynamic_rectification.score_choice_evidence( - {**_score_request(), "choice_evidence": [_evidence()]} - ) - - assert result["effective_answer_count"] == 1 - assert result["winning_segment"] == { - "start_time": "05:31", - "end_time": "05:32", - "representative_time": "05:31", - "width_minutes": 2, - } - assert result["can_apply"] is False - assert result["evidence"] == [] - - -def test_score_accepts_candidate_membership_independent_of_json_key_order() -> None: - scores = {"05:33": 0.0, "05:32": 1.0, "05:31": 1.0, "05:30": 0.0} - result = dynamic_rectification.score_choice_evidence( - {**_score_request(), "choice_evidence": [_evidence(candidate_scores=scores)]} - ) - - assert result["winning_segment"]["start_time"] == "05:31" - - -def test_cross_midnight_leaders_form_one_chronological_segment() -> None: - scores = {"23:58": 0.0, "23:59": 1.0, "00:00": 1.0, "00:01": 0.0} - evidence = [ - _evidence( - question_id=f"question-{index}", - opportunity_id=f"opportunity-{index}", - partition_id=f"partition-{index}", - dimension_code=dimension, - candidate_scores=scores, - information_gain=1.0, - ) - for index, dimension in enumerate( - ["career", "relationship", "education", "career"], start=1 - ) - ] - result = dynamic_rectification.score_choice_evidence({ - **_score_request(), - "start_time": "23:58", - "end_time": "00:01", - "choice_evidence": evidence, - }) - - assert result["confidence"] == "high" - assert result["winning_segment"] == { - "start_time": "23:59", - "end_time": "00:00", - "representative_time": "23:59", - "width_minutes": 2, - } - - -def test_opaque_trimmed_question_ids_are_valid_and_duplicates_remain_rejected() -> None: - evidence = _evidence(question_id=" question-career-window ") - result = dynamic_rectification.score_choice_evidence( - {**_score_request(), "choice_evidence": [evidence]} - ) - assert result["effective_answer_count"] == 1 - - with pytest.raises(ValueError, match="duplicate question"): - dynamic_rectification.score_choice_evidence({ - **_score_request(), - "choice_evidence": [ - evidence, - {**evidence, "question_id": "question-career-window"}, - ], - }) - - -def test_unknown_and_unmatched_are_never_choice_evidence() -> None: - with pytest.raises(ValueError, match="partition evidence"): - dynamic_rectification.score_choice_evidence( - {**_score_request(), "choice_evidence": [{"kind": "unknown"}]} - ) - - -def test_high_confidence_requires_versioned_hard_gates() -> None: - result = dynamic_rectification.adjudicate_choice_rows( - _decisive_rows(), - effective_answer_count=4, - dimension_count=3, - missing_layers=[], - ) - - assert result["confidence"] == "high" - assert result["can_apply"] is True - assert result["winning_segment"]["width_minutes"] <= 5 - assert result["margin_percent"] >= 20 - assert result["algorithm_version"] == "birth-time-choice-scoring-v2" - - -def test_medium_and_missing_layers_never_allow_application() -> None: - medium = dynamic_rectification.adjudicate_choice_rows( - _decisive_rows(), effective_answer_count=3, dimension_count=2, missing_layers=[] - ) - blocked = dynamic_rectification.adjudicate_choice_rows( - _decisive_rows(), - effective_answer_count=4, - dimension_count=3, - missing_layers=["D10"], - ) - - assert medium["confidence"] == "medium" - assert medium["can_apply"] is False - assert blocked["confidence"] == "low" - assert blocked["can_apply"] is False - - -def test_score_rejects_client_fields_duplicates_caps_and_invalid_scores() -> None: - evidence = _evidence() - with pytest.raises(ValueError, match="option_id"): - dynamic_rectification.score_choice_evidence({ - **_score_request(), "choice_evidence": [{**evidence, "option_id": "client"}], - }) - with pytest.raises(ValueError, match="duplicate question"): - dynamic_rectification.score_choice_evidence( - {**_score_request(), "choice_evidence": [evidence, evidence]} - ) - with pytest.raises(ValueError, match="at most 10"): - dynamic_rectification.score_choice_evidence({ - **_score_request(), - "choice_evidence": [ - {**evidence, "question_id": str(uuid4())} for _ in range(11) - ], - }) - with pytest.raises(ValueError, match="candidate scores"): - dynamic_rectification.score_choice_evidence({ - **_score_request(), - "choice_evidence": [_evidence(candidate_scores={ - **evidence["candidate_scores"], "05:34": 1.0, - })], - }) - with pytest.raises(ValueError, match="candidate scores"): - dynamic_rectification.score_choice_evidence({ - **_score_request(), - "choice_evidence": [_evidence(candidate_scores={ - **evidence["candidate_scores"], "05:30": -1.0, - })], - }) - with pytest.raises(ValueError, match="identifier"): - dynamic_rectification.score_choice_evidence( - {**_score_request(), "choice_evidence": [_evidence(partition_id="")]} - ) diff --git a/tests/test_heavy_compute_processes_20261028.py b/tests/test_heavy_compute_processes_20261028.py index 0314488f6..ff8eb517b 100644 --- a/tests/test_heavy_compute_processes_20261028.py +++ b/tests/test_heavy_compute_processes_20261028.py @@ -8,24 +8,11 @@ import time import pytest from scripts.api_process_pool import pool -from scripts.jyotish_api_server import REPO_ROOT, SCRIPTS_DIR, BadRequest, JyotishComputeService -from tests.test_rectification_v5_vedastro_validation import request as v5_request +from scripts.jyotish_api_server import REPO_ROOT, SCRIPTS_DIR -NOISE = ("fingerprint", "feature_hash", "_hash", "elapsed", "duration", "_ms", "timing") - - -def _body() -> dict: - body = v5_request() - body.pop("candidate_times") - return body - - -def _strip(value): - if isinstance(value, dict): - return {k: _strip(v) for k, v in value.items() if not any(n in k for n in NOISE)} - if isinstance(value, list): - return [_strip(v) for v in value] - return value +# The rectification V5 score this file used was retired on 2026-11-06; the +# professional report reference is the one pooled route left. +POOLED = "professional_report_reference" @pytest.fixture @@ -38,25 +25,10 @@ def started_pool(): def test_without_the_pool_routes_run_in_process(): assert not pool.active() calls = [] - assert pool.run("_compute_rectification_v5_score", {"x": 1}, lambda body: calls.append(body) or "inline") == "inline" + assert pool.run(POOLED, {"x": 1}, lambda body: calls.append(body) or "inline") == "inline" assert calls == [{"x": 1}] -def test_a_pooled_score_equals_the_in_process_one(started_pool): - inline = JyotishComputeService()._compute_rectification_v5_score - pooled = pool.run("_compute_rectification_v5_score", _body(), lambda body: pytest.fail("ran inline")) - assert pooled["success"] is True - # Fingerprints already vary per process (ERR-111); everything else is identical. - assert _strip(pooled) == _strip(inline(_body())) - - -def test_bad_input_is_still_a_bad_request(started_pool): - body = _body() - body["start_time"] = "not-a-time" - with pytest.raises((BadRequest, ValueError, KeyError)): - pool.run("_compute_rectification_v5_score", body, lambda _body: pytest.fail("ran inline")) - - def test_routes_outside_the_list_never_leave_the_process(started_pool): assert pool.run("_compute_chart", {}, lambda body: "inline") == "inline" @@ -66,7 +38,7 @@ def test_a_crashed_pool_answers_in_process_and_comes_back(started_pool): os.kill(victim.pid, 9) time.sleep(0.5) calls = [] - result = pool.run("_compute_rectification_v5_score", _body(), lambda body: calls.append(1) or "inline") + result = pool.run(POOLED, {}, lambda body: calls.append(1) or "inline") assert result == "inline" and calls == [1] for _ in range(120): if pool.active(): diff --git a/tests/test_jev_intent_research.py b/tests/test_jev_intent_research.py deleted file mode 100644 index 3ebc6d7aa..000000000 --- a/tests/test_jev_intent_research.py +++ /dev/null @@ -1,238 +0,0 @@ -"""Offline contracts for the Jev intent-classifier research scripts.""" - -from __future__ import annotations - -import json -import unittest -from pathlib import Path - -import inspect - -from scripts.research.jev_intent_corpus_build import ( # noqa: E402 - GENERATOR_NAME, - REVIEWER_NAME, - build_review_prompt, - holdout_name_denylist, - review_sample, - source_a_samples, -) -from scripts.research.jev_intent_questions import ( - CONTINUES_PREVIOUS_TURN_INSTRUCTIONS, - CRITERION_MAP, - INTENT_CRITERIA, - LOST_SEMANTICS, - build_questions, - build_state, - enforce_combo, - parse_jev_answers, -) -from scripts.research.jev_intent_source_b_v2 import attach_previous_turns - -ROOT = Path(__file__).resolve().parents[1] - - -class JevIntentQuestionsTests(unittest.TestCase): - def test_combo_nulls_answer_class_when_not_current_focus(self) -> None: - parsed = enforce_combo("stop_rectification", "no", True) - self.assertEqual(parsed["intent"], "stop_rectification") - self.assertIsNone(parsed["answer_class"]) - self.assertTrue(parsed["has_new_dated_event"]) - - def test_combo_rejects_current_focus_without_class(self) -> None: - parsed = enforce_combo("answer_current_focus", None, False) - self.assertEqual(parsed["intent"], "unclear") - self.assertIsNone(parsed["answer_class"]) - - def test_questions_match_advanced_json_shape(self) -> None: - sample = source_a_samples()[0] - questions = build_questions(sample) - self.assertEqual(questions["intent"]["type"], "choice") - self.assertEqual(set(questions["intent"]["criteria"]), set(INTENT_CRITERIA)) - self.assertEqual(questions["answer_class"]["type"], "choice") - self.assertEqual(questions["has_new_dated_event"]["type"], "noul") - self.assertIn("true", questions["has_new_dated_event"]["criteria"]) - self.assertIn("false", questions["has_new_dated_event"]["criteria"]) - state = build_state(sample) - self.assertEqual(set(state), {"current_question", "options", "user_message", "case_status"}) - - def test_criterion_map_covers_production_prompts(self) -> None: - joined = " ".join(row["production"] for row in CRITERION_MAP) - self.assertIn("不要按 A/B/C/D", joined) - self.assertIn("通常是回答当前问题", joined) - self.assertTrue(LOST_SEMANTICS) - - def test_parse_jev_answers_enforces_combo(self) -> None: - parsed = parse_jev_answers({ - "intent": {"choice": "stop_rectification", "confidence": 0.9, "probabilities": {}}, - "answer_class": {"choice": "no", "confidence": 0.4, "probabilities": {}}, - "has_new_dated_event": {"noul": 0.1}, - }) - self.assertEqual(parsed["intent"], "stop_rectification") - self.assertIsNone(parsed["answer_class"]) - self.assertEqual(parsed["confidence"], 0.9) - - -class JevIntentPreviousTurnTests(unittest.TestCase): - def test_v1_v2_state_shape_keeps_v0_questions(self) -> None: - sample = dict(source_a_samples()[0]) - sample["previous_turn"] = {"assistant_message": "上一问", "user_message": "上一句"} - sample["previous_decision"] = {"intent": "unclear", "answer_class": None} - v0 = build_state(sample, variant="v0") - self.assertEqual(set(v0), {"current_question", "options", "user_message", "case_status"}) - v1 = build_state(sample, variant="v1") - self.assertEqual(v1["previous_turn"], {"assistant_message": "上一问", "user_message": "上一句"}) - self.assertNotIn("previous_decision", v1) - v2 = build_state(sample, variant="v2") - self.assertEqual(v2["previous_decision"], {"intent": "unclear", "answer_class": None}) - v0_questions = build_questions(sample) - v2_questions = build_questions(sample, variant="v2") - self.assertNotIn("continues_previous_turn", v0_questions) - self.assertEqual(set(v0_questions["intent"]["criteria"]), set(v2_questions["intent"]["criteria"])) - self.assertEqual(v2_questions["continues_previous_turn"]["type"], "noul") - self.assertEqual( - v2_questions["continues_previous_turn"]["instructions"], - CONTINUES_PREVIOUS_TURN_INSTRUCTIONS, - ) - - def test_continues_rule_adopts_previous_intent_only_at_threshold(self) -> None: - answers = { - "intent": {"choice": "answer_current_focus", "confidence": 0.95, "probabilities": {}}, - "answer_class": {"choice": "yes", "confidence": 0.91, "probabilities": {}}, - "has_new_dated_event": {"noul": 0.1}, - "continues_previous_turn": {"noul": 0.9}, - } - adopted = parse_jev_answers( - answers, - previous_decision={"intent": "unclear", "answer_class": None}, - apply_continue=True, - ) - self.assertEqual(adopted["intent"], "unclear") - self.assertIsNone(adopted["answer_class"]) - self.assertTrue(adopted["continued"]) - self.assertEqual(adopted["confidence"], 0.9) - kept = parse_jev_answers( - {**answers, "continues_previous_turn": {"noul": 0.89}}, - previous_decision={"intent": "stop_rectification", "answer_class": None}, - apply_continue=True, - ) - self.assertEqual(kept["intent"], "answer_current_focus") - self.assertEqual(kept["answer_class"], "yes") - self.assertFalse(kept["continued"]) - focused = parse_jev_answers( - answers, - previous_decision={"intent": "answer_current_focus", "answer_class": "no"}, - apply_continue=True, - ) - self.assertEqual(focused["intent"], "answer_current_focus") - self.assertEqual(focused["answer_class"], "no") - - def test_case_first_turn_previous_turn_is_null(self) -> None: - rows = attach_previous_turns([ - { - "id": "first", - "case_id": "case-1", - "created_at": "2026-09-01T00:00:00Z", - "user_message": "第一句", - "assistant_message": "第一答", - }, - { - "id": "second", - "case_id": "case-1", - "created_at": "2026-09-01T00:01:00Z", - "user_message": "继续", - "assistant_message": "第二答", - }, - { - "id": "orphan", - "user_message": "没有案件", - "assistant_message": "答", - }, - ]) - by_id = {row["id"]: row for row in rows} - self.assertIsNone(by_id["first"]["previous_turn"]) - self.assertEqual(by_id["first"]["previous_turn_source"], "case_first") - self.assertEqual(by_id["second"]["previous_turn"], { - "assistant_message": "第一答", - "user_message": "第一句", - }) - self.assertIsNone(by_id["orphan"]["previous_turn"]) - state = build_state(by_id["first"], variant="v1") - self.assertIsNone(state["previous_turn"]) - self.assertIn("user_message", state) - - -class JevIntentCorpusTests(unittest.TestCase): - def test_source_a_has_ten_labeled_rows(self) -> None: - rows = source_a_samples() - self.assertEqual(len(rows), 10) - self.assertEqual({row["user_message"] for row in rows} & {"2016年3月入学", "随便吧"}, {"2016年3月入学", "随便吧"}) - for row in rows: - self.assertIn(row["gold"]["intent"], { - "answer_current_focus", "provide_new_evidence", "stop_rectification", - "ask_about_result", "unclear", - }) - - def test_reviewer_does_not_read_gold(self) -> None: - sample = { - "layer": "collect", - "user_message": "没有", - "focus": {"current_question": "钱的方面,还记得哪年收入明显变过吗?", "options": []}, - "gold": {"intent": "stop_rectification", "answer_class": None, "has_new_dated_event": False}, - "target_before_review": {"intent": "stop_rectification"}, - } - prompt = build_review_prompt(sample) - self.assertIn("没有", prompt) - self.assertIn("钱的方面,还记得哪年收入明显变过吗?", prompt) - self.assertNotIn("目标", prompt) - tail = prompt.rsplit("用户回复:", 1)[-1] - self.assertIn("没有", tail) - self.assertNotIn("stop_rectification", tail) - self.assertNotIn("template", GENERATOR_NAME.lower()) - self.assertNotIn("rule", REVIEWER_NAME.lower()) - - def test_corpus_build_has_no_literal_word_bank(self) -> None: - src = (ROOT / "scripts" / "research" / "jev_intent_corpus_build.py").read_text(encoding="utf-8") - self.assertNotIn("bank = {", src) - self.assertNotIn('GENERATOR_NAME = "agent-template', src) - self.assertNotIn('REVIEWER_NAME = "agent-rule', src) - - def test_reviewer_does_not_regex_label(self) -> None: - src = inspect.getsource(review_sample) - self.assertNotIn("re.search", src) - self.assertNotIn("re.match", src) - self.assertNotIn("STOP_RE", src) - self.assertIn("complete_chat", src) - - def test_current_instructions_match_production_classifier(self) -> None: - from scripts.research.jev_intent_current import CHOICE_INSTRUCTIONS, COLLECT_INSTRUCTIONS - - src = ( - ROOT / "frontend" / "src" / "lib" / "rectification-agentic" / "v9" / "turn-intent-classifier.ts" - ).read_text(encoding="utf-8") - self.assertIn(CHOICE_INSTRUCTIONS, src) - self.assertIn(COLLECT_INSTRUCTIONS, src) - - def test_simulated_has_no_holdout_names(self) -> None: - path = ROOT / "scripts" / "research" / "jev_intent_samples" / "simulated.jsonl" - if not path.is_file(): - self.skipTest("simulated.jsonl not generated yet") - names = holdout_name_denylist() - for line in path.read_text(encoding="utf-8").splitlines(): - row = json.loads(line) - message = row["user_message"] - for name in names: - self.assertNotIn(name, message) - - def test_report_json_includes_current_source_b(self) -> None: - path = ROOT / "docs" / "research" / "jev_intent_2026_09_19.json" - if not path.is_file(): - self.skipTest("report json not generated yet") - payload = json.loads(path.read_text(encoding="utf-8")) - current = (payload.get("metrics") or {}).get("current_source_b") - self.assertIsNotNone(current) - self.assertEqual(current["n"], payload["meta"]["source_b_n"]) - self.assertIn("source_b_none_confusion", payload["metrics"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_minute_candidate_discriminability.py b/tests/test_minute_candidate_discriminability.py deleted file mode 100644 index b5567e8a8..000000000 --- a/tests/test_minute_candidate_discriminability.py +++ /dev/null @@ -1,44 +0,0 @@ -from scripts.minute_candidate_discriminability import analyze_candidate_rows, feature_fingerprint - - -def _row(time: str, points: float, rules: list[str] | None = None) -> dict: - return { - "time": time, - "score": points, - "evidence": [{ - "event_id": "event-1", - "domain": "career", - "candidate_time": time, - "rule_ids": rules or ["same_rule"], - "points": points, - }], - "missing_layers": [], - } - - -def test_fingerprint_excludes_candidate_time_but_includes_evidence_features() -> None: - assert feature_fingerprint(_row("10:00", 1.0)) == feature_fingerprint(_row("10:01", 1.0)) - assert feature_fingerprint(_row("10:00", 1.0)) != feature_fingerprint(_row("10:00", 2.0)) - - -def test_diagnostic_reports_equivalent_adjacent_minutes() -> None: - report = analyze_candidate_rows([ - _row("10:00", 1.0), - _row("10:01", 1.0), - _row("10:02", 2.0, ["different_rule"]), - ]) - - assert report["unique_feature_fingerprint_count"] == 2 - assert report["indistinguishable_adjacent_pair_count"] == 1 - assert report["adjacent_transitions"][0]["feature_changed"] is False - assert report["adjacent_transitions"][0]["changed_event_ids"] == [] - assert report["top_candidate_feature_unique"] is True - assert report["status"] == "minute_feature_unique" - - -def test_diagnostic_blocks_a_fully_equivalent_range() -> None: - report = analyze_candidate_rows([_row("10:00", 1.0), _row("10:01", 1.0)]) - - assert report["distinguishable_candidate_ratio"] == 0.5 - assert report["top_candidate_feature_unique"] is False - assert report["status"] == "blocked_feature_equivalent_range" diff --git a/tests/test_minute_rectification_development.py b/tests/test_minute_rectification_development.py deleted file mode 100644 index 821b8467e..000000000 --- a/tests/test_minute_rectification_development.py +++ /dev/null @@ -1,47 +0,0 @@ -import json -from copy import deepcopy -from pathlib import Path - -from scripts.minute_rectification_development_validator import DEFAULT_MANIFEST, validate -from scripts.minute_rectification_development_eval import run - - -def test_public_development_case_is_valid_but_cannot_enter_holdout() -> None: - report = validate() - - assert report["status"] == "ready_for_development" - assert report["valid_development_cases"] == 3 - assert report["excluded_from_holdout"] is True - assert report["may_open_release_gate"] is False - - -def test_development_case_must_be_permanently_excluded_from_holdout(tmp_path: Path) -> None: - manifest = json.loads(DEFAULT_MANIFEST.read_text(encoding="utf-8")) - changed = deepcopy(manifest) - changed["cases"][0]["excluded_from_holdout"] = False - path = tmp_path / "invalid-development.json" - path.write_text(json.dumps(changed), encoding="utf-8") - - report = validate(path) - - assert report["status"] == "blocked" - assert "case_not_excluded_from_holdout" in report["invalid_cases"][0]["errors"] - - -def test_v3_development_result_stays_shadow_only() -> None: - report = run() - - assert report["case_count"] == 3 - assert report["summary"]["v3_shadow_only"] is True - assert report["summary"]["v3_may_replace_production"] is False - assert report["summary"]["decision"] == "reject_v3_production_promotion" - assert report["summary"]["v4_shadow_only"] is True - assert report["summary"]["v4_may_replace_production"] is False - assert report["summary"]["v4_decision"] == "requires_independent_frozen_holdout" - assert report["summary"]["v3_improved_case_count"] == 0 - assert report["summary"]["indistinguishable_adjacent_pair_ratio"] == 0.7 - assert report["summary"]["p6_fact_indistinguishable_adjacent_pair_ratio"] == 0.6333 - assert report["summary"]["p6_fact_difference_opportunity_count"] == 11 - assert report["summary"]["p6_question_ready_opportunity_count"] == 9 - assert report["summary"]["p6_fact_atoms_may_affect_score"] is False - assert all(case["production_confirmation_allowed"] is False for case in report["cases"]) diff --git a/tests/test_minute_rectification_fact_blind_eval_v4.py b/tests/test_minute_rectification_fact_blind_eval_v4.py deleted file mode 100644 index c6a2df2dd..000000000 --- a/tests/test_minute_rectification_fact_blind_eval_v4.py +++ /dev/null @@ -1,21 +0,0 @@ -from scripts.minute_rectification_fact_blind_eval_v4 import _would_confirm - - -def test_v4_holdout_confirmation_requires_every_non_release_gate() -> None: - result = { - "confidence": "high", - "winning_segment": { - "start_time": "10:01", - "end_time": "10:01", - "representative_time": "10:01", - "width_minutes": 1, - }, - "reasons": ["fact_ranker_v4_holdout_not_ready"], - "missing_layers": [], - } - - assert _would_confirm(result) is True - assert _would_confirm({**result, "reasons": [ - "leave_one_event_out_not_passed", "fact_ranker_v4_holdout_not_ready", - ]}) is False - assert _would_confirm({**result, "missing_layers": ["D10"]}) is False diff --git a/tests/test_minute_rectification_fact_ranker_v4.py b/tests/test_minute_rectification_fact_ranker_v4.py deleted file mode 100644 index 065f8a8c6..000000000 --- a/tests/test_minute_rectification_fact_ranker_v4.py +++ /dev/null @@ -1,90 +0,0 @@ -from scripts.minute_rectification_fact_ranker_v4 import ( - ALGORITHM_VERSION, - LAYER_FAMILIES, - rank_fact_rows, - score_fact_ranker_v4, -) - - -def _fact(event_id: str, domain: str, *, varga_house: int, av: int) -> dict: - return { - "event_id": event_id, - "domain": domain, - "vimshottari": {"md": "Sun", "ad": "Moon", "pd": "Mars"}, - "narayana": {"md_sign": 0, "ad_sign": 1}, - "d1": { - "ascendant_sign": 0, - "target_house_lords": ["Moon"], - "active_lord_houses": {"md": 1, "ad": 7, "pd": 3}, - }, - "vargas": [{ - "chart": "D9" if domain == "relationship" else "D10", - "ascendant_sign": 0, - "active_lord_houses": {"md": varga_house, "ad": 3, "pd": 4}, - }], - "arudha_signs": {"A7": 0} if domain == "relationship" else {"A10": 0}, - "ashtakavarga_target_house_scores": {"7": av}, - "verified_shadbala_state": ["shadbala_sthana_drik_naisargika_support_auxiliary"], - } - - -def _rows() -> list[dict]: - return [ - { - "time": candidate, - "feature_contract_version": "minute-rectification-feature-facts-v4-shadow", - "event_facts": [ - _fact("event-career", "career", varga_house=varga_house, av=av), - _fact("event-relationship", "relationship", varga_house=varga_house, av=av), - ], - "missing_layers": [], - } - for candidate, varga_house, av in ( - ("10:00", 3, 20), - ("10:01", 10, 32), - ("10:02", 3, 20), - ) - ] - - -def _events() -> list[dict]: - return [ - {"id": "event-career", "domain": "career", "date": "2020", "precision": "year"}, - {"id": "event-relationship", "domain": "relationship", "date": "2021-03", "precision": "month"}, - ] - - -def test_fact_ranker_uses_candidate_differences_and_balances_domains() -> None: - rows, contract = rank_fact_rows(_rows(), _events()) - - assert max(rows, key=lambda row: row["score"])["time"] == "10:01" - assert contract["algorithm_version"] == ALGORITHM_VERSION - assert contract["shadow_only"] is True - assert set(contract["layer_weights"]) == set(LAYER_FAMILIES) - assert set(contract["candidate_domain_scores"]["10:01"]) == {"career", "relationship"} - - -def test_fact_ranker_ablation_and_safety_gates_never_apply_a_minute() -> None: - result = score_fact_ranker_v4(_rows(), _events()) - - assert result["can_apply"] is False - assert result["shadow_only"] is True - assert "fact_ranker_v4_holdout_not_ready" in result["reasons"] - assert { - run["removed_layer"] for run in result["stability_diagnostics"]["ablation"]["runs"] - } == set(LAYER_FAMILIES) - assert result["stability_diagnostics"]["neighbor_stability"]["all_required_passed"] is False - assert result["stability_diagnostics"]["leave_one_event_out"]["status"] == "pass" - - -def test_constant_fact_layers_contribute_zero_candidate_preference() -> None: - rows = _rows() - for row in rows: - for fact in row["event_facts"]: - fact["vargas"][0]["active_lord_houses"]["md"] = 3 - fact["ashtakavarga_target_house_scores"]["7"] = 28 - - ranked, contract = rank_fact_rows(rows, _events()) - - assert len({row["score"] for row in ranked}) == 1 - assert all(score == 0 for score in contract["event_raw_scores"]["event-career"].values()) diff --git a/tests/test_minute_rectification_feature_facts_v4.py b/tests/test_minute_rectification_feature_facts_v4.py deleted file mode 100644 index 4c819de92..000000000 --- a/tests/test_minute_rectification_feature_facts_v4.py +++ /dev/null @@ -1,85 +0,0 @@ -from tests.conftest import FIXTURE_BIRTH_DATE, FIXTURE_BIRTH_LAT, FIXTURE_BIRTH_LON - -from datetime import datetime - -from scripts.minute_rectification_feature_facts_v4 import ( - FEATURE_CONTRACT_VERSION, - analyze_feature_fact_rows, - build_fact_difference_opportunities, - build_feature_fact_rows, - feature_fact_fingerprint, -) - - -def _fact_row(time: str, ad_lord: str) -> dict: - return { - "time": time, - "feature_contract_version": FEATURE_CONTRACT_VERSION, - "event_facts": [{ - "event_id": "career-event", - "domain": "career", - "vimshottari": {"md": "Sun", "ad": ad_lord, "pd": "Mercury"}, - }], - "missing_layers": [], - } - - -def test_fact_fingerprint_ignores_time_but_preserves_dasha_actor_identity() -> None: - assert feature_fact_fingerprint(_fact_row("10:00", "Moon")) == feature_fact_fingerprint( - _fact_row("10:01", "Moon") - ) - assert feature_fact_fingerprint(_fact_row("10:00", "Moon")) != feature_fact_fingerprint( - _fact_row("10:00", "Mars") - ) - - -def test_fact_audit_exposes_change_hidden_by_generic_rule_name() -> None: - report = analyze_feature_fact_rows([ - _fact_row("10:00", "Moon"), - _fact_row("10:01", "Mars"), - ]) - - assert report["unique_feature_fingerprint_count"] == 2 - assert report["indistinguishable_adjacent_pair_count"] == 0 - assert report["adjacent_transitions"][0]["changed_event_ids"] == ["career-event"] - assert report["shadow_only"] is True - assert report["may_affect_candidate_score"] is False - - opportunities = build_fact_difference_opportunities([ - _fact_row("10:00", "Moon"), - _fact_row("10:01", "Mars"), - ]) - assert len(opportunities) == 1 - assert opportunities[0]["event_id"] == "career-event" - assert [item["candidate_times"] for item in opportunities[0]["partitions"]] == [ - ["10:00"], ["10:01"], - ] - assert opportunities[0]["may_score_candidates"] is False - assert opportunities[0]["question_ready"] is True - assert opportunities[0]["requires_partition_coalescing"] is False - - -def test_real_fact_rows_include_dual_dasha_varga_arudha_av_and_shadbala() -> None: - rows = build_feature_fact_rows({ - "birth_date": FIXTURE_BIRTH_DATE, - "start_time": "14:29", - "end_time": "14:30", - "lat": FIXTURE_BIRTH_LAT, - "lon": FIXTURE_BIRTH_LON, - "tz": 8.0, - "events": [{ - "id": "career-event", - "domain": "career", - "date": "2019-07-01", - "precision": "day", - }], - }, candidates=[datetime(1993, 4, 17, 14, 29), datetime(1993, 4, 17, 14, 30)]) - - fact = rows[0]["event_facts"][0] - assert set(fact["vimshottari"]) == {"md", "ad", "pd"} - assert set(fact["narayana"]) == {"md_sign", "ad_sign"} - assert fact["vargas"][0]["chart"] == "D10" - assert "A10" in fact["arudha_signs"] - assert "10" in fact["ashtakavarga_target_house_scores"] - assert isinstance(fact["verified_shadbala_state"], list) - assert all(row["feature_contract_version"] == FEATURE_CONTRACT_VERSION for row in rows) diff --git a/tests/test_minute_rectification_holdout_intake.py b/tests/test_minute_rectification_holdout_intake.py deleted file mode 100644 index ca4ee282e..000000000 --- a/tests/test_minute_rectification_holdout_intake.py +++ /dev/null @@ -1,188 +0,0 @@ -import hashlib -import json -from copy import deepcopy -from pathlib import Path - -from scripts.minute_rectification_holdout_intake import DEFAULT_INTAKE, append_case -from scripts.minute_rectification_holdout_validator import ( - DEFAULT_MANIFEST, - FRESH_HUMAN_REVIEW_KIND, - MIGRATED_HUMAN_REVIEW_KIND, - case_errors, -) - -V3_HOLDOUT = Path(__file__).resolve().parents[1] / "references" / "real_case_calibration" / "minute_rectification_holdout_v3.json" -EXPECTED_V4_INTAKE_CASE_IDS = { - "barack_obama_1961_aa_v4_holdout", - "paul_ryan_1970_aa_v4_holdout", - "sean_lennon_1975_aa_v4_holdout", - "kurt_cobain_1967_aa_v4_holdout", -} - - -def _reviewed_case() -> dict: - case = deepcopy(json.loads(DEFAULT_MANIFEST.read_text(encoding="utf-8"))["cases"][0]) - case["case_id"] = "new-reviewed-case" - case["adjudicator"] = "independent-reviewer" - case["independent_human_reviewed"] = True - case["human_review_kind"] = FRESH_HUMAN_REVIEW_KIND - case["frozen_before_scoring"] = True - case["false_minute_commitments"] = [ - { - "offset_minutes": offset, - "commitment_hash": hashlib.sha256(f"control:{offset}".encode()).hexdigest(), - } - for offset in case["false_minute_offsets"] - ] - return case - - -def _queue(path: Path) -> None: - path.write_text(json.dumps({ - "schema_version": "minute-rectification-holdout-v4-intake", - "minimum_gate": { - "events_per_case": 3, - "domains_per_case": 2, - "independent_event_sources_per_case": 2, - "negative_minutes_per_case": 4, - "day_precision_events_per_case": 3, - }, - "cases": [], - }), encoding="utf-8") - - -def test_intake_appends_reviewed_case_but_keeps_release_blocked(tmp_path: Path) -> None: - path = tmp_path / "intake.json" - _queue(path) - - report = append_case(path, _reviewed_case()) - data = json.loads(path.read_text(encoding="utf-8")) - - assert report["appended"] is True - assert report["verified_minute_claim_allowed"] is False - assert data["production_tuning_allowed"] is False - assert data["verified_minute_claim_allowed"] is False - assert data["cases"][0]["ingested_at"].endswith("Z") - - -def test_intake_rejects_boolean_review_without_fresh_biography_audit(tmp_path: Path) -> None: - path = tmp_path / "intake.json" - _queue(path) - case = _reviewed_case() - case["human_review_kind"] = MIGRATED_HUMAN_REVIEW_KIND - - report = append_case(path, case) - - assert report["appended"] is False - assert "independent_review_requires_fresh_biography_audit" in report["errors"] - assert json.loads(path.read_text(encoding="utf-8"))["cases"] == [] - - -def test_intake_rejects_missing_review_and_commitments(tmp_path: Path) -> None: - path = tmp_path / "intake.json" - _queue(path) - case = _reviewed_case() - case["independent_human_reviewed"] = False - case["false_minute_commitments"] = [] - - report = append_case(path, case) - - assert report["appended"] is False - assert "independent_review_not_attested" in report["errors"] - assert "false_minute_commitments_do_not_match_offsets" in report["errors"] - - -def test_default_intake_is_non_production_and_contains_day_precision_v3_cases() -> None: - data = json.loads(DEFAULT_INTAKE.read_text(encoding="utf-8")) - gate = data["minimum_gate"] - - assert {case["case_id"] for case in data["cases"]} == EXPECTED_V4_INTAKE_CASE_IDS - assert len(data["cases"]) == 4 - assert data["production_tuning_allowed"] is False - assert data["verified_minute_claim_allowed"] is False - assert data["status"] == "exposed_awaiting_human_rereview" - assert data["blind_holdout_eligible_case_count"] == 0 - assert data["exposed_awaiting_human_rereview_case_count"] == 4 - for case in data["cases"]: - assert case["prior_score_exposures"] - assert case["human_review_kind"] == MIGRATED_HUMAN_REVIEW_KIND - assert case["independent_human_reviewed"] is False - assert case["frozen_before_scoring"] is False - assert case["holdout_partition"] == "exposed_awaiting_human_rereview" - errors = case_errors(case, gate, require_review_safeguards=True) - assert "results_already_seen_cannot_be_blind_holdout" in errors - assert "migrated_review_does_not_satisfy_safeguard" in errors - assert "fresh_biography_audit_not_attested" in errors - eligible = [ - case["case_id"] - for case in data["cases"] - if not case_errors(case, gate, require_review_safeguards=True) - ] - assert eligible == [] - - -def test_exposed_case_cannot_pass_blind_holdout_safeguards() -> None: - case = _reviewed_case() - case["prior_score_exposures"] = [ - { - "evaluation_kind": "v3_blind_replay", - "report_path": "references/real_case_calibration/minute_rectification_holdout_v3_report.json", - }, - { - "evaluation_kind": "post_audit_sidecar_diagnostic", - "report_path": "references/real_case_calibration/minute_rectification_holdout_v3_post_audit_diagnostic_report.json", - }, - ] - gate = json.loads(DEFAULT_INTAKE.read_text(encoding="utf-8"))["minimum_gate"] - errors = case_errors(case, gate, require_review_safeguards=True) - assert "results_already_seen_cannot_be_blind_holdout" in errors - - -def test_migrated_human_review_does_not_satisfy_safeguards() -> None: - case = _reviewed_case() - case["human_review_kind"] = MIGRATED_HUMAN_REVIEW_KIND - case["adjudicator"] = "v3_sealed_set_post_audit_migration" - gate = json.loads(DEFAULT_INTAKE.read_text(encoding="utf-8"))["minimum_gate"] - errors = case_errors(case, gate, require_review_safeguards=True) - assert "migrated_review_does_not_satisfy_safeguard" in errors - assert "fresh_biography_audit_not_attested" in errors - - -def test_fresh_unseen_reviewed_case_still_passes_safeguards() -> None: - case = _reviewed_case() - assert "prior_score_exposures" not in case - gate = json.loads(DEFAULT_INTAKE.read_text(encoding="utf-8"))["minimum_gate"] - assert case_errors(case, gate, require_review_safeguards=True) == [] - - -def test_year_precision_v3_cases_are_rejected_for_insufficient_day_precision() -> None: - v3 = json.loads(V3_HOLDOUT.read_text(encoding="utf-8")) - gate = json.loads(DEFAULT_INTAKE.read_text(encoding="utf-8"))["minimum_gate"] - rejected: dict[str, list[str]] = {} - for case in v3["cases"]: - payload = deepcopy(case) - payload.update({ - "adjudicator": "v3_sealed_set_post_audit_migration", - "human_review_kind": MIGRATED_HUMAN_REVIEW_KIND, - "independent_human_reviewed": True, - "frozen_before_scoring": True, - "false_minute_commitments": [ - { - "offset_minutes": offset, - "commitment_hash": hashlib.sha256(f"control:{offset}".encode()).hexdigest(), - } - for offset in case["false_minute_offsets"] - ], - }) - errors = case_errors(payload, gate, require_review_safeguards=True) - if errors: - rejected[str(case["case_id"])] = errors - - assert "insufficient_day_precision_events" in rejected["john_robbins_1947_aa_v4_holdout"] - assert "insufficient_day_precision_events" in rejected["iwao_takamoto_1925_aa_v4_holdout"] - assert "insufficient_day_precision_events" in rejected["angelina_jolie_1975_aa_v4_holdout"] - for case_id in EXPECTED_V4_INTAKE_CASE_IDS: - assert "migrated_review_does_not_satisfy_safeguard" in rejected[case_id] - assert "fresh_biography_audit_not_attested" in rejected[case_id] - assert "insufficient_day_precision_events" not in rejected[case_id] - assert all("insufficient_day_precision_events" in errors for case_id, errors in rejected.items() if case_id not in EXPECTED_V4_INTAKE_CASE_IDS) diff --git a/tests/test_minute_rectification_holdout_validator.py b/tests/test_minute_rectification_holdout_validator.py deleted file mode 100644 index 62f503515..000000000 --- a/tests/test_minute_rectification_holdout_validator.py +++ /dev/null @@ -1,194 +0,0 @@ -import hashlib -import json -from copy import deepcopy -from pathlib import Path - -from scripts.minute_rectification_blind_eval import _candidate_moments, implementation_sha256, summarize_trials -from scripts.minute_rectification_holdout_validator import DEFAULT_MANIFEST, validate - - -def _manifest() -> dict: - return json.loads(DEFAULT_MANIFEST.read_text(encoding="utf-8")) - - -def test_seeded_public_minute_protocol_remains_blocked_below_twenty_cases() -> None: - report = validate() - assert report["status"] == "blocked_awaiting_public_aa_cases" - assert report["verified_minute_claim_allowed"] is False - assert report["valid_public_aa_cases"] == 1 - assert report["invalid_cases"] == [] - - -def test_frozen_implementation_hash_matches_manifest() -> None: - manifest = _manifest() - frozen = manifest["frozen_scoring"] - assert implementation_sha256(frozen["files"]) == frozen["implementation_sha256"] - - -def test_validator_accepts_the_new_sealed_schema_version(tmp_path: Path) -> None: - manifest = _manifest() - manifest["schema_version"] = "minute-rectification-holdout-v3" - manifest["source_audit_status"] = "passed_before_freeze" - path = tmp_path / "v3.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - - report = validate(path) - - assert "unsupported_schema_version" not in report["manifest_errors"] - - -def test_v3_validator_requires_content_source_audit_before_freeze(tmp_path: Path) -> None: - manifest = _manifest() - manifest["schema_version"] = "minute-rectification-holdout-v3" - manifest["source_audit_status"] = "invalidated_after_replay" - path = tmp_path / "invalid-source-audit.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - - report = validate(path) - - assert "source_content_audit_not_passed_before_freeze" in report["manifest_errors"] - assert report["status"] == "blocked_awaiting_public_aa_cases" - - -def _add_v4_review_safeguards(manifest: dict) -> None: - manifest["schema_version"] = "minute-rectification-holdout-v4" - manifest["source_audit_status"] = "passed_before_freeze" - manifest["minimum_gate"]["day_precision_events_per_case"] = 3 - for case in manifest["cases"]: - case["adjudicator"] = "independent-reviewer" - case["independent_human_reviewed"] = True - case["human_review_kind"] = "fresh_biography_audit" - case["frozen_before_scoring"] = True - case["false_minute_commitments"] = [ - { - "offset_minutes": offset, - "commitment_hash": hashlib.sha256( - f"{case['case_id']}:{offset}:sealed".encode() - ).hexdigest(), - } - for offset in case["false_minute_offsets"] - ] - - -def test_v4_validator_accepts_reviewed_cases_with_committed_false_minutes(tmp_path: Path) -> None: - manifest = deepcopy(_manifest()) - _add_v4_review_safeguards(manifest) - path = tmp_path / "v4.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - - report = validate(path) - - assert report["manifest_errors"] == [] - assert report["invalid_case_details"] == [] - - -def test_v4_validator_rejects_unreviewed_or_uncommitted_cases(tmp_path: Path) -> None: - manifest = deepcopy(_manifest()) - _add_v4_review_safeguards(manifest) - case = manifest["cases"][0] - case["independent_human_reviewed"] = False - case["false_minute_commitments"].pop() - path = tmp_path / "invalid-v4.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - - errors = validate(path)["invalid_case_details"][0]["errors"] - - assert "independent_review_not_attested" in errors - assert "false_minute_commitments_do_not_match_offsets" in errors - - -def test_v4_safeguards_reject_exposed_or_migrated_review(tmp_path: Path) -> None: - manifest = deepcopy(_manifest()) - _add_v4_review_safeguards(manifest) - exposed = manifest["cases"][0] - exposed["prior_score_exposures"] = [ - {"report_path": "references/real_case_calibration/minute_rectification_holdout_v3_report.json"}, - ] - path = tmp_path / "exposed-v4.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - assert "results_already_seen_cannot_be_blind_holdout" in validate(path)["invalid_case_details"][0]["errors"] - - migrated = deepcopy(_manifest()) - _add_v4_review_safeguards(migrated) - migrated["cases"][0]["human_review_kind"] = "migrated_v3_record" - path = tmp_path / "migrated-v4.json" - path.write_text(json.dumps(migrated), encoding="utf-8") - errors = validate(path)["invalid_case_details"][0]["errors"] - assert "migrated_review_does_not_satisfy_safeguard" in errors - assert "fresh_biography_audit_not_attested" in errors - -def test_validator_rejects_tuning_case_and_non_independent_event_source(tmp_path: Path) -> None: - manifest = deepcopy(_manifest()) - case = manifest["cases"][0] - case["excluded_from_tuning"] = False - case["events"][0]["source"]["url"] = case["birth"]["source"]["url"] - path = tmp_path / "invalid.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - - report = validate(path) - errors = report["invalid_case_details"][0]["errors"] - assert "case_not_excluded_from_tuning" in errors - assert "event_1_source_not_independent_of_birth" in errors - assert report["valid_public_aa_cases"] == 0 - - -def test_validator_requires_adjacent_false_minutes_on_both_sides(tmp_path: Path) -> None: - manifest = deepcopy(_manifest()) - manifest["cases"][0]["false_minute_offsets"] = [1, 2, 5, 10] - path = tmp_path / "one-sided.json" - path.write_text(json.dumps(manifest), encoding="utf-8") - - errors = validate(path)["invalid_case_details"][0]["errors"] - assert "false_minutes_do_not_cover_both_sides" in errors - assert "false_minutes_missing_adjacent_controls" in errors - - -def test_metric_summary_reports_accuracy_error_and_rejection() -> None: - trials = [ - { - "true_rank": 1, - "minute_error": 0, - "false_confirmation": False, - "insufficient_evidence_rejected": True, - "would_confirm": True, - }, - { - "true_rank": 4, - "minute_error": 4, - "false_confirmation": True, - "insufficient_evidence_rejected": False, - "would_confirm": True, - }, - ] - gates = { - "top_1_rate_minimum": 0.5, - "top_3_rate_minimum": 0.5, - "mean_absolute_minute_error_maximum": 2.0, - "false_confirmation_rate_maximum": 0.5, - "correct_insufficient_evidence_rejection_rate_minimum": 0.5, - } - - report = summarize_trials(trials, gates) - - assert report["metrics"] == { - "top_1_rate": 0.5, - "top_3_rate": 0.5, - "mean_absolute_minute_error": 2.0, - "false_confirmation_rate": 0.5, - "correct_insufficient_evidence_rejection_rate": 0.5, - "confirmation_coverage_rate": 1.0, - } - assert report["metric_gates_passed"] is True - - -def test_blind_candidate_moments_preserve_real_dates_across_midnight() -> None: - case = { - "candidate_radius_minutes": 5, - "birth": {"date": "2000-01-02", "time": "00:03"}, - } - - moments = _candidate_moments(case) - - assert moments[0].isoformat() == "2000-01-01T23:58:00" - assert moments[5].isoformat() == "2000-01-02T00:03:00" - assert moments[-1].isoformat() == "2000-01-02T00:08:00" diff --git a/tests/test_minute_rectification_pairwise_v3.py b/tests/test_minute_rectification_pairwise_v3.py deleted file mode 100644 index a8a2d1e2e..000000000 --- a/tests/test_minute_rectification_pairwise_v3.py +++ /dev/null @@ -1,77 +0,0 @@ -from scripts.minute_rectification_pairwise_v3 import rank_candidate_rows, score_pairwise_v3 - - -def _events() -> list[dict]: - return [ - {"id": "career-1", "domain": "career", "date": "2000", "precision": "year"}, - {"id": "career-2", "domain": "career", "date": "2001", "precision": "year"}, - {"id": "relationship-1", "domain": "relationship", "date": "2002", "precision": "year"}, - ] - - -def _row(time: str, values: dict[str, float]) -> dict: - domains = {event["id"]: event["domain"] for event in _events()} - return { - "time": time, - "score": sum(values.values()), - "evidence": [ - { - "event_id": event_id, - "domain": domains[event_id], - "candidate_time": time, - "rule_ids": [f"rule-{event_id}"], - "points": points, - } - for event_id, points in values.items() - ], - "missing_layers": [], - } - - -def test_constant_event_contributes_zero_to_every_candidate() -> None: - events = [{"id": "career-1", "domain": "career", "date": "2000", "precision": "year"}] - rows = [ - _row("10:00", {"career-1": 5.0}), - _row("10:01", {"career-1": 5.0}), - ] - - ranked, contract = rank_candidate_rows(rows, events) - - assert [row["score"] for row in ranked] == [0.0, 0.0] - assert contract["constant_event_ids"] == ["career-1"] - assert contract["discriminating_event_ids"] == [] - - -def test_repeated_career_events_do_not_outvote_relationship_domain() -> None: - rows = [ - _row("10:00", {"career-1": 10, "career-2": 10, "relationship-1": 0}), - _row("10:01", {"career-1": 0, "career-2": 0, "relationship-1": 10}), - ] - - ranked, contract = rank_candidate_rows(rows, _events()) - - assert [row["score"] for row in ranked] == [50.0, 50.0] - assert contract["candidate_domain_scores"]["10:00"] == {"career": 1.0, "relationship": 0.0} - assert contract["candidate_domain_scores"]["10:01"] == {"career": 0.0, "relationship": 1.0} - - -def test_v3_never_opens_confirmation_without_new_holdout() -> None: - rows = [ - _row("09:55", {"career-1": 0, "career-2": 0, "relationship-1": 0}), - _row("09:56", {"career-1": 1, "career-2": 1, "relationship-1": 1}), - _row("09:57", {"career-1": 2, "career-2": 2, "relationship-1": 2}), - _row("09:58", {"career-1": 3, "career-2": 3, "relationship-1": 3}), - _row("09:59", {"career-1": 4, "career-2": 4, "relationship-1": 4}), - _row("10:00", {"career-1": 10, "career-2": 10, "relationship-1": 10}), - _row("10:01", {"career-1": 4, "career-2": 4, "relationship-1": 4}), - _row("10:02", {"career-1": 3, "career-2": 3, "relationship-1": 3}), - _row("10:03", {"career-1": 2, "career-2": 2, "relationship-1": 2}), - _row("10:04", {"career-1": 1, "career-2": 1, "relationship-1": 1}), - _row("10:05", {"career-1": 0, "career-2": 0, "relationship-1": 0}), - ] - - result = score_pairwise_v3(rows, _events()) - - assert result["winning_segment"]["representative_time"] == "10:00" - assert result["can_apply"] is False - assert "pairwise_v3_holdout_not_ready" in result["reasons"] diff --git a/tests/test_minute_rectification_source_audit.py b/tests/test_minute_rectification_source_audit.py deleted file mode 100644 index 106d8cbf4..000000000 --- a/tests/test_minute_rectification_source_audit.py +++ /dev/null @@ -1,24 +0,0 @@ -import json -from pathlib import Path - -from scripts.minute_rectification_source_audit import build_source_audit - - -def test_source_audit_supports_current_holdout_shape_and_counts_day_precision(tmp_path: Path) -> None: - source = tmp_path / "cases.json" - source.write_text(json.dumps({"cases": [{ - "case_id": "public-case", - "subject_label": "Public case", - "birth": {"source": {"rodden_rating": "AA", "url": "https://example.test/birth"}}, - "events": [ - {"date": "2001-01-01"}, - {"date": "2002"}, - ], - }]}), encoding="utf-8") - - report = build_source_audit([source]) - - assert report["public_aa_case_count"] == 1 - assert report["cases"][0]["existing_day_precision_event_count"] == 1 - assert report["cases"][0]["additional_day_precision_events_required"] == 2 - assert report["production_tuning_allowed"] is False diff --git a/tests/test_minute_resolution_research.py b/tests/test_minute_resolution_research.py deleted file mode 100644 index 12eb597f4..000000000 --- a/tests/test_minute_resolution_research.py +++ /dev/null @@ -1,97 +0,0 @@ -from __future__ import annotations - -from scripts.research.holdout_v4_build import MIN_DOMAINS, MIN_EVENTS, build -from scripts.research.minute_resolution_lib import ( - aggregate_samples, - dynamic_signature_layers, - rescale_varga_points, - shannon_entropy, - subtract_event_floor, - varga_divisor, -) -from scripts.research.minute_resolution_sweep import all_variants, verdict - - -def test_v4_cases_meet_event_and_domain_floors() -> None: - payload = build() - assert payload["ayanamsa"] == "raman" - assert payload["node_mode"] == "mean" - assert len(payload["cases"]) >= 8 - for case in payload["cases"]: - domains = {item["domain"] for item in case["events"]} - assert len(case["events"]) >= MIN_EVENTS, case["case_id"] - assert len(domains) >= MIN_DOMAINS, case["case_id"] - assert case["birth"]["source"]["rodden_rating"] == "AA" - assert str(case["birth"]["time"])[:5] == case["true_minute"] - - -def test_varga_divisor_modes() -> None: - assert varga_divisor(1, "2len") == 2.0 - assert varga_divisor(3, "2len") == 6.0 - assert varga_divisor(3, "len") == 3.0 - assert abs(varga_divisor(4, "sqrt") - 2.0) < 1e-9 - assert varga_divisor(3, "fixed2") == 2.0 - - -def test_year_aggregation_keeps_peak() -> None: - samples = [1.0, 1.0, 12.0] - assert aggregate_samples(samples, "mean") == 4.6667 - assert aggregate_samples(samples, "max") == 12.0 - lse = aggregate_samples(samples, "lse", 1.0) - assert lse > aggregate_samples(samples, "mean") - assert lse < 12.0 - - -def test_subtract_event_floor_zeroes_the_min() -> None: - out = subtract_event_floor({"04:50": 11.0, "04:51": 13.5, "04:52": 11.0}) - assert out["04:50"] == 0.0 - assert out["04:51"] == 2.5 - - -def test_entropy_is_zero_for_a_spike() -> None: - assert shannon_entropy([0, 0, 5]) == 0.0 - assert shannon_entropy([1, 1]) > 0.9 - - -def test_varga_rescale_doubles_single_chart_hit() -> None: - points = rescale_varga_points( - 1.0, - ["vim_md_domain_varga", "event_kind:career_change"], - "career", - "career_change", - "day", - "len", - ) - assert points > 1.0 - - -def test_dynamic_layers_drop_md_and_follow_domains() -> None: - layers = dynamic_signature_layers(["career", "health_pressure"]) - assert layers[0] == "d1" - assert "d10" in layers - assert "d30" in layers - assert "md" not in layers - - -def test_variant_grid_covers_pairs() -> None: - names = {item.name for item in all_variants()} - assert "baseline" in names - assert "R1@len" in names - assert "R3@1.0" in names - assert "R1+R3" in names - pair = next(item for item in all_variants() if item.name == "R1+R3") - assert pair.r1 == "len" - assert pair.r3 == 1.0 - - -def test_verdict_requires_hit_and_coverage() -> None: - baseline = { - "n": 10, "top1": 0.2, "coverage": 0.9, "width_median": 21, "tie": 0.8, - "squeezed": 1, "entropy0": 3.0, "entropy6": 2.0, "too_narrow": 0, "replay_top1": 0.5, - } - better = { - **baseline, "top1": 0.4, "tie": 0.4, "width_median": 12, "squeezed": 0, - } - worse = {**baseline, "top1": 0.1, "coverage": 0.7, "squeezed": 3} - assert verdict(baseline, better) == "benefit" - assert verdict(baseline, worse) == "no_benefit" diff --git a/tests/test_offline_research_20260926.py b/tests/test_offline_research_20260926.py deleted file mode 100644 index e97200d34..000000000 --- a/tests/test_offline_research_20260926.py +++ /dev/null @@ -1,77 +0,0 @@ -"""Pure-helper regression tests for the 2026-09-26 offline rectification research. - -Fictional inputs only. These cover the research helpers, not production code. -""" -from __future__ import annotations - -from datetime import date, timedelta - -from scripts.research.offline_research_20260926_lib import ( - NAKSHATRA_SPAN, - answerable_indices, - exhaustive_flip_sets, - flipped_answers, - nakshatra_lord, - sample_flip_sets, - shift_days_per_minute, - zip_misaligned, -) -from scripts.research.representative_pairs_probe import strict_boundary_windows -from scripts.research.varga_sensitivity_rerun import V1N_FACTORS, factor_table - -MEAN_MOON_DEG_PER_DAY = 13.176 - - -def test_shift_per_minute_is_about_one_year_per_degree_not_122_days() -> None: - venus = shift_days_per_minute(NAKSHATRA_SPAN * 1 + 1.0, MEAN_MOON_DEG_PER_DAY) - sun = shift_days_per_minute(NAKSHATRA_SPAN * 2 + 1.0, MEAN_MOON_DEG_PER_DAY) - assert nakshatra_lord(NAKSHATRA_SPAN * 1 + 1.0) == "Venus" - assert nakshatra_lord(NAKSHATRA_SPAN * 2 + 1.0) == "Sun" - assert 4.9 < venus < 5.1 - assert 1.45 < sun < 1.55 - # The 2026-09-14 figure (1.1 days) is below the slowest lord at mean speed. - assert sun > 1.1 - - -def test_flip_sets_are_seeded_and_only_touch_answered_questions() -> None: - answers = ["yes", None, "no", "yes", None, "no"] - assert answerable_indices(answers) == [0, 2, 3, 5] - first = sample_flip_sets(answers, 2, 5, case_id="fictional", radius=10) - again = sample_flip_sets(answers, 2, 5, case_id="fictional", radius=10) - assert first == again - assert all(len(item) == 2 and set(item) <= {0, 2, 3, 5} for item in first) - assert sample_flip_sets(answers, 5, 3, case_id="fictional", radius=10) == [] - assert len(exhaustive_flip_sets(answers, 2)) == 6 - assert flipped_answers(answers, (0, 2)) == ["no", None, "yes", "yes", None, "no"] - - -# Unequal spacing, like real dasha periods (equal spacing would make an -# off-by-one zip look like a constant shift). -OFFSETS = (0, 300, 1000, 1200, 2500, 2600) - - -def test_zip_misalignment_detects_off_by_one_lists() -> None: - base = [date(2000, 1, 10) + timedelta(days=days) for days in OFFSETS] - shifted = [item + timedelta(days=20) for item in base] - assert not zip_misaligned(base, shifted) - assert zip_misaligned(base[1:], shifted) - - -def test_strict_gate_drops_year_straddle_and_realigns() -> None: - left = [date(1999, 12, 28), date(2003, 5, 1)] - right = [date(2000, 1, 4), date(2003, 5, 8)] - assert strict_boundary_windows(left, right, min_days=45) == [] - base = [date(2000, 3, 1) + timedelta(days=days) for days in OFFSETS] - later = [item + timedelta(days=10) for item in base] - assert strict_boundary_windows(base, later[1:], min_days=45) == [] - far = [item + timedelta(days=60) for item in base] - assert len(strict_boundary_windows(base, far, min_days=45)) == 2 * len(OFFSETS) - - -def test_v1_saturates_on_wide_windows_and_v1n_keeps_mean_one() -> None: - table = factor_table() - assert set(table["30"].values()) == {1.0} - assert set(table["60"].values()) == {1.0} - assert table["10"]["D2"] < 1.0 - assert abs(sum(V1N_FACTORS.values()) / len(V1N_FACTORS) - 1.0) < 1e-4 - assert V1N_FACTORS["D30"] > V1N_FACTORS["D2"] diff --git a/tests/test_rect_scoring_perf_20261013.py b/tests/test_rect_scoring_perf_20261013.py deleted file mode 100644 index 63375eaee..000000000 --- a/tests/test_rect_scoring_perf_20261013.py +++ /dev/null @@ -1,361 +0,0 @@ -"""Output-identical speedups for rectification scoring (BUG-1323, 1324, 1325, 1345).""" -from __future__ import annotations - -import copy -import inspect -import time -from datetime import date, datetime, timedelta -from unittest.mock import patch - -import pytest - -from scripts.active_rectification_event_engine import ( - _active_narayana, - build_candidate_static_context, - compute_event_candidate_rows, -) -from scripts.rectification.api_service import ( - MAX_CANDIDATES_PER_REQUEST, - TooManyCandidates, - _candidate_count, - _reject_if_too_many_candidates, - block_scan, - diagnostics, - score_candidates, -) -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.dasha_transition_proximity import merge_transition_proximity -from scripts.rectification.event_probes import guided_collect_windows -from scripts.rectification.scoring_service import build_event_contribution_matrix, sha256 -import scripts.active_rectification_event_engine as event_engine -from scripts.rectification import dasha_transition_proximity as proximity -from scripts.rectification import event_probes -from scripts.rectification import scoring_service -from tests._baseline_rect_scoring_20261013 import ( - guided_collect_windows as baseline_guided_collect_windows, - merge_transition_proximity as baseline_merge_transition_proximity, -) - -FROZEN_TODAY = date(2026, 9, 16) -EVENT_SPECS = ( - ("education", "education_start", "2008-01-01", "2008-12-31", "year"), - ("career", "career_entry", "2012-06-01", "2012-06-30", "month"), - ("relocation", "relocation", "2014-03-01", "2014-03-31", "month"), - ("relationship", "relationship_commitment", "2016-10-01", "2016-10-31", "month"), - ("career", "promotion", "2018-01-01", "2018-12-31", "year"), - ("finance", "asset_change", "2019-05-01", "2019-05-31", "month"), - ("family", "family_event", "2020-08-01", "2020-08-31", "month"), - ("health", "self_health_event", "2022-01-01", "2022-12-31", "year"), -) - - -class _FrozenDate(date): - @classmethod - def today(cls) -> date: - return FROZEN_TODAY - - -def _events() -> list[dict]: - rows = [] - for index, (domain, kind, start, end, precision) in enumerate(EVENT_SPECS, start=1): - rows.append({ - "id": f"00000000-0000-4000-8000-{index:012d}", - "domain": domain, - "event_kind": kind, - "date_start": start, - "date_end": end, - "precision": precision, - "summary": "虚构", - }) - return rows - - -def _request(start: str, end: str, **extra) -> dict: - body = { - "birth_date": "1990-01-01", - "start_time": start, - "end_time": end, - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": _events(), - **extra, - } - return normalize_rectification_request(body, today=FROZEN_TODAY) - - -def _count(monkeypatch, owner, name: str) -> list[int]: - original = getattr(owner, name) - counter = [0] - - def wrapped(*args, **kwargs): - counter[0] += 1 - return original(*args, **kwargs) - - monkeypatch.setattr(owner, name, wrapped) - return counter - - -@pytest.fixture(scope="module") -def wide_case(): - request = _request("11:00", "13:00") - captured: dict = {} - original = scoring_service.merge_transition_proximity - - def grab(matrix, events, contexts, birth_date, *, public_technique_layers): - captured["matrix"] = copy.deepcopy(matrix) - captured["events"] = list(events) - captured["contexts"] = contexts - captured["birth_date"] = birth_date - captured["layers"] = public_technique_layers - return original( - matrix, events, contexts, birth_date, - public_technique_layers=public_technique_layers, - ) - - with patch.object(event_probes, "date", _FrozenDate), patch.object( - scoring_service, "merge_transition_proximity", grab, - ): - built = build_event_contribution_matrix(request) - return request, built, captured - - -def test_guided_collect_windows_matches_baseline_and_is_linear(wide_case, monkeypatch) -> None: - request, built, _captured = wide_case - times = list(built["candidate_times"]) - assert len(times) == 121 - variants = [ - (request, times), - (request, times[::2]), - (request, times[:3]), - ({**request, "declined_domains": ["relationship"]}, times), - ] - with patch.object(event_probes, "date", _FrozenDate): - for variant_request, variant_times in variants: - assert guided_collect_windows( - variant_request, built, candidate_times=variant_times, today=FROZEN_TODAY, - ) == baseline_guided_collect_windows( - variant_request, built, candidate_times=variant_times, today=FROZEN_TODAY, - ) - short_built = { - **built, - "static_contexts": list(built["static_contexts"])[:21], - "candidate_times": times[:21], - } - full_calls = _count(monkeypatch, event_probes, "_context_time") - guided_collect_windows(request, built, candidate_times=times, today=FROZEN_TODAY) - full = full_calls[0] - short_calls = _count(monkeypatch, event_probes, "_context_time") - guided_collect_windows(request, short_built, candidate_times=times[:21], today=FROZEN_TODAY) - short = short_calls[0] - assert full <= 16 * 121 - assert short <= 16 * 21 - assert full / short <= (121 / 21) * 1.2 - - -def test_merge_transition_proximity_matches_baseline(wide_case, monkeypatch) -> None: - _request_wide, _built, captured = wide_case - vim_calls = _count(monkeypatch, proximity, "_vim_start_dates") - nara_calls = _count(monkeypatch, proximity, "_narayana_start_dates") - fresh = copy.deepcopy(captured["matrix"]) - base = copy.deepcopy(captured["matrix"]) - merge_transition_proximity( - fresh, captured["events"], captured["contexts"], captured["birth_date"], - public_technique_layers=captured["layers"], - ) - baseline_merge_transition_proximity( - base, captured["events"], captured["contexts"], captured["birth_date"], - public_technique_layers=captured["layers"], - ) - assert fresh == base - assert vim_calls[0] <= 2 * len(captured["contexts"]) - assert nara_calls[0] <= len(captured["contexts"]) - - midnight = _request("23:20", "00:40") - midnight_captured: dict = {} - original = scoring_service.merge_transition_proximity - - def grab(matrix, events, contexts, birth_date, *, public_technique_layers): - midnight_captured["matrix"] = copy.deepcopy(matrix) - midnight_captured["events"] = list(events) - midnight_captured["contexts"] = contexts - midnight_captured["birth_date"] = birth_date - midnight_captured["layers"] = public_technique_layers - return original(matrix, events, contexts, birth_date, public_technique_layers=public_technique_layers) - - with patch.object(event_probes, "date", _FrozenDate), patch.object( - scoring_service, "merge_transition_proximity", grab, - ): - build_event_contribution_matrix(midnight) - fresh_night = copy.deepcopy(midnight_captured["matrix"]) - base_night = copy.deepcopy(midnight_captured["matrix"]) - merge_transition_proximity( - fresh_night, midnight_captured["events"], midnight_captured["contexts"], midnight_captured["birth_date"], - public_technique_layers=midnight_captured["layers"], - ) - baseline_merge_transition_proximity( - base_night, midnight_captured["events"], midnight_captured["contexts"], midnight_captured["birth_date"], - public_technique_layers=midnight_captured["layers"], - ) - assert fresh_night == base_night - - -def test_static_context_caches_match_fallback_and_stay_out_of_features(wide_case, monkeypatch) -> None: - request, built, _captured = wide_case - contexts = list(built["static_contexts"]) - assert len(contexts) == 121 - for context in contexts: - assert "functional_profile" not in context["feature"] - assert "narayana_antardasha_by_md" not in context["feature"] - assert context.get("functional_profile") - assert context.get("narayana_antardasha_by_md") - features = [context["feature"] for context in contexts] - cleared = [] - for context in contexts: - clone = dict(context) - clone["functional_profile"] = None - clone["narayana_antardasha_by_md"] = None - cleared.append(clone) - engine_request = { - "birth_date": "1990-01-01", - "start_time": "11:00", - "end_time": "13:00", - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": [{ - "id": "00000000-0000-4000-8000-000000000002", - "domain": "career", - "event_kind": "career_entry", - "date": "2012-06-15", - "precision": "day", - "summary": "虚构", - }], - } - assert compute_event_candidate_rows(engine_request, static_contexts=contexts) == compute_event_candidate_rows( - engine_request, static_contexts=cleared, - ) - assert sha256(features) == sha256([dict(feature) for feature in features]) - - functional_calls = _count( - monkeypatch, event_engine.functional_benefics, "derive_functional_benefic_malefic", - ) - narayana_calls = [0] - original = event_engine.narayana_dasha.get_current_narayana_dasha - - def wrapped(*args, **kwargs): - caller = inspect.stack()[1].filename.replace("\\", "/") - names = [frame.function for frame in inspect.stack()] - if caller.endswith("/active_rectification_event_engine.py") and "_candidate_row" in names: - narayana_calls[0] += 1 - return original(*args, **kwargs) - - monkeypatch.setattr(event_engine.narayana_dasha, "get_current_narayana_dasha", wrapped) - with patch.object(event_probes, "date", _FrozenDate): - scored = score_candidates(request, include_internal=True) - functional_during_score = functional_calls[0] - compact = score_candidates(request) - assert functional_during_score == 121 - # Probe path (_score_year) is out of scope and still calls get_current. - # The scoring loop (_candidate_row) must not. - assert narayana_calls[0] == 0 - assert "event_contribution_matrix" in scored - assert "candidate_decision_receipt" in scored - assert "event_contribution_matrix" not in compact - assert "candidate_decision_receipt" not in compact - - def without_timing(value): - if isinstance(value, dict): - return { - key: without_timing(item) - for key, item in value.items() - if key not in {"column_compare_ms", "event_contribution_matrix", "candidate_decision_receipt"} - } - if isinstance(value, list): - return [without_timing(item) for item in value] - return value - - assert without_timing(compact) == without_timing(scored) - assert len(scored["candidate_feature_snapshot"]["features"]) == 121 - assert scored["candidate_feature_snapshot"]["feature_hash"] == compact["candidate_feature_snapshot"]["feature_hash"] - - -def test_cached_narayana_matches_live_lookup_across_ages(wide_case) -> None: - _request, built, _captured = wide_case - contexts = list(built["static_contexts"])[:3] - assert len(contexts) == 3 - for context in contexts: - periods = context["narayana_periods"] - table = context["narayana_antardasha_by_md"] - birth = context["candidate_at"] - planets = context["planet_longitudes"] - asc = context["ascendant_index"] - - def at_age(age: float) -> datetime: - return birth + timedelta(seconds=age * 365.2425 * 86400) - - ages = [index / 100 for index in range(0, 12001)] - total = sum(period["years"] for period in periods) - cycle_start = min(float(period.get("start_age", 0)) for period in periods) - edges = [cycle_start, cycle_start + total] - edges.extend(float(period["start_age"]) for period in periods) - edges.extend(float(period["end_age"]) for period in periods) - for edge in edges: - for delta in (-1e-9, 0.0, 1e-9): - if edge + delta >= 0: - ages.append(edge + delta) - for age in ages: - event_at = at_age(age) - cached = _active_narayana(asc, planets, birth, event_at, periods, table) - live = _active_narayana(asc, planets, birth, event_at, periods, None) - assert cached == live - - -def test_candidate_cap_rejects_before_charts_and_allows_product_windows() -> None: - assert _candidate_count(_request("00:00", "03:59")) == 240 - assert _candidate_count(_request("00:00", "04:00")) == 241 - assert _candidate_count(_request("00:00", "04:01")) == 242 - _reject_if_too_many_candidates(_request("00:00", "03:59")) - _reject_if_too_many_candidates(_request("00:00", "04:00")) - with pytest.raises(TooManyCandidates) as rejected: - _reject_if_too_many_candidates(_request("00:00", "04:01")) - assert rejected.value.code == "too_many_candidates" - assert rejected.value.limit == MAX_CANDIDATES_PER_REQUEST == 241 - assert "count=242" in str(rejected.value) - - full_day = _request("00:00", "23:59") - assert _candidate_count(full_day) == 1440 - started = time.perf_counter() - with pytest.raises(TooManyCandidates) as full: - score_candidates(full_day) - assert time.perf_counter() - started < 0.05 - assert "count=1440" in str(full.value) - with pytest.raises(TooManyCandidates): - diagnostics(full_day) - - step_10 = _request("00:00", "23:59", minute_step=10) - assert _candidate_count(step_10) == 144 - _reject_if_too_many_candidates(step_10) - step_2 = _request("00:00", "03:00", minute_step=2) - step_5 = _request("00:00", "06:00", minute_step=5) - assert _candidate_count(step_2) <= 91 - assert _candidate_count(step_5) <= 121 - _reject_if_too_many_candidates(step_2) - _reject_if_too_many_candidates(step_5) - with patch( - "scripts.rectification.api_service.score_candidates", - return_value={"candidate_scores": [], "decision_receipt": {}}, - ) as scored: - block_scan(step_10) - block_scan(step_2) - block_scan(step_5) - assert scored.call_count == 3 - - -def test_one_candidate_context_exposes_top_level_caches() -> None: - request = _request("12:00", "12:00") - context = build_candidate_static_context(request, datetime(1990, 1, 1, 12, 0)) - assert "functional_profile" not in context["feature"] - assert "narayana_antardasha_by_md" not in context["feature"] - assert context["functional_profile"]["functional_benefics"] or context["functional_profile"]["functional_malefics"] - assert set(context["narayana_antardasha_by_md"]) == {period["sign_idx"] for period in context["narayana_periods"]} diff --git a/tests/test_rectification_confirmation_and.py b/tests/test_rectification_confirmation_and.py deleted file mode 100644 index b1a4bc34d..000000000 --- a/tests/test_rectification_confirmation_and.py +++ /dev/null @@ -1,403 +0,0 @@ -from __future__ import annotations - -import json -from pathlib import Path - -from scripts.rectification.decision_policy import ( - apply_vedastro_minute_sensitive_to_receipt, - build_candidate_decisions, - build_decision_receipt, - indistinguishable_width_minutes, -) -from scripts.rectification.sealed_holdout import ( - holdout_passed, - load_sealed_minute_holdout, -) - - -ROOT = Path(__file__).resolve().parents[1] -V3_REPORT_PATH = ( - ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v3_report.json" -) -DIAGNOSTIC_REPORT_PATH = ( - ROOT / "references" / "real_case_calibration" - / "minute_rectification_holdout_v3_post_audit_diagnostic_report.json" -) -PRODUCT_HOLDOUT_PATH = ROOT / "references" / "rectification_sealed_holdout.v1.json" - - -def _request(*, extra_events=()): - events = [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "career", - "summary": "入职", - "event_kind": "career_entry", - "precision": "day", - "date_start": "2016-09-15", - "date_end": "2016-09-15", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "relationship", - "summary": "开始一段关系", - "event_kind": "relationship_start", - "precision": "day", - "date_start": "2018-03-01", - "date_end": "2018-03-01", - }, - { - "id": "00000000-0000-4000-8000-000000000003", - "domain": "education", - "summary": "毕业", - "event_kind": "education_completion", - "precision": "day", - "date_start": "2015-06-01", - "date_end": "2015-06-01", - }, - { - "id": "00000000-0000-4000-8000-000000000010", - "domain": "career", - "summary": "职责变化", - "event_kind": "career_change", - "precision": "day", - "date_start": "2019-04-01", - "date_end": "2019-04-01", - }, - *extra_events, - ] - return {"events": events} - - -def _diagnostics(): - return { - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "primary_secondary_margin_percent": 50, - } - - -def _rows(): - return [ - {"time": "05:13", "score": 20, "evidence": [], "missing_layers": []}, - {"time": "05:14", "score": 8, "evidence": [], "missing_layers": []}, - ] - - -def test_sealed_holdout_contract_matches_v3_report_and_stays_closed() -> None: - holdout = load_sealed_minute_holdout() - report = json.loads(V3_REPORT_PATH.read_text(encoding="utf-8")) - diagnostic = json.loads(DIAGNOSTIC_REPORT_PATH.read_text(encoding="utf-8")) - product = json.loads(PRODUCT_HOLDOUT_PATH.read_text(encoding="utf-8")) - sidecar = diagnostic["current_tree_unfrozen_diagnostic"] - produced_by = product["metrics_produced_by"] - current_tree = product["current_tree_scorer"] - rerun = json.loads((ROOT / current_tree["source_report"]).read_text(encoding="utf-8")) - unfrozen = product["current_tree_unfrozen_diagnostic"] - assert holdout["sealed_benchmark_id"] == report["benchmark_id"] == product["sealed_benchmark_id"] - assert holdout["valid_public_aa_cases"] == report["validation"]["valid_public_aa_cases"] - assert holdout["required_cases"] == report["validation"]["minimum_public_aa_cases"] - assert holdout["top_1_rate"] == report["release_metrics"]["top_1_rate"]["actual"] - assert holdout["confirmation_coverage_rate"] == report["release_metrics"]["confirmation_coverage_rate"] - assert holdout["status"] == "not_ready" - assert holdout["valid_public_aa_cases"] >= holdout["required_cases"] - assert holdout["confirmation_coverage_rate"] == 0.0 - assert holdout_passed(holdout) is False - assert set(holdout) == { - "sealed_benchmark_id", - "status", - "valid_public_aa_cases", - "required_cases", - "top_1_rate", - "confirmation_coverage_rate", - } - assert produced_by["implementation_sha256"] == report["frozen_scoring"]["implementation_sha256"] - assert produced_by["algorithm_version"] == report["frozen_scoring"]["algorithm_version"] - assert produced_by["implementation_hash_matches_at_replay"] is True - assert produced_by["source_report"] == "references/real_case_calibration/minute_rectification_holdout_v3_report.json" - assert current_tree["implementation_sha256"] == rerun["frozen_record"]["implementation_sha256"] - assert current_tree["extended_identity"] == rerun["frozen_record"]["extended_identity"] - assert "scripts/rectification/dasha_transition_proximity.py" in current_tree["extended_identity"]["production_scoring_files"] - assert product["current_tree_fixed_protocol_rerun"]["extended_identity"] == current_tree["extended_identity"] - assert current_tree["fixed_protocol_rerun_hash_matches"] is rerun["implementation_hash_matches_at_replay"] is True - assert current_tree["fixed_protocol_rerun_trial_count"] == rerun["trial_count"] == 20 - assert rerun["official_valid_independent_blind"] is False - assert current_tree["matches_metrics_scorer"] is False - assert current_tree["official_eval_implementation_hash_matches"] is False - assert current_tree["official_eval_trial_count"] == diagnostic["trial_count"] == 0 - assert current_tree["implementation_sha256"] != produced_by["implementation_sha256"] - assert unfrozen["is_blind_evaluation"] is False - assert unfrozen["is_blind_evaluation"] is diagnostic["is_blind_evaluation"] - assert unfrozen["results_already_seen"] is True - assert unfrozen["scorer_frozen"] is False - assert unfrozen["scorer_frozen"] is diagnostic["frozen_scoring"]["implementation_hash_matches"] - assert unfrozen["source_audit_passed"] is False - assert unfrozen["source_audit_passed"] is report["post_replay_source_audit"]["passed"] - assert unfrozen["must_not_claim_as_release_metrics"] is True - assert unfrozen["must_not_use_for_tuning"] is True - assert unfrozen["report_path"] == ( - "references/real_case_calibration/minute_rectification_holdout_v3_post_audit_diagnostic_report.json" - ) - assert unfrozen["implementation_sha256"] == sidecar["actual_sha256"] - assert unfrozen["trial_count"] == sidecar["trial_count"] - assert unfrozen["top_1_rate"] == sidecar["metrics"]["top_1_rate"] - assert unfrozen["top_3_rate"] == sidecar["metrics"]["top_3_rate"] - assert unfrozen["mean_absolute_minute_error"] == sidecar["metrics"]["mean_absolute_minute_error"] - assert product["top_1_rate"] != unfrozen["top_1_rate"] - assert holdout["top_1_rate"] != unfrozen["top_1_rate"] - - -def test_vedastro_pass_rewrites_audit_but_holdout_still_blocks(monkeypatch) -> None: - extra = [{ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "family", - "summary": "家人变化", - "event_kind": "family_event", - "precision": "day", - "date_start": "2020-01-01", - "date_end": "2020-01-01", - }] - decisions = build_candidate_decisions(_rows(), result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt(_request(extra_events=extra), decisions, {"missing_layers": [], "matrix": {}}, _diagnostics()) - assert receipt["gates"]["exact_confirmation"]["engine_granted"] is True - apply_vedastro_minute_sensitive_to_receipt(receipt, "passed", summary={"discriminated": True}) - audit = {row["technique"]: row for row in receipt["technique_audit_table"]} - assert audit["VedAstro 分钟级校验"]["status"] == "executed" - assert "未调用不等于失败" not in audit["VedAstro 分钟级校验"]["note"] - assert audit["唯一分钟确认"]["status"] == "blocked" - assert receipt["confirmation_allowed"] is False - assert receipt["gates"]["exact_confirmation"]["holdout"]["status"] == "not_ready" - - -def test_confirmation_allowed_only_when_holdout_ready(monkeypatch) -> None: - extra = [{ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "family", - "summary": "家人变化", - "event_kind": "family_event", - "precision": "day", - "date_start": "2020-01-01", - "date_end": "2020-01-01", - }] - monkeypatch.setattr( - "scripts.rectification.decision_policy.load_sealed_minute_holdout", - lambda: { - "sealed_benchmark_id": "minute_rectification_holdout_v2", - "status": "ready", - "valid_public_aa_cases": 20, - "required_cases": 20, - "top_1_rate": 0.7, - "confirmation_coverage_rate": 0.2, - }, - ) - monkeypatch.setattr("scripts.rectification.decision_policy.holdout_passed", lambda holdout=None: True) - decisions = build_candidate_decisions(_rows(), result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt(_request(extra_events=extra), decisions, {"missing_layers": [], "matrix": {}}, _diagnostics()) - apply_vedastro_minute_sensitive_to_receipt(receipt, "passed", summary={"discriminated": True}) - assert receipt["confirmation_allowed"] is True - assert receipt["confirm_allowed"] is True - audit = {row["technique"]: row for row in receipt["technique_audit_table"]} - assert audit["唯一分钟确认"]["status"] == "executed" - - -def test_kp_only_missing_does_not_block_propose_or_engine_grant() -> None: - extra = [{ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "family", - "summary": "家人变化", - "event_kind": "family_event", - "precision": "day", - "date_start": "2020-01-01", - "date_end": "2020-01-01", - }] - decisions = build_candidate_decisions(_rows(), result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt( - _request(extra_events=extra), - decisions, - {"missing_layers": ["KP_cusps"], "matrix": {}}, - _diagnostics(), - ) - assert receipt["gates"]["required_layers"]["passed"] is True - assert receipt["gates"]["required_layers"]["missing_layers"] == [] - assert receipt["gates"]["required_layers"]["skipped_by_policy"] == ["KP_cusps"] - assert receipt["propose_allowed"] is True - assert receipt["gates"]["exact_confirmation"]["engine_granted"] is True - assert "missing_mandatory_layers" not in receipt["confirmation_reasons"] - - -def test_four_events_two_domains_neither_selects_nor_proposes() -> None: - events = [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "summary": "入学", - "event_kind": "education_start", - "precision": "month", - "date_start": "2016-09-01", - "date_end": "2016-09-30", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "education", - "summary": "毕业", - "event_kind": "education_completion", - "precision": "month", - "date_start": "2020-06-01", - "date_end": "2020-06-30", - }, - { - "id": "00000000-0000-4000-8000-000000000003", - "domain": "relationship", - "summary": "相识", - "event_kind": "relationship_start", - "precision": "day", - "date_start": "2024-05-01", - "date_end": "2024-05-01", - }, - { - "id": "00000000-0000-4000-8000-000000000004", - "domain": "relationship", - "summary": "分手", - "event_kind": "relationship_end", - "precision": "day", - "date_start": "2024-08-08", - "date_end": "2024-08-08", - }, - ] - decisions = build_candidate_decisions(_rows(), result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt( - {"events": events}, - decisions, - {"missing_layers": ["KP_cusps"], "matrix": {}}, - { - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 0.5, - "date_sensitivity_retention_rate": 1, - "primary_secondary_margin_percent": 10.27, - }, - ) - # 原值: selection_allowed=True(区间门槛 3 件 2 域,4 件 2 域可选不可提议) - # 新值: selection_allowed=False,domain_diversity 不通过,原因 insufficient_domain_diversity - # 原因: R1 生时校正交付门槛 4 件 3 域(BUG-1193),2 个领域不再给区间 - assert receipt["selection_allowed"] is False - assert receipt["gates"]["event_quality"]["passed"] is True - assert receipt["gates"]["domain_diversity"]["passed"] is False - assert receipt["gates"]["domain_diversity"]["minimum"] == 3 - assert "insufficient_domain_diversity" in receipt["reasons"] - assert receipt["propose_allowed"] is False - assert receipt["gates"]["exact_confirmation"]["engine_granted"] is False - assert "insufficient_confirmation_domains" in receipt["confirmation_reasons"] - assert "insufficient_diagnostic_stability" in receipt["confirmation_reasons"] - - -def test_d9_missing_still_blocks_required_layers() -> None: - extra = [{ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "family", - "summary": "家人变化", - "event_kind": "family_event", - "precision": "day", - "date_start": "2020-01-01", - "date_end": "2020-01-01", - }] - decisions = build_candidate_decisions(_rows(), result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt( - _request(extra_events=extra), - decisions, - {"missing_layers": ["KP_cusps", "D9"], "matrix": {}}, - _diagnostics(), - ) - assert receipt["gates"]["required_layers"]["passed"] is False - assert receipt["gates"]["required_layers"]["missing_layers"] == ["D9"] - assert receipt["propose_allowed"] is False - assert "missing_mandatory_layers" in receipt["confirmation_reasons"] - - -def test_timeout_status_stays_not_evaluated_not_fail() -> None: - decisions = build_candidate_decisions(_rows(), result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt(_request(), decisions, {"missing_layers": [], "matrix": {}}, _diagnostics()) - apply_vedastro_minute_sensitive_to_receipt( - receipt, - "not_evaluated", - summary={"reason": "vedastro_minute_snapshot_timeout"}, - ) - exact = receipt["gates"]["exact_confirmation"] - assert exact["external_validation_status"] == "not_evaluated" - assert exact["external_validation_status"] != "failed" - assert receipt["confirmation_allowed"] is False - note = next(row["note"] for row in receipt["technique_audit_table"] if row["technique"] == "VedAstro 分钟级校验") - assert "不等于失败" in note - - -def test_indistinguishable_width_matches_public_span() -> None: - width = indistinguishable_width_minutes([ - {"time": "04:45", "rank": 1, "tied_minute_count": 25}, - {"time": "04:46", "rank": 2, "tied_minute_count": 25}, - {"time": "04:47", "rank": 3, "tied_minute_count": 25}, - ]) - assert width >= 25 - - -def test_indistinguishable_width_uses_cluster_span_not_representatives() -> None: - width = indistinguishable_width_minutes([ - { - "time": "04:53", - "rank": 1, - "tied_minute_count": 1, - "cluster_start": "04:50", - "cluster_end": "04:55", - }, - { - "time": "04:59", - "rank": 2, - "tied_minute_count": 1, - "cluster_start": "04:56", - "cluster_end": "05:02", - }, - ]) - assert width == 13 - - -def test_fourteen_minute_tied_cluster_proposes_but_does_not_confirm() -> None: - extra = [{ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "family", - "summary": "家人变化", - "event_kind": "family_event", - "precision": "day", - "date_start": "2020-01-01", - "date_end": "2020-01-01", - }] - rows = [ - { - "time": f"{15 + ((50 + offset) // 60):02d}:{(50 + offset) % 60:02d}", - "score": 20, - "evidence": [], - "missing_layers": [], - } - for offset in range(14) - ] - decisions = build_candidate_decisions(rows, result_id="00000000-0000-4000-8000-000000000099") - receipt = build_decision_receipt( - _request(extra_events=extra), - decisions, - {"missing_layers": ["KP_cusps"], "matrix": {}}, - _diagnostics(), - ) - exact = receipt["gates"]["exact_confirmation"] - assert receipt["selection_allowed"] is True - assert receipt["propose_allowed"] is True - assert receipt["gates"]["unique_top"]["passed"] is False - assert exact["indistinguishable_width_minutes"] >= 14 - assert exact["adjacent_passed"] is False - assert exact["engine_granted"] is False - assert receipt["confirmation_allowed"] is False - assert exact["unique_minute_path"] == "closed_at_representative" - assert "adjacent_minutes_indistinguishable" in receipt["confirmation_reasons"] - note = next( - row["note"] - for row in receipt["technique_audit_table"] - if row["technique"] == "唯一分钟确认" - ) - assert "本会话以代表性时间收口" in note diff --git a/tests/test_rectification_cross_midnight_gate.py b/tests/test_rectification_cross_midnight_gate.py deleted file mode 100644 index 6ddcc2332..000000000 --- a/tests/test_rectification_cross_midnight_gate.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Collect candidate-date regressions through quick's test_rectification_*.py glob. - -The re-export deliberately keeps all nine cases inside the quick gate. If both -this bridge and the source file are selected (e.g. the full suite), pytest runs -them twice: eighteen collected items are nine independent cases, not eighteen. -""" - -from tests.test_dasha_transition_proximity_cross_midnight import ( # noqa: F401 - test_every_candidate_uses_own_date_and_caches_do_not_cross_dates, - test_fixed_scoring_identity_is_exposed_without_changing_input_contract, - test_legacy_context_without_candidate_at_retains_request_date, - test_real_cross_midnight_all_candidates_match_independent_dated_calculation, - test_same_day_public_aa_scores_keep_pre_fix_bytes, -) diff --git a/tests/test_rectification_diagnostics_clusters.py b/tests/test_rectification_diagnostics_clusters.py deleted file mode 100644 index b290c6dd1..000000000 --- a/tests/test_rectification_diagnostics_clusters.py +++ /dev/null @@ -1,153 +0,0 @@ -from __future__ import annotations - -import unittest - -from scripts.rectification.diagnostics_service import run_diagnostics - - -def row(time: str, score: float) -> dict: - return {"time": time, "score": score, "evidence": [], "missing_layers": []} - - -def diagnostics(rows: list[dict]) -> dict: - return run_diagnostics({"events": []}, rows, {"date_sensitivity": [], "matrix": {}}) - - -class RectificationDiagnosticsClustersTest(unittest.TestCase): - def test_primary_cluster_joins_adjacent_minutes_across_midnight(self): - result = diagnostics([ - row("23:59", 100), - row("12:00", 98), - row("00:00", 99), - ]) - - self.assertEqual(result["neighbor_support_minutes"], 2) - self.assertEqual(result["candidate_splits"][0]["left_cluster"], { - "start": "23:59", - "end": "00:00", - }) - self.assertEqual(result["candidate_splits"][0]["right_cluster"], { - "start": "12:00", - "end": "12:00", - }) - - def test_primary_cluster_keeps_ordinary_daytime_gaps_separate(self): - result = diagnostics([ - row("05:13", 100), - row("05:14", 99), - row("05:16", 98), - ]) - - self.assertEqual(result["neighbor_support_minutes"], 2) - self.assertEqual(result["candidate_splits"][0]["left_cluster"], { - "start": "05:13", - "end": "05:14", - }) - self.assertEqual(result["candidate_splits"][0]["right_cluster"], { - "start": "05:16", - "end": "05:16", - }) - - def test_candidate_split_reports_actual_candidate_deltas_not_global_activation(self): - stable_event = "00000000-0000-4000-8000-000000000001" - separating_event = "00000000-0000-4000-8000-000000000002" - rows = [ - { - "time": "05:13", "score": 100, "missing_layers": [], - "evidence": [ - {"event_id": stable_event, "domain": "relationship", "candidate_time": "05:13", "rule_ids": ["D9:a"], "points": 50}, - {"event_id": separating_event, "domain": "education", "candidate_time": "05:13", "rule_ids": ["D24:a"], "points": 50}, - ], - }, - { - "time": "05:14", "score": 90, "missing_layers": [], - "evidence": [ - {"event_id": stable_event, "domain": "relationship", "candidate_time": "05:14", "rule_ids": ["D9:b"], "points": 50}, - {"event_id": separating_event, "domain": "education", "candidate_time": "05:14", "rule_ids": ["D24:b"], "points": 40}, - ], - }, - ] - built = { - "date_sensitivity": [], - "static_contexts": [ - {"feature": { - "time": "05:13", - "varga_ascendants": {"D9": 1, "D24": 2}, - "arudha_signs": {}, - "fingerprints": {"ashtakavarga": "same", "shadbala": "same"}, - }}, - {"feature": { - "time": "05:14", - "varga_ascendants": {"D9": 1, "D24": 3}, - "arudha_signs": {}, - "fingerprints": {"ashtakavarga": "same", "shadbala": "same"}, - }}, - ], - "matrix": { - stable_event: { - "05:13": {"points": 50, "technique_layers": ["D9", "D24"]}, - "05:14": {"points": 50, "technique_layers": ["D9", "D24"]}, - }, - separating_event: { - "05:13": {"points": 50, "technique_layers": ["D9", "D24"]}, - "05:14": {"points": 40, "technique_layers": ["D9", "D24"]}, - }, - }, - } - result = run_diagnostics({"events": [{"id": stable_event, "domain": "relationship"}, {"id": separating_event, "domain": "education"}]}, rows, built) - self.assertEqual(result["candidate_splits"][0]["technique_layers"], ["D24"]) - self.assertEqual(result["candidate_splits"][0]["event_ids"], [separating_event]) - - def test_window_scan_reports_d9_diversity_with_sign_names(self): - built = { - "date_sensitivity": [], - "matrix": {}, - "static_contexts": [ - {"feature": {"time": "05:13", "varga_ascendants": {"D9": 1, "D10": 4}}}, - {"feature": {"time": "05:14", "varga_ascendants": {"D9": 7, "D10": 4}}}, - ], - } - result = run_diagnostics({"events": []}, [row("05:13", 100), row("05:14", 90)], built) - scan = result["window_scan"] - self.assertEqual(scan["scanned"], True) - self.assertEqual(scan["confirmation_allowed"], False) - self.assertEqual(scan["unique_minute_claim"], False) - self.assertEqual(scan["d9_lagna_count"], 2) - self.assertEqual(scan["d10_lagna_count"], 1) - self.assertEqual(scan["d9_candidates_differ"], True) - self.assertEqual(scan["d10_candidates_differ"], False) - self.assertEqual(scan["transitions"], [{ - "layer": "d9", - "at": "05:14", - "user_meaning": "D9 在 05:14 发生变化", - "from_sign": "金牛座", - "to_sign": "天蝎座", - }]) - encoded = str(scan) - self.assertIn("金牛座", encoded) - self.assertIn("天蝎座", encoded) - self.assertNotIn("Aries", encoded) - self.assertNotIn("Scorpio", encoded) - self.assertFalse(scan["unique_minute_claim"]) - - def test_staging_quick_gate_runs_rectification_python_suite(self) -> None: - from pathlib import Path - - from scripts.run_quality_gate import CORE_PYTEST_TARGETS, _expand_pytest_targets - - glob_target = "tests/test_rectification_*.py" - text = Path("scripts/run_quality_gate.py").read_text(encoding="utf-8") - self.assertIn(f'"{glob_target}"', text) - self.assertIn(glob_target, CORE_PYTEST_TARGETS) - expanded = _expand_pytest_targets([glob_target]) - self.assertGreaterEqual(len(expanded), 6) - self.assertTrue(all( - item.startswith("tests/test_rectification_") and item.endswith(".py") - for item in expanded - )) - with self.assertRaises(SystemExit): - _expand_pytest_targets(["tests/no_such_rectification_glob_*.py"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rectification_engine_convergence.py b/tests/test_rectification_engine_convergence.py deleted file mode 100644 index 16ddb1c37..000000000 --- a/tests/test_rectification_engine_convergence.py +++ /dev/null @@ -1,420 +0,0 @@ -"""Round 2 engine-convergence invariants (TASK-rectification-engine-convergence-20260901).""" - -from __future__ import annotations - -import unittest -from datetime import date, datetime -from pathlib import Path - -from scripts.rectification.candidate_contrast import distinguish_contract_errors -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.event_probes import ( - _apply_prior_ranking, - _dominant_existence_prior, - _partition_ranked_probes, - _vim_start_dates, - discriminating_event_probes, - event_clarification_probes, -) -from scripts.rectification.refinement_packet import build_refinement_packet, window_scan -from scripts.rectification.scoring_service import build_event_contribution_matrix - -REPO_ROOT = Path(__file__).resolve().parents[1] -PLANETS = { - "Sun": 12.0, - "Moon": 100.0, - "Mars": 40.0, - "Mercury": 20.0, - "Jupiter": 80.0, - "Venus": 50.0, - "Saturn": 200.0, - "Rahu": 310.0, - "Ketu": 130.0, -} -GRID_TIMES = [ - f"{4 + (45 + offset) // 60:02d}:{(45 + offset) % 60:02d}" - for offset in range(31) -] -SPLIT_EVENT_ID = "00000000-0000-4000-8000-000000000003" - - -def _varga(asc: int, planet_sign: int) -> dict: - return { - "Ascendant": {"sign_idx": asc}, - **{name: {"sign_idx": planet_sign} for name in PLANETS}, - } - - -def _context( - time: str, - *, - moon: float = 100.0, - d4_asc: int = 1, - d9_asc: int = 1, - d10_asc: int = 1, - d12_asc: int = 1, - d24_asc: int = 1, - sun_house: int = 10, -) -> dict: - hour, minute = (int(part) for part in time.split(":")) - planets = {**PLANETS, "Moon": moon} - natal_planets = { - name: {"house": sun_house if name != "Moon" else 4, "lon": lon} - for name, lon in planets.items() - } - return { - "candidate_at": datetime(1997, 8, 8, hour, minute), - "chart": {"ascendant": {"lon": 10.0, "sign": "Aries"}, "planets": natal_planets}, - "planet_longitudes": dict(planets), - "ascendant_index": 0, - "varga_charts": { - "D4": _varga(d4_asc, 1), - "D9": _varga(d9_asc, 1), - "D10": _varga(d10_asc, 1), - "D5": _varga(1, 1), - "D24": _varga(d24_asc, 1), - "D12": _varga(d12_asc, 1), - "D7": _varga(1, 1), - "D3": _varga(1, 1), - }, - "arudha_padas": {}, - "feature": { - "time": time, - "ascendant_sign_index": 0, - "varga_ascendants": { - "D4": d4_asc, "D9": d9_asc, "D10": d10_asc, "D5": 1, "D24": d24_asc, "D12": d12_asc, - }, - }, - } - - -def _accident_events() -> list[dict]: - return [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_start", - "date_start": "2016-01-01", - "date_end": "2016-12-31", - "precision": "year", - "summary": "上大学", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "relationship", - "event_kind": "relationship_start", - "date_start": "2024-05-01", - "date_end": "2024-05-31", - "precision": "month", - "summary": "开始认真交往", - }, - { - "id": SPLIT_EVENT_ID, - "domain": "relationship", - "event_kind": "relationship_end", - "date_start": "2024-08-08", - "date_end": "2024-08-08", - "precision": "day", - "summary": "分手", - }, - { - "id": "00000000-0000-4000-8000-000000000004", - "domain": "career", - "event_kind": "career_entry", - "date_start": "2020-04-01", - "date_end": "2020-04-30", - "precision": "month", - "summary": "实习入职", - }, - { - "id": "00000000-0000-4000-8000-000000000005", - "domain": "career", - "event_kind": "career_exit", - "date_start": "2020-10-01", - "date_end": "2020-10-31", - "precision": "month", - "summary": "实习结束离职", - }, - ] - - -def _accident_request() -> dict: - return normalize_rectification_request( - { - "birth_date": "1997-08-08", - "start_time": "04:45", - "end_time": "05:15", - "lat": 36.420487, - "lon": 114.209936, - "tz": 8, - "events": _accident_events(), - }, - today=date(2026, 8, 22), - ) - - -def _equal_rows(payload: dict) -> list[dict]: - event = payload["events"][0] - return [ - { - "time": time, - "score": 10, - "evidence": [{ - "event_id": event["id"], - "domain": event["domain"], - "candidate_time": time, - "rule_ids": ["vim_md_domain_house"], - "points": 10, - }], - "missing_layers": [], - } - for time in GRID_TIMES - ] - - -def _moons_with_split_proximity() -> tuple[float, float]: - event_at = date(2024, 8, 8) - ranked: list[tuple[int, float]] = [] - for moon in (100.0, 100.5, 101.0, 103.0, 110.0): - starts = _vim_start_dates("1997-08-08", moon, 2023, 2025) - if not starts: - continue - nearest = min(abs((item - event_at).days) for item in starts) - ranked.append((nearest, moon)) - ranked.sort() - if len(ranked) < 2 or ranked[0][0] == ranked[-1][0]: - raise AssertionError("fixture moons do not split AD/PD proximity") - return ranked[0][1], ranked[-1][1] - - -def _probe_events(*, education_count: int = 2, d24_split: bool = True) -> tuple[dict, dict]: - events = [ - { - "id": f"00000000-0000-4000-8000-{index:012d}", - "domain": "education", - "event_kind": "education_start", - "summary": "入学", - "date": f"{2015 + index}-09-01", - "precision": "month", - } - for index in range(1, education_count + 1) - ] - events.extend([ - { - "id": "00000000-0000-4000-8000-000000000011", - "domain": "career", - "event_kind": "career_entry", - "summary": "入职", - "date": "2018-07-01", - "precision": "month", - }, - { - "id": "00000000-0000-4000-8000-000000000012", - "domain": "career", - "event_kind": "career_change", - "summary": "换岗", - "date": "2020-04-01", - "precision": "month", - }, - { - "id": "00000000-0000-4000-8000-000000000013", - "domain": "relationship", - "event_kind": "relationship_start", - "summary": "相识", - "date": "2021-08-01", - "precision": "month", - }, - ]) - late = 2 if d24_split else 1 - built = { - "static_contexts": [ - _context("05:00", d24_asc=1, d12_asc=1, d9_asc=1, d10_asc=1), - _context("05:07", d24_asc=late, d12_asc=late, d9_asc=late, d10_asc=late), - ] - } - return {"birth_date": "1997-08-08", "events": events}, built - - -class EngineConvergenceProximityTests(unittest.TestCase): - def test_day_event_proximity_splits_adjacent_minutes_in_accident_shape(self) -> None: - from scripts.rectification.dasha_transition_proximity import ( - DAY_MAX_POINTS, - score_transition_proximity, - ) - - closer_moon, farther_moon = _moons_with_split_proximity() - event_at = date(2024, 8, 8) - closer_starts = _vim_start_dates("1997-08-08", closer_moon, 2023, 2025) - farther_starts = _vim_start_dates("1997-08-08", farther_moon, 2023, 2025) - closer_delta = min(abs((item - event_at).days) for item in closer_starts) - farther_delta = min(abs((item - event_at).days) for item in farther_starts) - closer_points = score_transition_proximity( - event_date=event_at, - precision="day", - vim_starts=closer_starts, - narayana_starts=[], - ) - farther_points = score_transition_proximity( - event_date=event_at, - precision="day", - vim_starts=farther_starts, - narayana_starts=[], - ) - self.assertLessEqual(float(closer_points["points"]), DAY_MAX_POINTS) - self.assertNotEqual(closer_points["points"], farther_points["points"]) - self.assertEqual( - closer_points["points"] > farther_points["points"], - closer_delta < farther_delta, - ) - self.assertTrue( - any(str(rule).startswith("vim_transition_proximity_") for rule in closer_points["rule_ids"]) - ) - - contexts = [ - _context(time, moon=closer_moon if time == "05:00" else farther_moon) - for time in GRID_TIMES - ] - request = _accident_request() - built = build_event_contribution_matrix( - request, - row_provider=_equal_rows, - static_contexts=contexts, - ) - self.assertEqual(len(built["candidate_times"]), 31) - cell_0500 = built["matrix"][SPLIT_EVENT_ID]["05:00"] - cell_0507 = built["matrix"][SPLIT_EVENT_ID]["05:07"] - self.assertNotEqual(cell_0500["points"], cell_0507["points"]) - self.assertEqual( - cell_0500["points"] > cell_0507["points"], - closer_delta < farther_delta, - ) - self.assertTrue( - any("transition_proximity" in str(rule) for rule in cell_0500["rule_ids"]) - or any("transition_proximity" in str(rule) for rule in cell_0507["rule_ids"]) - ) - self.assertLessEqual(abs(cell_0500["points"] - cell_0507["points"]), DAY_MAX_POINTS) - - def test_algorithm_and_policy_versions_change_with_proximity_semantics(self) -> None: - from scripts.rectification.decision_policy import POLICY_VERSION - from scripts.rectification.scoring_service import ALGORITHM_VERSION - - self.assertNotEqual(ALGORITHM_VERSION, "rectification-v5-matrix-scoring-6") - self.assertNotEqual(POLICY_VERSION, "rectification-candidate-policy-v2") - - -class EngineConvergenceProbeTests(unittest.TestCase): - def test_anchored_quality_outranks_family_existence_and_drops_dominant_priors(self) -> None: - request, built = _probe_events() - probes = discriminating_event_probes( - request, - built, - scan=window_scan(built), - candidate_times=["05:00", "05:07"], - representative_time="05:00", - today=date(2026, 8, 22), - ) - quality = [item for item in probes if item.get("source") == "known_event_quality"] - self.assertTrue(quality) - self.assertEqual(quality[0]["role"], "distinguish") - self.assertTrue(quality[0].get("target_evidence_id")) - self.assertFalse(distinguish_contract_errors(quality[0])) - ranked_family = _apply_prior_ranking({ - "domain": "family", - "source": "dasha_boundary", - "choice_kind": "existence", - "information_gain": float(quality[0].get("raw_split_gain") or quality[0].get("information_gain") or 0), - "semantic_key": "family.2024.existence", - "year": 2024, - "window_span_years": 3, - "role": "distinguish", - "phase": "candidate_discriminator", - "candidate_ids": ["05:00", "05:07"], - "expected_outcomes": [ - {"answer_class": "yes", "supports": ["05:00"], "conflicts": ["05:07"]}, - {"answer_class": "no", "supports": ["05:07"], "conflicts": ["05:00"]}, - ], - }) - self.assertTrue(_dominant_existence_prior(ranked_family, ranked_family["answer_priors"])) - _, ranked_dropped = _partition_ranked_probes([quality[0], ranked_family]) - self.assertTrue( - any(item.get("reason") == "dominant_answer_prior" for item in ranked_dropped), - ranked_dropped, - ) - packet = build_refinement_packet( - request, - built, - representative_time="05:00", - candidate_times=["05:00", "05:07"], - ) - dropped = list(packet.get("dropped_probes") or []) + ranked_dropped - self.assertTrue( - any(item.get("reason") == "dominant_answer_prior" for item in dropped), - dropped, - ) - self.assertFalse( - any( - item.get("choice_kind") == "existence" - and float(max((item.get("answer_priors") or {}).values() or [0])) > 0.8 - for item in probes - ) - ) - - def test_quality_distinguish_requires_varga_type_split_and_caps_at_two(self) -> None: - same_request, same_built = _probe_events(d24_split=False) - same_probes = discriminating_event_probes( - same_request, - same_built, - scan=window_scan(same_built), - candidate_times=["05:00", "05:07"], - representative_time="05:00", - today=date(2026, 8, 22), - ) - self.assertFalse(any(item.get("source") == "known_event_quality" for item in same_probes)) - clarification = event_clarification_probes(same_request) - self.assertTrue(any(item.get("source") == "known_event_quality" for item in clarification)) - - split_request, split_built = _probe_events(education_count=4, d24_split=True) - split_probes = discriminating_event_probes( - split_request, - split_built, - scan=window_scan(split_built), - candidate_times=["05:00", "05:07"], - representative_time="05:00", - today=date(2026, 8, 22), - ) - quality = [item for item in split_probes if item.get("source") == "known_event_quality"] - self.assertTrue(quality) - self.assertLessEqual(len(quality), 2) - for item in quality: - self.assertEqual(item["role"], "distinguish") - self.assertTrue(item.get("target_evidence_id")) - self.assertTrue(item.get("display_date_label")) - self.assertEqual(item.get("choice_kind"), "event_quality") - self.assertFalse(distinguish_contract_errors(item)) - - -class EngineConvergenceAnswerKeyTests(unittest.TestCase): - def test_scripts_and_frontend_have_no_answer_key_literals(self) -> None: - forbidden = ("target" + "_minute", "pl9_" + "1993", "regression" + "_only") - hits: list[str] = [] - roots = ( - REPO_ROOT / "scripts", - REPO_ROOT / "frontend" / "src", - REPO_ROOT / "frontend" / "tests", - ) - skip_parts = {"node_modules", ".next", "dist"} - for root in roots: - for path in root.rglob("*"): - if not path.is_file() or path.suffix not in {".py", ".ts", ".tsx", ".js", ".mjs"}: - continue - if any(part in skip_parts for part in path.parts): - continue - text = path.read_text(encoding="utf-8", errors="ignore") - for token in forbidden: - if token in text: - hits.append(f"{path.relative_to(REPO_ROOT)}:{token}") - self.assertEqual(hits, []) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rectification_engine_memoization.py b/tests/test_rectification_engine_memoization.py deleted file mode 100644 index ad9f4d47f..000000000 --- a/tests/test_rectification_engine_memoization.py +++ /dev/null @@ -1,800 +0,0 @@ -"""Memoization for candidate-minute invariants in the rectification engine. - -Historical golden tests/golden/rectification_engine_memoization_v1.json was -produced from origin/staging @ a8d29d1b before any memoization landed. -On 2026-09-20 only two identity leaves were refreshed from the real engine: -representative_candidate_id 85ca5490-07ab-54b7-acf0-59385f705015 -> -e8c11277-022c-519c-95e9-6a0a04e8bf23, and snapshot algorithm_version -rectification-v5-matrix-scoring-7 -> rectification-v5-matrix-scoring-8. -The authorized cross-midnight version bump changes UUID identity, not this -same-day fixture's scores. Historical numeric values and feature hashes remain. -That file is now frozen (sha256 pinned below) and no longer the comparison -target: scoring-8/9 scores belong to the old functional benefic / malefic -grouping. - -Current golden tests/golden/rectification_engine_memoization_v2.json -(2026-10-02, BUG-1181) was written by ``write_golden`` from the real engine at -57782aea (functional profile bphs_ch34_general_with_sign_exceptions_v2) with -ALGORITHM_VERSION rectification-v5-matrix-scoring-10. Scores move for the same -input (candidate 12:00: 8.6274 -> 8.4977), which is why the algorithm identity -was bumped; it already carries the dated-v1 receipt metadata. Never rewrite it -in place: a future scoring change adds a v3 file and freezes this one. - -Current golden tests/golden/rectification_engine_memoization_v3.json -(2026-10-02, BUG-1193, upstream sync 5) was written by ``write_golden`` after -R1 raised the range floor to 4 dated events / 3 domains. Candidate scores are -identical to v2 (the ported combustion / Chara Karaka / Yogini / Shodhana -changes do not feed the event matrix; 77 v5 cases A/B byte-identical), so the -algorithm stays scoring-10. Only the decision receipt moved: policy -rectification-candidate-policy-v3 -> v4, event_quality / domain_diversity -minimum 3/2 -> 4/3, and the representative candidate UUID (its namespace -carries the policy version). v2 is frozen by sha256 below. - -Golden tests/golden/rectification_engine_memoization_v4.json -(2026-10-07, BUG-1260) was written by ``write_golden`` after the D5/D11 -mappings changed education and finance varga points for this same request. -The algorithm is rectification-v5-matrix-scoring-11. Policy stays v4. -v3 stays byte-for-byte and is pinned below. v4 is now frozen the same way. - -Golden tests/golden/rectification_engine_memoization_v5.json -(2026-10-08, BUG-1275) was written by ``write_golden`` after sidereal -longitudes included nutation. The same request moves (12:00 8.5289 -> 8.5336). -The algorithm is rectification-v5-matrix-scoring-12. Policy stays v4. -v4 stays byte-for-byte and is pinned below. v5 is now frozen the same way. - -Golden tests/golden/rectification_engine_memoization_v6.json -(2026-11-04, BUG-1560 / BUG-1570, product decision) was written by -``write_golden`` after varga.py's even-sign D30 followed BPHS ch. 6 and Venus -became a functional malefic for Aries / Scorpio. This request's candidate -scores are unchanged (12:00 8.5336, 12:01 8.5242, 12:02 8.088; the chart is -not Aries / Scorpio rising), but the D30 feature (Capricorn -> Pisces), its -window transition and the feature hashes moved; other inputs score -differently, hence rectification-v5-matrix-scoring-13. Policy stays v4. v5 -stays byte-for-byte and is pinned below. v6 is now frozen the same way. - -Golden tests/golden/rectification_engine_memoization_v7.json -(2026-11-04, #166 astrologer rulings, BUG-1583..1588, product decision) was -written by ``write_golden`` after Shadbala Sthana / Drik followed the named -BPHS version (Saptavargaja values, Moolatrikona 3 / 15 deg, whole-sign -Kendradi, BPHS 26 special aspects, Mercury with any malefic) and the -jaimini.py Arudha 1/7 exception counted from the first-count pada. Both feed -the rectification score, hence rectification-v5-matrix-scoring-14. Policy -stays v4. v6 stays byte-for-byte and is pinned below. v7 is now frozen the same way. - -Current golden tests/golden/rectification_engine_memoization_v8.json -(2026-11-04, #166 batch 2, BUG-1590) was written by ``write_golden`` after -the functional roles made Gemini Saturn (8, 9) and Virgo Saturn (5, 6) mixed, -which the *_functional_* rules read; hence rectification-v5-matrix-scoring-15. -Policy stays v4. v7 stays byte-for-byte and is pinned below. - -Do not compare that payload with a whole-structure ``==``. Cross-machine -libm / pyswisseph rounding already drifted ``margin_percent`` by 1.1e-3 -(TASK-rectification-engine-memoization-fix-20260915). Equivalence of the -four cached layers is proven in-process instead. -""" - -from __future__ import annotations - -import hashlib -import inspect -import json -import math -from datetime import date, datetime -from pathlib import Path -from typing import Any -from unittest.mock import patch -from uuid import NAMESPACE_URL, uuid5 - -import pytest - -from scripts.active_rectification_event_engine import ( - _candidate_datetimes, - _controlled_transit_rules, - _shadbala_verified_components_auxiliary, - build_candidate_static_context, - compute_event_candidate_rows, -) -from scripts.rectification.api_service import score_candidates -from scripts.rectification.candidate_contrast import opportunity_from_probe -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.refinement_packet import build_refinement_packet -from scripts.rectification.scoring_service import sample_event_dates, scoreable_request -import scripts.active_rectification_event_engine as event_engine -import scripts.rectification.event_probes as event_probes -import scripts.rectification.scoring_service as scoring_service -import shadbala - -ROOT = Path(__file__).resolve().parents[1] -GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v8.json" -V7_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v7.json" -V7_GOLDEN_SHA256 = "708e084b4401fd2f516e15224ef794ac4a037b67e40e534473b5c701e8008626" -V7_SOURCE_COMMIT = "78f98eba93034ad3de8ea348c53f9e4b02241d4c" -V6_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v6.json" -V6_GOLDEN_SHA256 = "f8d63b807293464eb20585ecf8c2408f0cbf310bad4bf71f3e61671eac0e1f4b" -V6_SOURCE_COMMIT = "18c685c428a06f4530e43218588c03ca9ce1dea3" -V5_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v5.json" -V5_GOLDEN_SHA256 = "92efd8fdbae43f553b0006cfe28e929d5255fe02f3c36e616475fa149a356212" -V5_SOURCE_COMMIT = "e5f2a75183381c4a027014c7f1e89ddcb8393bd3" -V4_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v4.json" -V4_GOLDEN_SHA256 = "8491093281fe9767defea1b46d325237f1a4c6c0d4f076b9a77f07b985b526c3" -V4_SOURCE_COMMIT = "db68e90816d462b0c17b4f84a0d19df83010fbce" -V3_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v3.json" -V3_GOLDEN_SHA256 = "7064f30bea3a7bcd8058fdcb6b52484a96a09767c0c289e0d71f3e2368fc8d45" -V3_SOURCE_COMMIT = "7fb165ecf66ba1726f2fc74ffa2353fadc65ba39" -PREVIOUS_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v2.json" -PREVIOUS_GOLDEN_SHA256 = "abb15efae4d86387d930cd463b82a22fe95ccd1779e85ca6cc4cdf07a063cb73" -PREVIOUS_SOURCE_COMMIT = "57782aea8ae28f5dd165a08d221ec27dbef391f8" -HISTORICAL_GOLDEN_PATH = ROOT / "tests" / "golden" / "rectification_engine_memoization_v1.json" -HISTORICAL_GOLDEN_SHA256 = "6266e448d7dad204b264cbe8f9bcf4c36e02286794764a94edb9e2ce4d0e3015" -# 原值: rectification-v5-matrix-scoring-11;新值: ...-scoring-12;原因: 章动修正改变同输入分数(BUG-1275)。 -# 原值: rectification-v5-matrix-scoring-12;新值: ...-scoring-13;原因: D30 偶数星座与白羊 / 天蝎金星功能凶改变同输入分数(BUG-1560 / BUG-1570)。 -# 原值: rectification-v5-matrix-scoring-13;新值: ...-scoring-14;原因: #166 占星师裁定改了 Shadbala Sthana / Drik 与 jaimini.py Arudha 例外,同输入分数变(BUG-1583~1588)。 -# 原值: ...-scoring-14;新值: ...-scoring-15;原因: #166 第二批(第 4 条:双子 / 处女上升土星改为混合,BUG-1590)改变同输入分数。 -CURRENT_ALGORITHM_VERSION = "rectification-v5-matrix-scoring-15" -FROZEN_TODAY = date(2026, 9, 16) -TIMING_KEYS = frozenset({"column_compare_ms"}) -HISTORICAL_SOURCE_COMMIT = "a8d29d1b6cc37ff865ddec6c8bccdf9aa889ee53" -CURRENT_POLICY_VERSION = "rectification-candidate-policy-v4" -# #166 batch 2 commit that moves these scores (BUG-1590). v7 keeps V7_SOURCE_COMMIT. -SOURCE_COMMIT = "4b223eb8eaf28db7c22364b50c17af7941c1d606" -# 原值: 4 个缓存键(ashtakavarga / shadbala / vimshottari / narayana_periods) -# 新值: 再加 functional_profile、narayana_antardasha_by_md,共 6 个 -# 原因: BUG-1324。这两项只依赖候选分钟,放在静态上下文顶层;置 None 仍现算,输出应相同 -CACHE_LAYER_KEYS = ( - "ashtakavarga_result", - "shadbala_result", - "vimshottari_timeline", - "narayana_periods", - "functional_profile", - "narayana_antardasha_by_md", -) -# TASK-rectification-engine-memoization-fix-20260915 §2 measured max -# cross-machine drift of 1.1e-3 on decision_receipt.margin_percent -# (5.2995 vs golden 5.3006). Candidate scores, already rounded to 4 -# decimals, drifted by 1 ulp (1.0e-4). Tolerance is the wider of -# abs=2e-3 and rel=5e-4 so 1.1e-3 still passes while a 1e-2 mutation -# (the reverse test below) fails. -GOLDEN_FLOAT_ABS = 2e-3 -GOLDEN_FLOAT_REL = 5e-4 - - -def public_score_request() -> dict[str, Any]: - """Fictional events on the public 1990-01-01 Beijing smoke chart.""" - return { - "birth_date": "1990-01-01", - "start_time": "12:00", - "end_time": "12:02", - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_start", - "date_start": "2008-01-01", - "date_end": "2008-12-31", - "precision": "year", - "summary": "入学", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "career", - "event_kind": "career_entry", - "date_start": "2012-06-01", - "date_end": "2012-06-30", - "precision": "month", - "summary": "入职", - }, - ], - } - - -def _strip_timing(value: Any) -> Any: - if isinstance(value, dict): - return { - key: _strip_timing(item) - for key, item in value.items() - if key not in TIMING_KEYS - } - if isinstance(value, list): - return [_strip_timing(item) for item in value] - return value - - -def _normalized_request() -> dict[str, Any]: - return normalize_rectification_request(public_score_request(), today=FROZEN_TODAY) - - -class _FrozenDate(date): - """`event_probes` reads `date.today()` for its year windows; the golden - must not depend on the wall clock (BUG-733 family).""" - - @classmethod - def today(cls) -> date: - return FROZEN_TODAY - - -def _golden_payload() -> dict[str, Any]: - with patch.object(event_probes, "date", _FrozenDate): - scored = score_candidates(_normalized_request()) - return { - "source_commit": SOURCE_COMMIT, - "candidate_scores": scored["candidate_scores"], - "decision_receipt": _strip_timing(scored["decision_receipt"]), - "candidate_feature_snapshot": scored["candidate_feature_snapshot"], - } - - -def write_golden(path: Path = GOLDEN_PATH) -> Path: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(_golden_payload(), ensure_ascii=True, indent=2) + "\n", encoding="utf-8") - return path - - -def _count_calls(monkeypatch, owner: Any, name: str, *, from_engine: bool = False) -> list[int]: - original = getattr(owner, name) - counter = [0] - - def wrapped(*args: Any, **kwargs: Any) -> Any: - if from_engine: - caller = inspect.stack()[1].filename.replace("\\", "/") - if not caller.endswith("/active_rectification_event_engine.py"): - return original(*args, **kwargs) - counter[0] += 1 - return original(*args, **kwargs) - - monkeypatch.setattr(owner, name, wrapped) - return counter - - -def _is_json_number(value: Any) -> bool: - return isinstance(value, (int, float)) and not isinstance(value, bool) - - -def _assert_tiered_equal(actual: Any, expected: Any, *, path: str) -> None: - if isinstance(expected, dict): - assert isinstance(actual, dict), path - assert set(actual) == set(expected), f"{path} keys {set(actual)!r} != {set(expected)!r}" - for key in expected: - _assert_tiered_equal(actual[key], expected[key], path=f"{path}.{key}") - return - if isinstance(expected, list): - assert isinstance(actual, list), path - assert len(actual) == len(expected), f"{path} length {len(actual)} != {len(expected)}" - for index, (left, right) in enumerate(zip(actual, expected)): - _assert_tiered_equal(left, right, path=f"{path}[{index}]") - return - if isinstance(expected, int) and isinstance(actual, int) and not isinstance(expected, bool) and not isinstance(actual, bool): - assert actual == expected, f"{path}: {actual!r} != {expected!r}" - return - if _is_json_number(expected) or _is_json_number(actual): - left = float(actual) - right = float(expected) - tolerance = max(GOLDEN_FLOAT_ABS, GOLDEN_FLOAT_REL * abs(right)) - assert math.isclose(left, right, rel_tol=0.0, abs_tol=tolerance), ( - f"{path}: {left!r} vs {right!r} exceeds {tolerance}" - ) - return - assert actual == expected, f"{path}: {actual!r} != {expected!r}" - - -def _assert_memoization_payloads(actual: dict[str, Any], expected: dict[str, Any]) -> None: - _assert_tiered_equal(actual["candidate_scores"], expected["candidate_scores"], path="candidate_scores") - _assert_tiered_equal(actual["decision_receipt"], expected["decision_receipt"], path="decision_receipt") - - -def _event_engine_request() -> dict[str, Any]: - """Dated events for compute_event_candidate_rows (not the v5 score payload).""" - return { - "birth_date": "1990-01-01", - "start_time": "12:00", - "end_time": "12:02", - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_start", - "date": "2008-07-01", - "precision": "day", - "summary": "入学", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "career", - "event_kind": "career_entry", - "date": "2012-06-15", - "precision": "day", - "summary": "入职", - }, - ], - } - - -def _contexts_with_layer_cache_cleared(contexts: list[dict[str, Any]]) -> list[dict[str, Any]]: - cleared: list[dict[str, Any]] = [] - for context in contexts: - clone = dict(context) - for key in CACHE_LAYER_KEYS: - clone[key] = None - cleared.append(clone) - return cleared - - -def _assert_dated_payload_against_golden(actual: dict[str, Any], expected: dict[str, Any]) -> None: - """Compare with the scoring-15 / policy-v4 golden; identity is spelled out, not trusted.""" - metadata = { - "candidate_window_contract": "dated-v1", - "candidate_intervals": [{"start_at": "1990-01-01T12:00", "end_at": "1990-01-01T12:02"}], - "candidate_timezone_offset": 8, - "candidate_timezone_id": "", - } - receipt = actual["decision_receipt"] - golden_receipt = expected["decision_receipt"] - assert set(receipt) == set(golden_receipt), f"receipt keys {set(receipt) ^ set(golden_receipt)!r}" - for key, value in metadata.items(): - assert receipt[key] == value, key - assert golden_receipt[key] == value, key - assert expected["candidate_feature_snapshot"]["algorithm_version"] == CURRENT_ALGORITHM_VERSION - assert actual["candidate_feature_snapshot"]["algorithm_version"] == CURRENT_ALGORITHM_VERSION - # Independently spell out the result/candidate UUID namespace formula. Do not - # call the production identity helper or accept any arbitrary UUID string. - identity_request = { - key: value for key, value in _normalized_request().items() - if key not in {"asked_probe_keys", "dropped_asked_probe_keys", "declined_domains", "column_times", "refresh_probes"} - } - fingerprint = hashlib.sha256(json.dumps( - identity_request, ensure_ascii=True, sort_keys=True, separators=(",", ":"), - ).encode()).hexdigest() - result_id = uuid5(NAMESPACE_URL, f"{CURRENT_ALGORITHM_VERSION}:{fingerprint}") - representative_time = golden_receipt["representative_time"] - candidate_id = uuid5(NAMESPACE_URL, f"{CURRENT_POLICY_VERSION}:{result_id}:{representative_time}") - assert golden_receipt["representative_candidate_id"] == str(candidate_id) - assert receipt["representative_candidate_id"] == str(candidate_id) - # BUG-733/985: fingerprints hash unrounded floats; do not turn the - # snapshot into a cross-process exact-hash contract. - _assert_memoization_payloads(actual, expected) - - -def test_historical_scoring_8_golden_is_frozen_and_no_longer_current() -> None: - """BUG-1181: the scoring-8 golden stays byte-identical and is not the current payload.""" - raw = HISTORICAL_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == HISTORICAL_GOLDEN_SHA256 - historical = json.loads(raw) - assert historical["source_commit"] == HISTORICAL_SOURCE_COMMIT - assert historical["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-8" - current = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - assert current["source_commit"] == SOURCE_COMMIT - with pytest.raises(AssertionError): - _assert_memoization_payloads(current, historical) - - -def test_previous_policy_v3_golden_is_frozen_with_identical_scores() -> None: - """BUG-1193: v2 stays byte-identical; scores equal v3 (both scoring-10), only the receipt policy moved.""" - raw = PREVIOUS_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == PREVIOUS_GOLDEN_SHA256 - previous = json.loads(raw) - current = json.loads(V3_GOLDEN_PATH.read_text(encoding="utf-8")) - assert previous["source_commit"] == PREVIOUS_SOURCE_COMMIT - # 原值: 与 CURRENT_ALGORITHM_VERSION 相同;新值: 两者都是 scoring-10;原因: 当前身份已是 scoring-11,v2/v3 仍是当时的 scoring-10。 - assert previous["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-10" - assert current["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-10" - _assert_tiered_equal(current["candidate_scores"], previous["candidate_scores"], path="candidate_scores") - assert previous["decision_receipt"]["policy_version"] == "rectification-candidate-policy-v3" - assert current["decision_receipt"]["policy_version"] == CURRENT_POLICY_VERSION - assert previous["decision_receipt"]["gates"]["event_quality"]["minimum"] == 3 - assert current["decision_receipt"]["gates"]["event_quality"]["minimum"] == 4 - assert previous["decision_receipt"]["gates"]["domain_diversity"]["minimum"] == 2 - assert current["decision_receipt"]["gates"]["domain_diversity"]["minimum"] == 3 - with pytest.raises(AssertionError): - _assert_memoization_payloads(current, previous) - - -def test_scoring_10_golden_is_frozen_and_scores_moved() -> None: - """BUG-1260: v3 stays byte-identical; D5/D11 moved this request, hence scoring-11.""" - raw = V3_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == V3_GOLDEN_SHA256 - previous = json.loads(raw) - scoring11 = json.loads(V4_GOLDEN_PATH.read_text(encoding="utf-8")) - assert previous["source_commit"] == V3_SOURCE_COMMIT - assert previous["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-10" - assert scoring11["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-11" - assert scoring11["source_commit"] == V4_SOURCE_COMMIT - with pytest.raises(AssertionError): - _assert_memoization_payloads(scoring11, previous) - - -def test_scoring_11_golden_is_frozen_and_scores_moved() -> None: - """BUG-1275: v4 stays byte-identical; nutation moved this request, hence scoring-12.""" - raw = V4_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == V4_GOLDEN_SHA256 - previous = json.loads(raw) - scoring12 = json.loads(V5_GOLDEN_PATH.read_text(encoding="utf-8")) - assert previous["source_commit"] == V4_SOURCE_COMMIT - assert previous["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-11" - assert scoring12["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-12" - assert scoring12["source_commit"] == V5_SOURCE_COMMIT - with pytest.raises(AssertionError): - _assert_memoization_payloads(scoring12, previous) - - -def test_scoring_12_golden_is_frozen_and_scores_moved() -> None: - """BUG-1560 / BUG-1570: v5 stays byte-identical; the D30 feature of this request moved, hence scoring-13.""" - raw = V5_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == V5_GOLDEN_SHA256 - previous = json.loads(raw) - current = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - assert previous["source_commit"] == V5_SOURCE_COMMIT - assert previous["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-12" - assert current["candidate_feature_snapshot"]["algorithm_version"] == CURRENT_ALGORITHM_VERSION - assert current["source_commit"] == SOURCE_COMMIT - with pytest.raises(AssertionError): - _assert_memoization_payloads(current, previous) - - -def test_scoring_13_golden_is_frozen_and_scores_moved() -> None: - """#166 (BUG-1583..1588): v6 stays byte-identical; this request moved, hence scoring-14.""" - raw = V6_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == V6_GOLDEN_SHA256 - previous = json.loads(raw) - current = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - assert previous["source_commit"] == V6_SOURCE_COMMIT - assert previous["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-13" - assert current["candidate_feature_snapshot"]["algorithm_version"] == CURRENT_ALGORITHM_VERSION - assert current["source_commit"] == SOURCE_COMMIT - with pytest.raises(AssertionError): - _assert_memoization_payloads(current, previous) - - -def test_scoring_14_golden_is_frozen() -> None: - """#166 batch 2 (BUG-1590): v7 stays byte-identical; the identity moved to scoring-15.""" - raw = V7_GOLDEN_PATH.read_bytes() - assert hashlib.sha256(raw).hexdigest() == V7_GOLDEN_SHA256 - previous = json.loads(raw) - current = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - assert previous["source_commit"] == V7_SOURCE_COMMIT - assert previous["candidate_feature_snapshot"]["algorithm_version"] == "rectification-v5-matrix-scoring-14" - assert current["candidate_feature_snapshot"]["algorithm_version"] == CURRENT_ALGORITHM_VERSION - assert current["source_commit"] == SOURCE_COMMIT - - -def test_score_candidates_matches_baseline_golden() -> None: - expected = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - actual = json.loads(json.dumps(_golden_payload(), ensure_ascii=True)) - _assert_dated_payload_against_golden(actual, expected) - - -@pytest.mark.parametrize("field,value", [ - ("candidate_window_contract", "dated-v0"), - ("candidate_intervals", [{"start_at": "1990-01-02T12:00", "end_at": "1990-01-02T12:02"}]), - ("candidate_timezone_offset", 9), - ("candidate_timezone_id", "UTC"), - ("representative_candidate_id", "00000000-0000-4000-8000-000000000001"), - ("unapproved_metadata", True), - ("confirmation_allowed", True), -]) -def test_dated_golden_projection_rejects_metadata_identity_and_gate_mutations(field, value) -> None: - expected = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - actual = json.loads(json.dumps(_golden_payload(), ensure_ascii=True)) - _assert_dated_payload_against_golden(actual, expected) - assert actual["decision_receipt"].get(field) != value - actual["decision_receipt"][field] = value - with pytest.raises(AssertionError): - _assert_dated_payload_against_golden(actual, expected) - - -def test_golden_float_shift_of_1e_minus_2_fails() -> None: - expected = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - mutated = json.loads(json.dumps(expected)) - mutated["candidate_scores"][0]["score"] += 1e-2 - with pytest.raises(AssertionError): - _assert_memoization_payloads(expected, mutated) - - -def test_golden_discrete_field_mismatch_fails() -> None: - expected = json.loads(GOLDEN_PATH.read_text(encoding="utf-8")) - mutated = json.loads(json.dumps(expected)) - mutated["candidate_scores"][0]["time"] = "99:99" - with pytest.raises(AssertionError): - _assert_memoization_payloads(expected, mutated) - - -def test_shadbala_verified_fields_match_with_and_without_birth_minute() -> None: - request = { - "birth_date": "1990-01-01", - "start_time": "12:17", - "end_time": "12:17", - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": [], - } - candidate_at = datetime(1990, 1, 1, 12, 17) - context = build_candidate_static_context(request, candidate_at) - chart = context["chart"] - planets = chart.get("planets", {}) - sun = float(planets["Sun"]["lon"]) - moon = float(planets["Moon"]["lon"]) - sign = str(chart["ascendant"].get("sign")) - birth_hour = candidate_at.hour + candidate_at.minute / 60 - with_minute = shadbala.calc_shadbala( - planets, - sign, - birth_hour, - sun, - moon, - birth_minute=float(candidate_at.minute), - ) - without_minute = shadbala.calc_shadbala(planets, sign, birth_hour, sun, moon) - fields_with = { - planet: ( - float((row.get("sthana_bala") or {}).get("total", 0)), - float(row.get("drik_bala", 0)), - float(row.get("naisargika_bala", 0)), - ) - for planet, row in (with_minute.get("planets") or {}).items() - } - fields_without = { - planet: ( - float((row.get("sthana_bala") or {}).get("total", 0)), - float(row.get("drik_bala", 0)), - float(row.get("naisargika_bala", 0)), - ) - for planet, row in (without_minute.get("planets") or {}).items() - } - assert fields_with == fields_without - reused_rules, reused_points = _shadbala_verified_components_auxiliary( - chart, birth_hour, ("Sun", "Moon", "Mars"), shadbala_result=with_minute, - ) - fresh_rules, fresh_points = _shadbala_verified_components_auxiliary( - chart, birth_hour, ("Sun", "Moon", "Mars"), - ) - assert reused_rules == fresh_rules - assert reused_points == fresh_points - - -def test_shadbala_and_ashtakavarga_run_once_per_candidate(monkeypatch) -> None: - shadbala_calls = _count_calls(monkeypatch, event_engine.shadbala, "calc_shadbala") - ashtakavarga_calls = _count_calls(monkeypatch, event_engine.ashtakavarga, "calc_ashtakavarga") - request = _normalized_request() - scored = score_candidates(request) - candidate_count = len(scored["candidate_scores"]) - assert candidate_count >= 2 - assert len(request["events"]) >= 2 - year_samples = sample_event_dates(request["events"][0]) - assert request["events"][0]["precision"] == "year" - assert len(year_samples) >= 2 - assert shadbala_calls[0] == candidate_count - assert ashtakavarga_calls[0] == candidate_count - - -def test_dasha_timelines_run_once_per_candidate(monkeypatch) -> None: - # Year-only events skip dasha-transition proximity, which also calls these - # two functions from event_probes. The scoring path itself must stay 1×/minute. - body = public_score_request() - body["events"][1]["precision"] = "year" - body["events"][1]["date_start"] = "2012-01-01" - body["events"][1]["date_end"] = "2012-12-31" - request = normalize_rectification_request(body, today=FROZEN_TODAY) - vim_calls = _count_calls( - monkeypatch, event_engine.dasha_analyzer, "build_dasha_timeline", from_engine=True, - ) - narayana_calls = _count_calls( - monkeypatch, event_engine.narayana_dasha, "calc_narayana_mahadasha", from_engine=True, - ) - scored = score_candidates(request) - candidate_count = len(scored["candidate_scores"]) - assert len(request["events"]) >= 2 - assert vim_calls[0] == candidate_count - assert narayana_calls[0] == candidate_count - - -def test_transit_charts_match_unique_event_dates_not_candidates(monkeypatch) -> None: - transit_calls = [0] - original = event_engine.domain_calculation_service.compute_chart - - def wrapped(payload: dict[str, Any], *args: Any, **kwargs: Any) -> Any: - # Natal candidates in this fixture also sit at 12:00; transit charts use the event year. - if payload.get("hour") == 12 and payload.get("minute") == 0 and payload.get("year") != 1990: - transit_calls[0] += 1 - return original(payload, *args, **kwargs) - - monkeypatch.setattr(event_engine.domain_calculation_service, "compute_chart", wrapped) - request = _normalized_request() - scored = score_candidates(request) - candidate_count = len(scored["candidate_scores"]) - expected_dates = { - sampled - for event in scoreable_request(request)["events"] - for sampled in sample_event_dates(event) - } - assert candidate_count >= 2 - assert len(expected_dates) >= 2 - assert transit_calls[0] == len(expected_dates) - assert transit_calls[0] != candidate_count * len(expected_dates) - - -def test_year_precision_transits_still_short_circuit() -> None: - request = { - "birth_date": "1990-01-01", - "start_time": "12:00", - "end_time": "12:00", - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": [{ - "id": "00000000-0000-4000-8000-000000000009", - "domain": "career", - "event_kind": "career_entry", - "date": "2012", - "precision": "year", - "summary": "入职", - }], - } - with patch.object(event_engine.domain_calculation_service, "compute_chart") as compute_chart: - rules = _controlled_transit_rules(request, request["events"][0], 0, (10,)) - assert rules == [] - compute_chart.assert_not_called() - - -def _probe_request_and_built() -> tuple[dict[str, Any], dict[str, Any], list[str]]: - body = public_score_request() - body["events"] = [ - { - "id": f"00000000-0000-4000-8000-{index:012d}", - "domain": domain, - "event_kind": kind, - "date_start": "2012-01-01", - "date_end": "2012-12-31", - "precision": "year", - "summary": kind, - } - for index, (domain, kind) in enumerate( - ( - ("education", "education_start"), - ("career", "career_entry"), - ("relationship", "relationship_start"), - ), - start=1, - ) - ] - request = normalize_rectification_request(body, today=FROZEN_TODAY) - times = ["12:00", "12:01", "12:02"] - event_ids = [event["id"] for event in request["events"]] - built = { - "candidate_times": times, - "matrix": { - event_id: { - clock: {"points": 4, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]} - for clock in times - } - for event_id in event_ids - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - return request, built, times - - -def test_discriminating_probes_run_once_when_probe_times_equal_grid(monkeypatch) -> None: - calls = _count_calls(monkeypatch, event_probes, "_discriminating_event_probe_lists") - request, built, times = _probe_request_and_built() - packet = build_refinement_packet( - request, - built, - representative_time="12:00", - candidate_times=times, - ) - assert calls[0] == 1 - assert packet["candidate_contrast_opportunities"] == [ - opportunity_from_probe(probe) for probe in packet["discriminating_event_probes"] - ] - - -def test_discriminating_probes_run_twice_on_refresh_columns(monkeypatch) -> None: - calls = _count_calls(monkeypatch, event_probes, "_discriminating_event_probe_lists") - request, built, times = _probe_request_and_built() - request = {**request, "refresh_probes": True} - packet = build_refinement_packet( - request, - built, - representative_time="12:00", - candidate_times=times, - column_times=["12:00"], - ) - assert times != ["12:00"] - assert calls[0] == 2 - assert "discriminating_event_probes" in packet - assert "candidate_contrast_opportunities" in packet - - -def test_dead_row_cache_removed_from_scoring_service() -> None: - token = "_cached_" + "rows" - assert not hasattr(scoring_service, token) - hits: list[str] = [] - for folder in ("scripts", "tests"): - for path in (ROOT / folder).rglob("*.py"): - text = path.read_text(encoding="utf-8") - if token in text: - hits.append(str(path.relative_to(ROOT)).replace("\\", "/")) - assert hits == [] - - -def test_compute_event_candidate_rows_reuses_static_context_without_mutating_it() -> None: - request = { - "birth_date": "1990-01-01", - "start_time": "12:00", - "end_time": "12:01", - "lat": 39.9, - "lon": 116.4, - "tz": 8, - "events": [{ - "id": "00000000-0000-4000-8000-000000000003", - "domain": "career", - "event_kind": "career_entry", - "date": "2012-06-15", - "precision": "day", - "summary": "入职", - }], - } - contexts = [ - build_candidate_static_context(request, candidate) - for candidate in _candidate_datetimes(request) - ] - original_keys = [frozenset(context) for context in contexts] - rows = compute_event_candidate_rows(request, static_contexts=contexts) - assert len(rows) == 2 - assert [frozenset(context) for context in contexts] == original_keys - assert all("_transit_chart_cache" not in context for context in contexts) - - -def test_cached_static_context_matches_uncached_fallback(monkeypatch) -> None: - request = _event_engine_request() - cached = [ - build_candidate_static_context(request, candidate) - for candidate in _candidate_datetimes(request) - ] - assert len(cached) >= 2 - assert len(request["events"]) >= 2 - for context in cached: - for key in CACHE_LAYER_KEYS: - assert context.get(key) is not None - uncached = _contexts_with_layer_cache_cleared(cached) - for context in uncached: - for key in CACHE_LAYER_KEYS: - assert context[key] is None - calls = _count_calls(monkeypatch, event_engine.shadbala, "calc_shadbala") - rows_cached = compute_event_candidate_rows(request, static_contexts=cached) - cached_calls = calls[0] - rows_uncached = compute_event_candidate_rows(request, static_contexts=uncached) - uncached_calls = calls[0] - cached_calls - assert rows_cached == rows_uncached - assert cached_calls == 0 - assert uncached_calls > cached_calls - assert uncached_calls >= len(cached) * len(request["events"]) - - -def test_poisoned_static_cache_diverges_from_live_rows() -> None: - request = _event_engine_request() - cached = [ - build_candidate_static_context(request, candidate) - for candidate in _candidate_datetimes(request) - ] - rows_cached = compute_event_candidate_rows(request, static_contexts=cached) - poisoned = [dict(context) for context in cached] - poisoned[0]["shadbala_result"] = { - "planets": { - name: { - "sthana_bala": {"total": 0.0}, - "drik_bala": 0.0, - "naisargika_bala": 0.0, - } - for name in ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn") - } - } - rows_poisoned = compute_event_candidate_rows(request, static_contexts=poisoned) - assert rows_poisoned != rows_cached diff --git a/tests/test_rectification_family_appearance_scoring.py b/tests/test_rectification_family_appearance_scoring.py deleted file mode 100644 index 68ee3b7f8..000000000 --- a/tests/test_rectification_family_appearance_scoring.py +++ /dev/null @@ -1,254 +0,0 @@ -from __future__ import annotations - -from datetime import date - -from scripts.active_rectification_event_engine import ( - AUXILIARY_DOMAINS, - AUXILIARY_SCORE_FACTOR, - DOMAIN_CONFIG, - _score_event, - compute_candidate_static_contexts, - compute_event_candidate_rows, -) -from scripts.rectification.contracts import ( - is_primary_scoreable_event, - is_scoreable_event, - normalize_rectification_request, -) -from scripts.rectification.scoring_service import public_technique_layers - - -def test_family_event_is_scoreable_with_d12_and_kin_houses() -> None: - prefixes, houses = DOMAIN_CONFIG["family"] - assert prefixes == ("D12", "D7", "D3") - assert houses == (3, 4, 5, 9) - event = { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "family", - "event_kind": "family_event", - "date_start": "2016-09-15", - "date_end": "2016-09-15", - "precision": "day", - "summary": "家人变化", - } - assert is_scoreable_event(event) is True - assert is_primary_scoreable_event(event) is True - coerced = normalize_rectification_request( - { - "birth_date": "1997-08-08", - "start_time": "05:13", - "end_time": "05:15", - "lat": 36.419, - "lon": 114.213, - "tz": 8, - "events": [{**event, "subject": "self"}], - }, - today=date(2026, 7, 28), - ) - assert coerced["events"][0]["subject"] == "family" - normalized = normalize_rectification_request( - { - "birth_date": "1997-08-08", - "start_time": "05:13", - "end_time": "05:15", - "lat": 36.419, - "lon": 114.213, - "tz": 8, - "events": [event], - }, - today=date(2026, 7, 28), - ) - assert normalized["events"][0]["subject"] == "family" - - -def test_career_event_always_exposes_d1_tenth_and_d10_layers() -> None: - prefixes, houses = DOMAIN_CONFIG["career"] - assert prefixes == ("D10",) - assert houses == (10,) - layers = public_technique_layers("career", ["vim_md_domain_house", "vim_md_domain_varga"]) - assert "d1-rashi" in layers - assert "d10-dashamsa" in layers - scored = _score_event( - candidate_time="05:13", - event={ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "career", - "event_kind": "career_entry", - "date": "2016-09-15", - "precision": "day", - }, - natal_chart={"ascendant": {"lon": 10.0, "sign": "Aries"}, "planets": {"Sun": {"house": 10, "lon": 12.0}}}, - varga_charts=[{"Ascendant": {"sign_idx": 0}, "Sun": {"sign_idx": 9}}], - vimshottari=("Sun", "Moon", "Mars"), - narayana=(None, None), - arudha_padas={}, - ) - assert any(item.endswith("_domain_house") for item in scored["rule_ids"]) - assert any(item.endswith("_domain_varga") for item in scored["rule_ids"]) - - -def test_appearance_is_auxiliary_first_house_not_primary() -> None: - prefixes, houses = DOMAIN_CONFIG["appearance"] - assert prefixes == () - assert houses == (1,) - assert "appearance" in AUXILIARY_DOMAINS - assert AUXILIARY_SCORE_FACTOR == 0.4 - natal = { - "ascendant": {"lon": 10.0, "sign": "Aries"}, - "planets": {"Sun": {"house": 1, "lon": 12.0}}, - } - scored = _score_event( - candidate_time="05:13", - event={ - "id": "00000000-0000-4000-8000-000000000002", - "domain": "appearance", - "event_kind": "birthmark_or_scar", - "date": "2010-01-01", - "precision": "year", - }, - natal_chart=natal, - varga_charts=[], - vimshottari=("Sun", "Moon", "Mars"), - narayana=(None, None), - arudha_padas={}, - ) - assert "appearance_auxiliary_not_primary" in scored["rule_ids"] - primary = _score_event( - candidate_time="05:13", - event={ - "id": "00000000-0000-4000-8000-000000000003", - "domain": "career", - "event_kind": "career_entry", - "date": "2010-01-01", - "precision": "year", - }, - natal_chart={"ascendant": {"lon": 10.0, "sign": "Aries"}, "planets": {"Sun": {"house": 10, "lon": 12.0}}}, - varga_charts=[{"Ascendant": {"sign_idx": 0}, "Sun": {"sign_idx": 9}}], - vimshottari=("Sun", "Moon", "Mars"), - narayana=(None, None), - arudha_padas={}, - ) - assert scored["points"] < primary["points"] - assert is_primary_scoreable_event({ - "id": "00000000-0000-4000-8000-000000000002", - "domain": "appearance", - "event_kind": "appearance_note", - "date_start": "2010-01-01", - "date_end": "2010-12-31", - "precision": "year", - }) is False - - -def test_family_event_engine_rows_include_d12_and_are_not_skipped() -> None: - request = { - "birth_date": "1997-08-08", - "start_time": "05:13", - "end_time": "05:14", - "lat": 36.419, - "lon": 114.213, - "tz": 8.0, - "events": [{ - "id": "00000000-0000-4000-8000-000000000001", - "domain": "family", - "event_kind": "family_event", - "date": "2016-09-15", - "precision": "day", - "summary": "家人变化", - }], - } - contexts = compute_candidate_static_contexts(request) - assert all("D12" in context["feature"]["available_layers"] for context in contexts) - assert all("D7" in context["feature"]["available_layers"] for context in contexts) - assert all("D3" in context["feature"]["available_layers"] for context in contexts) - assert all(context["varga_charts"]["D12"] is not None for context in contexts) - assert all(context["varga_charts"]["D7"] is not None for context in contexts) - assert all(context["varga_charts"]["D3"] is not None for context in contexts) - assert all(isinstance(context["feature"].get("pada_index"), int) for context in contexts) - assert all(0 <= context["feature"]["pada_index"] <= 107 for context in contexts) - assert all(isinstance(context["feature"].get("bhava_sign_index"), int) for context in contexts) - rows = compute_event_candidate_rows(request, static_contexts=contexts) - assert [row["time"] for row in rows] == ["05:13", "05:14"] - for row in rows: - assert "D12" not in row["missing_layers"] - assert "D7" not in row["missing_layers"] - assert row["evidence"], "family events must enter scoring instead of being skipped" - assert row["evidence"][0]["domain"] == "family" - assert "event_kind:family_event" in row["evidence"][0]["rule_ids"] - career = { - **request, - "events": [{ - "id": "00000000-0000-4000-8000-000000000004", - "domain": "career", - "event_kind": "career_entry", - "date": "2016-09-15", - "precision": "day", - }], - } - career_rows = compute_event_candidate_rows(career, static_contexts=contexts) - assert all(row["evidence"] for row in career_rows) - career_rules = [rule for row in career_rows for item in row["evidence"] for rule in item["rule_ids"]] - layers = public_technique_layers("career", career_rules) - assert "d1-rashi" in layers and "d10-dashamsa" in layers - family_layers = public_technique_layers("family", ["vim_md_domain_house", "vim_md_domain_varga"]) - assert "d12-dwadashamsha" in family_layers and "d7-saptamsha" in family_layers - assert "d3-drekkana" in family_layers - education_layers = public_technique_layers("education", ["vim_md_domain_house"]) - assert "d5-panchamsha" in education_layers and "d24-chaturvimshamsha" in education_layers - finance_layers = public_technique_layers("finance", ["vim_md_domain_house"]) - assert "d2-hora" in finance_layers and "d11-labhamsha" in finance_layers - health_layers = public_technique_layers("health_pressure", ["vim_md_domain_house"]) - assert "d30-trimshamsha" in health_layers - occupation_layers = public_technique_layers("occupation", ["vim_md_domain_house"]) - assert "d1-rashi" in occupation_layers and "d10-dashamsa" in occupation_layers - assert all("D10" in context["feature"]["available_layers"] for context in contexts) - assert all("D5" in context["feature"]["available_layers"] for context in contexts) - - -def test_occupation_is_auxiliary_tenth_house_independent_of_career() -> None: - prefixes, houses = DOMAIN_CONFIG["occupation"] - assert prefixes == ("D10",) - assert houses == (10,) - assert "occupation" in AUXILIARY_DOMAINS - event = { - "id": "00000000-0000-4000-8000-000000000005", - "domain": "occupation", - "event_kind": "occupation_note", - "date_start": "2019-01-01", - "date_end": "2019-12-31", - "precision": "year", - "summary": "长期工作", - } - assert is_scoreable_event(event) is True - assert is_primary_scoreable_event(event) is False - scored = _score_event( - candidate_time="05:13", - event={ - "id": event["id"], - "domain": "occupation", - "event_kind": "occupation_note", - "date": "2019-01-01", - "precision": "year", - }, - natal_chart={"ascendant": {"lon": 10.0, "sign": "Aries"}, "planets": {"Sun": {"house": 10, "lon": 12.0}}}, - varga_charts=[{"Ascendant": {"sign_idx": 0}, "Sun": {"sign_idx": 9}}], - vimshottari=("Sun", "Moon", "Mars"), - narayana=(None, None), - arudha_padas={}, - ) - assert "occupation_auxiliary_not_primary" in scored["rule_ids"] - career = _score_event( - candidate_time="05:13", - event={ - "id": "00000000-0000-4000-8000-000000000006", - "domain": "career", - "event_kind": "career_entry", - "date": "2019-01-01", - "precision": "year", - }, - natal_chart={"ascendant": {"lon": 10.0, "sign": "Aries"}, "planets": {"Sun": {"house": 10, "lon": 12.0}}}, - varga_charts=[{"Ascendant": {"sign_idx": 0}, "Sun": {"sign_idx": 9}}], - vimshottari=("Sun", "Moon", "Mars"), - narayana=(None, None), - arudha_padas={}, - ) - assert scored["points"] < career["points"] diff --git a/tests/test_rectification_horary_observation.py b/tests/test_rectification_horary_observation.py deleted file mode 100644 index d811d69ed..000000000 --- a/tests/test_rectification_horary_observation.py +++ /dev/null @@ -1,66 +0,0 @@ -from __future__ import annotations - -from tests.conftest import FIXTURE_BIRTH_DATE, FIXTURE_BIRTH_LAT, FIXTURE_BIRTH_LON - -from scripts.rectification.horary_observation import build_horary_observation - - -def _request(**overrides): - body = { - "birth_date": FIXTURE_BIRTH_DATE, - "start_time": "14:29", - "end_time": "14:30", - "lat": FIXTURE_BIRTH_LAT, - "lon": FIXTURE_BIRTH_LON, - "tz": 8.0, - "events": [], - } - body.update(overrides) - return body - - -def test_horary_without_query_is_skipped() -> None: - result = build_horary_observation(_request(events=[{ - "id": "00000000-0000-4000-8000-000000000001", - "domain": "career", - "event_kind": "career_entry", - "date_start": "2019-07-01", - "date_end": "2019-07-01", - "precision": "day", - }])) - assert result["status"] == "skipped" - assert result["unique_minute_claim"] is False - - -def test_dated_horary_query_is_observation_only() -> None: - result = build_horary_observation(_request(events=[{ - "id": "00000000-0000-4000-8000-000000000002", - "domain": "horary", - "event_kind": "horary_query", - "date_start": "2024-01-15", - "date_end": "2024-01-15", - "precision": "day", - "summary": "第一次问起是 14:30", - }])) - assert result["status"] in {"executed", "blocked"} - assert result["unique_minute_claim"] is False - assert "不计分" in result["user_meaning"] - if result["status"] == "executed": - assert result["question_date"] == "2024-01-15" - assert result["question_time"] == "14:30" - assert result.get("lagna") - - -def test_horary_without_coordinates_is_blocked_not_a_gate_fail() -> None: - result = build_horary_observation({ - "events": [{ - "id": "00000000-0000-4000-8000-000000000003", - "domain": "horary", - "event_kind": "horary_query", - "date_start": "2024-01-15", - "date_end": "2024-01-15", - "precision": "day", - }], - }) - assert result["status"] == "blocked" - assert result["unique_minute_claim"] is False diff --git a/tests/test_rectification_kp_cusp_observation.py b/tests/test_rectification_kp_cusp_observation.py index 4562b54fe..d99aec7fb 100644 --- a/tests/test_rectification_kp_cusp_observation.py +++ b/tests/test_rectification_kp_cusp_observation.py @@ -9,11 +9,6 @@ from scripts.active_rectification_event_engine import ( build_candidate_static_context, compute_event_candidate_rows, ) -from scripts.rectification.decision_policy import ( - build_candidate_decisions, - build_decision_receipt, - build_technique_audit, -) from scripts.rectification.kp_cusp_observation import observe_kp_cusps from scripts.rectification.refinement_packet import window_scan @@ -132,48 +127,6 @@ def test_window_scan_emits_kp_sub_lord_changes_without_confirmation() -> None: assert scan["unique_minute_claim"] is False -def test_technique_audit_kp_executed_when_snapshot_present() -> None: - rows = build_technique_audit( - { - "matrix": {}, - "static_contexts": [{ - "feature": { - "time": "05:13", - "kp_cusps": {"status": "executed", "house_system": "placidus", "ayanamsa": "krishnamurti"}, - } - }], - }, - house_table={"time": "05:13", "lagna": "金牛座"}, - ) - kp = next(row for row in rows if row["technique"] == "KP 宫头") - assert kp["status"] == "executed" - assert "政策跳过" not in kp["note"] - assert "不计分" in kp["note"] - - -def test_technique_audit_kp_blocked_is_honest_and_does_not_fail_propose() -> None: - rows = build_technique_audit({"matrix": {}, "static_contexts": []}, house_table=None) - kp = next(row for row in rows if row["technique"] == "KP 宫头") - assert kp["status"] == "blocked" - assert "政策跳过" not in kp["note"] - decisions = build_candidate_decisions( - [{"time": "05:13", "score": 20, "evidence": [], "missing_layers": []}, - {"time": "05:14", "score": 8, "evidence": [], "missing_layers": []}], - result_id="00000000-0000-4000-8000-000000000099", - ) - receipt = build_decision_receipt( - _score_request(), - decisions, - {"missing_layers": [], "matrix": {}, "static_contexts": [{"feature": {"time": "05:13", "kp_cusps": {"status": "blocked"}}}]}, - _diagnostics(), - ) - assert receipt["gates"]["required_layers"]["passed"] is True - assert receipt["propose_allowed"] is True - audit = next(row for row in receipt["technique_audit_table"] if row["technique"] == "KP 宫头") - assert audit["status"] == "blocked" - assert "政策跳过" not in audit["note"] - - def test_observe_kp_cusps_blocks_without_inventing_whole_sign_proxy() -> None: snapshot = observe_kp_cusps(None, 36.6, 114.3) assert snapshot["status"] == "blocked" diff --git a/tests/test_rectification_midnight_date_anchor.py b/tests/test_rectification_midnight_date_anchor.py deleted file mode 100644 index e0881748a..000000000 --- a/tests/test_rectification_midnight_date_anchor.py +++ /dev/null @@ -1,155 +0,0 @@ -"""BUG-982/983: explicit civil-date windows; synthetic dates, native computations.""" -from datetime import datetime, timedelta - -import pytest - -from scripts.active_rectification_event_engine import _candidate_datetimes -from scripts.rectification.decision_policy import _cluster_span, indistinguishable_width_minutes - - -def test_declared_minute_stays_on_declared_date(): - moments = _candidate_datetimes({ - "birth_date": "2000-06-15", "start_time": "23:55", "end_time": "00:25", - "candidate_intervals": [{"start_at": "2000-06-14T23:55", "end_at": "2000-06-15T00:25"}], - }) - assert datetime(2000, 6, 15, 0, 10) in moments - assert datetime(2000, 6, 16, 0, 10) not in moments - - -def test_late_night_unknown_is_two_segments_of_same_day(): - moments = _candidate_datetimes({ - "birth_date": "2000-06-15", "start_time": "23:00", "end_time": "03:59", - "candidate_intervals": [ - {"start_at": "2000-06-15T00:00", "end_at": "2000-06-15T03:59"}, - {"start_at": "2000-06-15T23:00", "end_at": "2000-06-15T23:59"}, - ], - }) - assert len(moments) == 300 - assert {at.date().isoformat() for at in moments} == {"2000-06-15"} - assert not any(4 <= at.hour < 23 for at in moments) - - -def test_cluster_span_uses_window_order_across_midnight(): - row = {"time": "23:58", "cluster_times": ["23:58", "23:59", "00:00"], - "cluster_positions": [ - {"time": time, "window_index": i, "window_offset_minutes": i, - "segment_index": 0, "candidate_date": "2000-06-14" if i < 2 else "2000-06-15"} - for i, time in enumerate(["23:58", "23:59", "00:00"]) - ]} - assert _cluster_span(row) == (["23:58", "23:59", "00:00"], "23:58", "00:00") - assert indistinguishable_width_minutes([{ - "rank": 1, "time": "23:58", "tied_minute_count": 3, - "cluster_start": "23:58", "cluster_end": "00:00", - "cluster_intervals": [{"start_index": 0, "end_index": 2, - "start_offset_minutes": 0, "end_offset_minutes": 2, - "start_at": "2000-06-14T23:58", "end_at": "2000-06-15T00:00", "segment_index": 0}], - }]) == 3 - - -@pytest.mark.parametrize("step", [1, 2, 5, 10, 15]) -def test_same_day_candidate_enumeration_unchanged(step): - request = {"birth_date": "2000-06-15", "start_time": "11:45", "end_time": "12:15", "minute_step": step} - assert _candidate_datetimes(request) == _candidate_datetimes({**request, "candidate_intervals": [ - {"start_at": "2000-06-15T11:45", "end_at": "2000-06-15T12:15"}, - ]}) - - -@pytest.mark.parametrize("date", ["2000-01-01", "2000-03-01", "2000-02-29", "2001-03-01", "2000-12-31"]) -@pytest.mark.parametrize("clock", ["00:00", "00:10", "23:59"]) -def test_calendar_boundaries(date, clock): - center = datetime.fromisoformat(f"{date}T{clock}") - start, end = center - timedelta(minutes=15), center + timedelta(minutes=15) - request = {"birth_date": date, "start_time": start.strftime("%H:%M"), "end_time": end.strftime("%H:%M"), - "candidate_intervals": [{"start_at": start.isoformat(timespec="minutes"), "end_at": end.isoformat(timespec="minutes")}]} - moments = _candidate_datetimes(request) - assert moments == [start + timedelta(minutes=i) for i in range(31)] - assert moments[15] == center - - -@pytest.mark.parametrize("step", [2, 15]) -def test_nondivisible_sampling_preserves_legacy_endpoint_rule(step): - request = {"birth_date": "2000-01-01", "start_time": "12:00", "end_time": "12:31", "minute_step": step} - moments = _candidate_datetimes(request) - assert [at.minute for at in moments] == list(range(0, 32, step)) - assert moments[-1].minute == 30 # legacy range() never appends an unaligned endpoint - - -@pytest.mark.parametrize("parts", [ - [{"start_at": "2000-02-30T00:00", "end_at": "2000-03-01T00:00"}], - [{"start_at": "1999-12-30T23:59", "end_at": "1999-12-30T23:59"}], - [{"start_at": "2000-01-03T00:00", "end_at": "2000-01-03T00:00"}], - [{"start_at": "2000-01-01T01:00", "end_at": "2000-01-01T00:00"}], - [{"start_at": "2000-01-01T00:00", "end_at": "2000-01-01T01:00"}, {"start_at": "2000-01-01T01:00", "end_at": "2000-01-01T02:00"}], - [{"start_at": "2000-01-01T00:00", "end_at": "2000-01-01T00:01"}, {"start_at": "2000-01-02T00:00", "end_at": "2000-01-02T00:01"}], - [{"start_at": "2000-01-01T00:00Z", "end_at": "2000-01-01T00:01Z"}], -]) -def test_invalid_intervals_fail_closed(parts): - from scripts.rectification.candidate_window import candidate_intervals - with pytest.raises(ValueError): - candidate_intervals({"birth_date": "2000-01-01", "start_time": "00:00", "end_time": "23:59", "candidate_intervals": parts}) - - -@pytest.mark.parametrize("parts", [None, [], {}, "", [None], [{"start_at": "2000-01-01T00:00"}]]) -def test_api_normalization_rejects_present_invalid_intervals(parts): - from scripts.rectification.contracts import normalize_rectification_request - request = {"birth_date": "2000-01-01", "start_time": "23:55", "end_time": "00:25", - "lat": 0, "lon": 0, "tz": 0, "events": []} - legacy = normalize_rectification_request(request) - assert "candidate_intervals" not in legacy - with pytest.raises(ValueError): - normalize_rectification_request({**request, "candidate_intervals": parts}) - - -def test_report_sampler_recasts_actual_dates_without_gap(monkeypatch): - from types import SimpleNamespace - from scripts import jyotish_engine - import flexible_birth_time_profile as profile - captured = [] - def recast(at, **kwargs): - captured.append(at) - return {"ascendant": {"sign": "Aries"}} - monkeypatch.setattr(profile, "_recast_candidate_layers", recast) - args = SimpleNamespace(year=2000, month=3, day=1, hour=0, minute=0, lat=0, lon=0, tz=0, - birth_time_accuracy="provisional", ayanamsa="raman", candidate_range={"start_time": "23:58", "end_time": "00:02", - "candidate_intervals": [{"start_at": "2000-02-29T23:58", "end_at": "2000-03-01T00:02"}]}) - result = jyotish_engine._build_birth_time_sensitivity(args) - assert captured == [datetime(2000, 2, 29, 23, 58)+timedelta(minutes=i) for i in range(5)] - assert result["status"] == "candidate_window_only" - captured.clear() - args.candidate_range = {"start_time": "23:00", "end_time": "03:59", "candidate_intervals": [ - {"start_at": "2000-03-01T00:00", "end_at": "2000-03-01T03:59"}, - {"start_at": "2000-03-01T23:00", "end_at": "2000-03-01T23:59"}]} - jyotish_engine._build_birth_time_sensitivity(args) - assert len(captured) == 31 - assert all(at.date().isoformat() == "2000-03-01" and (at.hour < 4 or at.hour == 23) for at in captured) - - -def test_segment_cap_merge_retains_all_minutes_without_daytime(): - from scripts.rectification.candidate_window import candidate_positions, intervals_from_positions, interval_union_width - from scripts.rectification.candidate_contrast import select_signature_representatives - request = {"birth_date": "2000-01-01", "start_time": "23:00", "end_time": "03:59", "candidate_intervals": [ - {"start_at": "2000-01-01T00:00", "end_at": "2000-01-01T03:59"}, - {"start_at": "2000-01-01T23:00", "end_at": "2000-01-01T23:59"}]} - positions = candidate_positions(request, _candidate_datetimes(request)) - contexts = [{**row, "feature": {"time": row["time"], "ascendant_sign_index": row["window_index"] % 70}} for row in positions] - rows = [{"time": row["time"], "score": 1.0} for row in positions] - result = select_signature_representatives(rows, contexts) - assert len(result) == 64 - assert {time for row in result for time in row["cluster_times"]} == {row["time"] for row in positions} - intervals = [part for row in result for part in intervals_from_positions(row["cluster_positions"])] - assert interval_union_width(intervals) == 300 - assert {part["segment_index"] for part in intervals} == {0, 1} - - -def test_same_signature_different_segments_and_step_offsets(): - from scripts.rectification.candidate_window import candidate_positions, intervals_from_positions, interval_union_width - from scripts.rectification.candidate_contrast import cluster_contexts_by_signature - request = {"birth_date": "2000-01-01", "start_time": "23:00", "end_time": "03:59", "minute_step": 2, - "candidate_intervals": [{"start_at": "2000-01-01T00:00", "end_at": "2000-01-01T03:59"}, - {"start_at": "2000-01-01T23:00", "end_at": "2000-01-01T23:59"}]} - rows = candidate_positions(request, _candidate_datetimes(request)) - contexts = [{**row, "feature": {"time": row["time"]}} for row in rows] - assert len(cluster_contexts_by_signature(contexts)) == 2 - assert rows[120]["window_offset_minutes"] == 1380 - assert rows[120]["window_index"] == 120 - assert interval_union_width(intervals_from_positions(rows)) == 298 diff --git a/tests/test_rectification_provenance.py b/tests/test_rectification_provenance.py deleted file mode 100644 index a8442b9a7..000000000 --- a/tests/test_rectification_provenance.py +++ /dev/null @@ -1,47 +0,0 @@ -from datetime import date -import unittest - -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.scoring_service import build_event_contribution_matrix, calculation_spec, sha256 - -EVENT_ID = "00000000-0000-4000-8000-000000000002" - -def request(): - return { - "birth_date": "1990-01-02", "start_time": "05:00", "end_time": "06:00", - "lat": 25.033, "lon": 121.5654, "tz": 8, - "events": [{"id": EVENT_ID, "domain": "career", "event_kind": "career_change", "date_start": "2020-01-01", "date_end": "2020-12-31", "precision": "year", "summary": "工作变动"}], - } - -class RectificationProvenanceTest(unittest.TestCase): - def test_missing_and_explicit_null_remain_distinct(self): - legacy = normalize_rectification_request(request(), today=date(2026, 7, 30)) - self.assertNotIn("birth_time_source", legacy) - enriched_input = request() - enriched_input["birth_time_source"] = None - enriched_input["events"][0]["date_source"] = None - enriched = normalize_rectification_request(enriched_input, today=date(2026, 7, 30)) - self.assertIn("birth_time_source", enriched) - self.assertIsNone(enriched["birth_time_source"]) - self.assertIn("date_source", enriched["events"][0]) - - def test_enriched_spec_hash_matches_typescript_fixture(self): - value = request() - value.update({"birth_time_source": "family_exact", "timezone_id": "Asia/Taipei", "timezone_source": "iana_historical", "local_time_status": "resolved"}) - normalized = normalize_rectification_request(value, today=date(2026, 7, 30)) - self.assertEqual(sha256(calculation_spec(normalized)), "de2096c6fe903a795d04e27bbce8849faab3042ca568a5a90ad4b6e1b8815b6c") - - def test_event_provenance_is_not_forwarded_to_scoring_weights(self): - value = request() - value["events"][0].update({"date_source": "user_reported", "date_reliability": "medium"}) - normalized = normalize_rectification_request(value, today=date(2026, 7, 30)) - seen = [] - def provider(payload): - seen.append(payload) - return [{"time": "05:00", "score": 1, "evidence": [{"event_id": EVENT_ID, "domain": "career", "candidate_time": "05:00", "rule_ids": ["D10:test"], "points": 1}], "missing_layers": []}] - build_event_contribution_matrix(normalized, provider) - self.assertTrue(seen) - self.assertTrue(all("date_source" not in payload["events"][0] for payload in seen)) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rectification_refinement_packet.py b/tests/test_rectification_refinement_packet.py deleted file mode 100644 index bfe1f2c0d..000000000 --- a/tests/test_rectification_refinement_packet.py +++ /dev/null @@ -1,482 +0,0 @@ -from __future__ import annotations - -import unittest - -from scripts.rectification.decision_policy import build_candidate_decisions, build_decision_receipt -from scripts.rectification.refinement_packet import ( - build_refinement_packet, - cluster_scan, - dasha_agreement, - match_level, - precision_stage, - window_scan, -) - - -def feature( - time: str, - *, - d1: int | None = None, - d9: int | None = None, - d10: int | None = None, - d4: int | None = None, - d5: int | None = None, - d7: int | None = None, - d12: int | None = None, - d24: int | None = None, - d2: int | None = None, - d11: int | None = None, - d30: int | None = None, - degree: float | None = None, - pada: int | None = None, - hora: int | None = None, - ghati: int | None = None, - bhava: int | None = None, - pranapada: int | None = None, -) -> dict: - vargas = {} - if d9 is not None: - vargas["D9"] = d9 - if d10 is not None: - vargas["D10"] = d10 - if d4 is not None: - vargas["D4"] = d4 - if d5 is not None: - vargas["D5"] = d5 - if d7 is not None: - vargas["D7"] = d7 - if d12 is not None: - vargas["D12"] = d12 - if d24 is not None: - vargas["D24"] = d24 - if d2 is not None: - vargas["D2"] = d2 - if d11 is not None: - vargas["D11"] = d11 - if d30 is not None: - vargas["D30"] = d30 - row: dict = {"time": time, "varga_ascendants": vargas} - if d1 is not None: - row["ascendant_sign_index"] = d1 - if degree is not None: - row["ascendant_degree"] = degree - if pada is not None: - row["pada_index"] = pada - if hora is not None: - row["hora_sign_index"] = hora - if ghati is not None: - row["ghati_sign_index"] = ghati - if bhava is not None: - row["bhava_sign_index"] = bhava - if pranapada is not None: - row["pranapada_sign_index"] = pranapada - return {"feature": row} - - -def request_events() -> dict: - return { - "events": [ - {"id": "00000000-0000-4000-8000-000000000001", "domain": "career", "summary": "入职", "event_kind": "career_entry", "precision": "day", "date_start": "2016-09-15", "date_end": "2016-09-15"}, - {"id": "00000000-0000-4000-8000-000000000002", "domain": "relationship", "summary": "开始一段关系", "event_kind": "relationship_start", "precision": "day", "date_start": "2018-03-01", "date_end": "2018-03-01"}, - {"id": "00000000-0000-4000-8000-000000000003", "domain": "education", "summary": "毕业", "event_kind": "education_completion", "precision": "day", "date_start": "2015-06-01", "date_end": "2015-06-01"}, - {"id": "00000000-0000-4000-8000-000000000004", "domain": "family", "summary": "家人变化", "event_kind": "family_event", "precision": "day", "date_start": "2020-01-01", "date_end": "2020-01-01"}, - ], - } - - -class RefinementPacketTest(unittest.TestCase): - def test_window_scan_emits_d9_sign_names_for_type_table_report(self): - built = { - "static_contexts": [ - feature("05:13", d1=1, d9=1, d10=4), - feature("05:14", d1=1, d9=7, d10=4), - ] - } - scan = window_scan(built) - self.assertEqual(scan["d9_lagna_count"], 2) - self.assertEqual(scan["d10_lagna_count"], 1) - self.assertEqual(scan["d1_lagna_count"], 1) - self.assertEqual(scan["d9_sign_names"], ["金牛座", "天蝎座"]) - self.assertEqual(scan["d10_sign_names"], ["狮子座"]) - self.assertEqual(scan["transitions"], [{ - "layer": "d9", - "at": "05:14", - "user_meaning": "D9 在 05:14 发生变化", - "from_sign": "金牛座", - "to_sign": "天蝎座", - }]) - encoded = str(scan) - self.assertNotIn("Aries", encoded) - self.assertFalse(scan["unique_minute_claim"]) - self.assertFalse(scan["confirmation_allowed"]) - - def test_match_level_and_dual_dasha_conflict(self): - self.assertEqual(match_level(["vim_md_domain_house"]), "strong") - self.assertEqual(match_level(["vim_ad_domain_lord"]), "medium") - self.assertEqual(match_level(["no_domain_activation"]), "none") - built = { - "matrix": { - "00000000-0000-4000-8000-000000000001": { - "05:13": {"points": 8, "rule_ids": ["vim_md_domain_house"]}, - "05:14": {"points": 1, "rule_ids": ["vim_ad_domain_house"]}, - }, - "00000000-0000-4000-8000-000000000002": { - "05:13": {"points": 1, "rule_ids": ["narayana_ad_domain_house"]}, - "05:14": {"points": 9, "rule_ids": ["narayana_md_domain_house"]}, - }, - } - } - agreement = dasha_agreement(built, ["05:13", "05:14"]) - self.assertEqual(agreement["status"], "conflict") - self.assertEqual(agreement["vimshottari_top"], "05:13") - self.assertEqual(agreement["narayana_top"], "05:14") - self.assertIn("冲突", agreement["user_meaning"]) - - def test_dasha_agreement_same_cluster_peaks_agree(self): - built = { - "matrix": { - "00000000-0000-4000-8000-000000000001": { - "04:54": {"points": 8, "rule_ids": ["vim_md_domain_house"]}, - "04:59": {"points": 1, "rule_ids": ["vim_ad_domain_house"]}, - }, - "00000000-0000-4000-8000-000000000002": { - "04:54": {"points": 1, "rule_ids": ["narayana_ad_domain_house"]}, - "04:59": {"points": 9, "rule_ids": ["narayana_md_domain_house"]}, - }, - } - } - clusters = [{ - "time": "04:54", - "cluster_start": "04:54", - "cluster_end": "04:59", - "cluster_times": ["04:54", "04:59"], - }] - without_clusters = dasha_agreement(built, ["04:54", "04:59"]) - self.assertEqual(without_clusters["status"], "conflict") - agreement = dasha_agreement(built, ["04:54", "04:59"], clusters=clusters) - self.assertEqual(agreement["status"], "agree") - self.assertEqual(agreement["vimshottari_top"], "04:54") - self.assertEqual(agreement["narayana_top"], "04:59") - - def test_dasha_agreement_cross_cluster_peaks_conflict(self): - built = { - "matrix": { - "00000000-0000-4000-8000-000000000001": { - "05:13": {"points": 8, "rule_ids": ["vim_md_domain_house"]}, - "05:20": {"points": 1, "rule_ids": ["vim_ad_domain_house"]}, - }, - "00000000-0000-4000-8000-000000000002": { - "05:13": {"points": 1, "rule_ids": ["narayana_ad_domain_house"]}, - "05:20": {"points": 9, "rule_ids": ["narayana_md_domain_house"]}, - }, - } - } - clusters = [ - {"time": "05:13", "cluster_start": "05:13", "cluster_end": "05:13", "cluster_times": ["05:13"]}, - {"time": "05:20", "cluster_start": "05:20", "cluster_end": "05:20", "cluster_times": ["05:20"]}, - ] - agreement = dasha_agreement(built, ["05:13", "05:20"], clusters=clusters) - self.assertEqual(agreement["status"], "conflict") - - def test_dasha_agreement_one_track_is_partial(self): - built = { - "matrix": { - "00000000-0000-4000-8000-000000000001": { - "05:13": {"points": 8, "rule_ids": ["vim_md_domain_house"]}, - "05:20": {"points": 1, "rule_ids": ["vim_ad_domain_house"]}, - }, - } - } - agreement = dasha_agreement(built, ["05:13", "05:20"]) - self.assertEqual(agreement["status"], "partial") - - def test_precision_stage_walks_d1_then_d9_then_ready(self): - self.assertEqual(precision_stage({"d1_candidates_differ": True}, 2)["current"], "lagna_frame") - self.assertEqual(precision_stage({"d9_candidates_differ": True}, 2)["current"], "d9_refine") - self.assertEqual(precision_stage({"d10_candidates_differ": True}, 2)["current"], "d10_refine") - self.assertEqual(precision_stage({"d4_candidates_differ": True}, 2)["current"], "d4_refine") - self.assertEqual(precision_stage({"d5_candidates_differ": True}, 2)["current"], "d5_refine") - self.assertEqual( - precision_stage({"d24_candidates_differ": True, "d5_candidates_differ": False}, 2)["current"], - "d5_refine", - ) - self.assertNotEqual(precision_stage({"d4_candidates_differ": True}, 2)["current"], "theme_refine") - self.assertIn("搬家", precision_stage({"d4_candidates_differ": True}, 2)["user_meaning"]) - self.assertNotIn("家人", precision_stage({"d4_candidates_differ": True}, 2)["user_meaning"]) - ready = precision_stage({}, 3) - self.assertEqual(ready["current"], "ready_to_adopt") - self.assertFalse(ready["unique_minute_claim"]) - - def test_precision_stage_uses_candidate_cluster_not_full_declared_range(self): - built = { - "static_contexts": [ - feature("12:00", d1=3, d9=1, d10=4), - feature("13:37", d1=4, d9=1, d10=4), - feature("15:50", d1=4, d9=1, d10=4), - feature("15:51", d1=4, d9=1, d10=4), - feature("16:03", d1=5, d9=1, d10=4), - ] - } - scan = window_scan(built) - self.assertEqual(scan["d1_lagna_count"], 3) - self.assertTrue(scan["d1_candidates_differ"]) - cluster = cluster_scan(built, ["15:50", "15:51"], "15:50", 14) - self.assertEqual(cluster["d1_lagna_count"], 1) - self.assertFalse(cluster["d1_candidates_differ"]) - packet = build_refinement_packet( - request_events(), - built, - representative_time="15:50", - candidate_times=["15:50", "15:51"], - cluster_width_minutes=14, - ) - self.assertEqual(packet["window_scan"]["d1_lagna_count"], 3) - self.assertNotEqual(packet["precision_stage"]["current"], "lagna_frame") - - def test_window_scan_reports_d24_and_fine_minute_changes_without_unique_claim(self): - scan = window_scan({ - "static_contexts": [ - feature("05:13", d1=1, d5=3, d24=4, pada=10, hora=2, ghati=6), - feature("05:14", d1=1, d5=3, d24=8, pada=11, hora=3, ghati=6), - ] - }) - self.assertEqual(scan["d24_lagna_count"], 2) - self.assertTrue(scan["d24_candidates_differ"]) - self.assertFalse(scan["d5_candidates_differ"]) - self.assertEqual(scan["pada_count"], 2) - self.assertTrue(scan["pada_candidates_differ"]) - self.assertTrue(scan["hora_candidates_differ"]) - self.assertFalse(scan["ghati_candidates_differ"]) - meanings = [item["user_meaning"] for item in scan["transitions"]] - self.assertIn("D24 在 05:14 发生变化", meanings) - self.assertIn("Nakshatra pada 在 05:14 发生变化", meanings) - self.assertIn("Hora Lagna 在 05:14 发生变化", meanings) - self.assertNotIn("Ghati Lagna 在 05:14 发生变化", meanings) - self.assertFalse(scan["unique_minute_claim"]) - self.assertFalse(scan["confirmation_allowed"]) - self.assertEqual(precision_stage(scan, 2)["current"], "d5_refine") - - def test_window_scan_reports_finance_health_and_bhava_without_delaying_adopt(self): - scan = window_scan({ - "static_contexts": [ - feature("05:13", d1=1, d2=2, d11=4, d30=6, bhava=1, hora=2, ghati=6, pranapada=8), - feature("05:14", d1=1, d2=3, d11=4, d30=7, bhava=2, hora=2, ghati=6, pranapada=8), - ] - }) - self.assertTrue(scan["d2_candidates_differ"]) - self.assertFalse(scan["d11_candidates_differ"]) - self.assertTrue(scan["d30_candidates_differ"]) - self.assertTrue(scan["bhava_candidates_differ"]) - self.assertFalse(scan["pranapada_candidates_differ"]) - meanings = [item["user_meaning"] for item in scan["transitions"]] - self.assertIn("D2 在 05:14 发生变化", meanings) - self.assertIn("D30 在 05:14 发生变化", meanings) - self.assertIn("Bhava Lagna 在 05:14 发生变化", meanings) - self.assertNotIn("Pranapada Lagna 在 05:14 发生变化", meanings) - self.assertEqual(precision_stage(scan, 2)["current"], "ready_to_adopt") - self.assertFalse(scan["unique_minute_claim"]) - pranapada_scan = window_scan({ - "static_contexts": [ - feature("05:13", d1=1, d11=4, pranapada=8), - feature("05:14", d1=1, d11=5, pranapada=9), - ] - }) - self.assertTrue(pranapada_scan["d11_candidates_differ"]) - self.assertTrue(pranapada_scan["pranapada_candidates_differ"]) - self.assertIn( - "Pranapada Lagna 在 05:14 发生变化", - [item["user_meaning"] for item in pranapada_scan["transitions"]], - ) - self.assertEqual(precision_stage(pranapada_scan, 2)["current"], "ready_to_adopt") - - def test_packet_ledger_oos_and_nakshatra_without_scores(self): - request = request_events() - built = { - "static_contexts": [ - feature("05:13", d1=1, d9=1, d10=4, degree=13.1), - feature("05:14", d1=2, d9=1, d10=4, degree=13.2), - ], - "matrix": { - request["events"][0]["id"]: { - "05:13": {"points": 6, "rule_ids": ["vim_md_domain_house", "narayana_md_domain_house"]}, - "05:14": {"points": 1, "rule_ids": ["no_domain_activation"]}, - }, - request["events"][1]["id"]: { - "05:13": {"points": 2, "rule_ids": ["vim_ad_domain_house"]}, - "05:14": {"points": 2, "rule_ids": ["vim_ad_domain_house"]}, - }, - request["events"][2]["id"]: { - "05:13": {"points": 0, "rule_ids": ["no_domain_activation"]}, - "05:14": {"points": 0, "rule_ids": ["no_domain_activation"]}, - }, - }, - } - packet = build_refinement_packet( - request, - built, - representative_time="05:13", - candidate_times=["05:13", "05:14"], - ) - self.assertEqual(packet["event_dasha_ledger"][0]["match"], "strong") - self.assertIn("入职", packet["event_dasha_ledger"][0]["user_meaning"]) - self.assertNotIn("points", str(packet["event_dasha_ledger"])) - self.assertEqual(packet["lagna_contrast"]["intervals"][0]["lagna"], "金牛座") - self.assertTrue(packet["nakshatra_boundary"]["near_boundary"]) - self.assertEqual(len(packet["nakshatra_boundary"]["options"][0]["traits"]), 1) - self.assertEqual(len(packet["nakshatra_boundary"]["options"][1]["traits"]), 1) - self.assertNotEqual( - packet["nakshatra_boundary"]["options"][0]["traits"][0], - packet["nakshatra_boundary"]["options"][1]["traits"][0], - ) - self.assertIn("A:", packet["nakshatra_boundary"]["user_meaning"]) - self.assertNotIn(";", packet["nakshatra_boundary"]["user_meaning"]) - self.assertEqual(packet["oos_blind_prompts"][0]["domain"], "finance") - self.assertFalse(packet["oos_blind_prompts"][0]["used_for_scoring"]) - self.assertFalse(packet["confirmation_allowed"]) - encoded = str(packet["window_scan"]) - self.assertIn("金牛座", encoded) - self.assertNotIn("热情冲动", encoded) - self.assertIn("事件吻合率", str(packet["event_fit_rate"])) - self.assertFalse(packet["event_fit_rate"]["unique_minute_claim"]) - self.assertEqual(packet["discriminating_event_probes"], []) - - def test_decision_receipt_downgrades_confidence_on_dasha_conflict(self): - request = request_events() - rows = [ - {"time": "05:13", "score": 20, "evidence": [], "missing_layers": []}, - {"time": "05:20", "score": 8, "evidence": [], "missing_layers": []}, - ] - decisions = build_candidate_decisions(rows, result_id="00000000-0000-4000-8000-000000000099") - built = { - "missing_layers": [], - "static_contexts": [feature("05:13", d1=1, d9=1, d10=4), feature("05:20", d1=2, d9=1, d10=4)], - "matrix": { - request["events"][0]["id"]: { - "05:13": {"points": 8, "rule_ids": ["vim_md_domain_house"]}, - "05:20": {"points": 1, "rule_ids": ["vim_ad_domain_house"]}, - }, - request["events"][1]["id"]: { - "05:13": {"points": 1, "rule_ids": ["narayana_ad_domain_house"]}, - "05:20": {"points": 9, "rule_ids": ["narayana_md_domain_house"]}, - }, - request["events"][2]["id"]: { - "05:13": {"points": 1, "rule_ids": ["vim_md_domain_varga"]}, - "05:20": {"points": 1, "rule_ids": ["vim_md_domain_varga"]}, - }, - }, - } - diagnostics = { - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "primary_secondary_margin_percent": 50, - } - receipt = build_decision_receipt(request, decisions, built, diagnostics) - self.assertTrue(receipt["acceptance_allowed"]) - self.assertFalse(receipt["confirmation_allowed"]) - self.assertEqual(receipt["overall_confidence"], "medium") - self.assertIn("vimshottari_narayana_conflict", receipt["reasons"]) - self.assertEqual(receipt["dasha_agreement"]["status"], "conflict") - self.assertEqual(receipt["event_dasha_ledger"][0]["match_label"], "强相关") - self.assertTrue(any(row["technique"] == "唯一分钟确认" and row["status"] == "blocked" for row in receipt["technique_audit_table"])) - self.assertTrue(any(row["technique"] == "VedAstro 分钟级校验" and row["status"] == "blocked" for row in receipt["technique_audit_table"])) - self.assertFalse(receipt["unique_minute_claim"]) - - def test_same_cluster_dasha_peaks_agree_without_opening_confirmation(self): - request = request_events() - rows = [ - {"time": "04:54", "score": 20, "evidence": [], "missing_layers": []}, - {"time": "04:59", "score": 18, "evidence": [], "missing_layers": []}, - ] - contexts = [ - feature("04:54", d1=1, d9=1, d10=4), - feature("04:59", d1=1, d9=1, d10=4), - ] - decisions = build_candidate_decisions( - rows, - result_id="00000000-0000-4000-8000-000000000099", - static_contexts=contexts, - ) - built = { - "missing_layers": [], - "static_contexts": contexts, - "candidate_times": ["04:54", "04:59"], - "matrix": { - request["events"][0]["id"]: { - "04:54": {"points": 8, "rule_ids": ["vim_md_domain_house"]}, - "04:59": {"points": 1, "rule_ids": ["vim_ad_domain_house"]}, - }, - request["events"][1]["id"]: { - "04:54": {"points": 1, "rule_ids": ["narayana_ad_domain_house"]}, - "04:59": {"points": 9, "rule_ids": ["narayana_md_domain_house"]}, - }, - request["events"][2]["id"]: { - "04:54": {"points": 1, "rule_ids": ["vim_md_domain_varga"]}, - "04:59": {"points": 1, "rule_ids": ["vim_md_domain_varga"]}, - }, - }, - } - diagnostics = { - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "primary_secondary_margin_percent": 50, - } - receipt = build_decision_receipt(request, decisions, built, diagnostics) - self.assertEqual(receipt["dasha_agreement"]["status"], "agree") - self.assertNotIn("vimshottari_narayana_conflict", receipt["reasons"]) - self.assertFalse(receipt["confirmation_allowed"]) - width = receipt["gates"]["exact_confirmation"]["indistinguishable_width_minutes"] - self.assertGreaterEqual(width, 6) - - def test_receipt_recasts_house_tables_per_candidate_and_blocks_unique_minute(self): - request = request_events() - rows = [ - {"time": "05:13", "score": 20, "evidence": [], "missing_layers": []}, - {"time": "05:14", "score": 8, "evidence": [], "missing_layers": []}, - ] - decisions = build_candidate_decisions(rows, result_id="00000000-0000-4000-8000-000000000099") - chart_a = {"ascendant": {"sign": "Taurus", "lon": 40.0}, "planets": {"Sun": {"sign": "Aries", "house": 12}}} - chart_b = {"ascendant": {"sign": "Gemini", "lon": 70.0}, "planets": {"Sun": {"sign": "Aries", "house": 11}}} - built = { - "missing_layers": [], - "static_contexts": [ - {**feature("05:13", d1=1, d9=1, d10=4), "chart": chart_a}, - {**feature("05:14", d1=2, d9=1, d10=4), "chart": chart_b}, - ], - "matrix": { - request["events"][0]["id"]: { - "05:13": {"points": 8, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["d1-rashi", "d10-dashamsa"]}, - "05:14": {"points": 1, "rule_ids": ["vim_ad_domain_house"], "technique_layers": ["d1-rashi", "d10-dashamsa"]}, - }, - request["events"][1]["id"]: { - "05:13": {"points": 1, "rule_ids": ["narayana_ad_domain_house"], "technique_layers": ["d1-rashi", "d9-navamsa"]}, - "05:14": {"points": 9, "rule_ids": ["narayana_md_domain_house"], "technique_layers": ["d1-rashi", "d9-navamsa"]}, - }, - request["events"][2]["id"]: { - "05:13": {"points": 1, "rule_ids": ["vim_md_domain_varga"], "technique_layers": ["d1-rashi", "d5-panchamsha"]}, - "05:14": {"points": 1, "rule_ids": ["vim_md_domain_varga"], "technique_layers": ["d1-rashi", "d5-panchamsha"]}, - }, - }, - } - receipt = build_decision_receipt(request, decisions, built, { - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "primary_secondary_margin_percent": 50, - }) - self.assertEqual(receipt["house_table"]["time"], "05:13") - self.assertEqual(receipt["house_table"]["lagna"], "金牛座") - self.assertEqual(receipt["house_tables_by_time"]["05:14"]["lagna"], "双子座") - self.assertEqual(receipt["natal_recast"]["time"], "05:13") - self.assertFalse(receipt["natal_recast"]["unique_minute_claim"]) - self.assertFalse(receipt["confirmation_allowed"]) - techniques = {row["technique"]: row["status"] for row in receipt["technique_audit_table"]} - self.assertEqual(techniques["D1 本命盘"], "executed") - self.assertEqual(techniques["D5 成就分盘"], "executed") - self.assertEqual(techniques["KP 宫头"], "blocked") - self.assertEqual(techniques["唯一分钟确认"], "blocked") - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rectification_relative_support.py b/tests/test_rectification_relative_support.py deleted file mode 100644 index 2dac05061..000000000 --- a/tests/test_rectification_relative_support.py +++ /dev/null @@ -1,71 +0,0 @@ -from __future__ import annotations - -import unittest -from decimal import Decimal - -from scripts.rectification.decision_policy import ( - POLICY_VERSION, - RELATIVE_SUPPORT_MODE, - _relative_support, - build_candidate_decisions, -) -from scripts.rectification.scoring_service import ALGORITHM_VERSION - - -def _row(time: str, score: float) -> dict: - return {"time": time, "score": score, "evidence": [], "missing_layers": []} - - -class RelativeSupportScaleTest(unittest.TestCase): - def test_holdout_gate_keeps_proportional_default(self) -> None: - # 原值: policy-v3;新值: policy-v4;原因: R1 区间门槛 4 件 3 域(BUG-1193),相对支持口径不变。 - self.assertEqual(POLICY_VERSION, "rectification-candidate-policy-v4") - # Explicit date windows: scoring identity -8 -> -9, not a prior/policy change. - # 原值: -11;新值: -12;原因: 章动修正改变同输入分数(BUG-1275),策略 v4 与相对支持口径不变。 - # 原值: -12;新值: -13;原因: D30 偶数星座与白羊 / 天蝎金星功能凶改变同输入分数(BUG-1560 / BUG-1570),策略 v4 与相对支持口径不变。 - # 原值: -13;新值: -14;原因: 同输入分数变了(#166 占星师裁定:Shadbala Sthana / Drik 按具名 BPHS 口径、jaimini.py Arudha 例外从初算落点数,BUG-1583~1588),策略 v4 与相对支持口径不变。 - # 原值: -14;新值: -15;原因: #166 第二批(第 4 条:双子 / 处女上升土星改为混合,BUG-1590)改变同输入分数,策略 v4 不变。 - self.assertEqual(ALGORITHM_VERSION, "rectification-v5-matrix-scoring-15") - self.assertEqual(RELATIVE_SUPPORT_MODE, "proportional") - - def test_offset_top_two_lead_is_at_least_proportional(self) -> None: - scores = [ - Decimal("15.52"), Decimal("15.40"), Decimal("14.10"), Decimal("13.00"), - Decimal("12.50"), Decimal("12.00"), Decimal("11.80"), Decimal("11.50"), - Decimal("11.40"), Decimal("11.20"), Decimal("11.10"), Decimal("10.96"), - ] - floor = min(scores) - proportional = _relative_support(scores, floor=floor, mode="proportional") - offset = _relative_support(scores, floor=floor, mode="offset") - prop_lead = sorted(proportional, reverse=True) - offset_lead = sorted(offset, reverse=True) - self.assertGreaterEqual(offset_lead[0] - offset_lead[1], prop_lead[0] - prop_lead[1]) - self.assertEqual(sum(offset), 100) - self.assertEqual(sum(proportional), 100) - - def test_equal_scores_split_evenly_for_offset_and_proportional(self) -> None: - scores = [Decimal("12")] * 12 - expected = _relative_support(scores, floor=Decimal("12"), mode="proportional") - offset = _relative_support(scores, floor=Decimal("12"), mode="offset") - self.assertEqual(offset, expected) - self.assertEqual(sum(offset), 100) - self.assertTrue(all(value in {8, 9} for value in offset)) - - def test_build_candidate_decisions_offset_lead_beats_proportional_on_spaced_grid(self) -> None: - scores = [ - 15.52, 15.40, 14.10, 13.00, 12.50, 12.00, - 11.80, 11.50, 11.40, 11.20, 11.10, 10.96, - ] - rows = [_row(f"05:{index * 5:02d}", score) for index, score in enumerate(scores)] - proportional = build_candidate_decisions(rows, result_id="00000000-0000-4000-8000-000000000001", support_mode="proportional") - offset = build_candidate_decisions(rows, result_id="00000000-0000-4000-8000-000000000001", support_mode="offset") - self.assertEqual(len(proportional), 12) - self.assertEqual(len(offset), 12) - prop_lead = proportional[0]["relative_support"] - proportional[1]["relative_support"] - offset_lead = offset[0]["relative_support"] - offset[1]["relative_support"] - self.assertGreaterEqual(offset_lead, prop_lead) - self.assertEqual(sum(item["relative_support"] for item in offset), 100) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rectification_v5_services.py b/tests/test_rectification_v5_services.py deleted file mode 100644 index 4703c122b..000000000 --- a/tests/test_rectification_v5_services.py +++ /dev/null @@ -1,1302 +0,0 @@ -from __future__ import annotations - -import unittest -from datetime import date, datetime -from unittest.mock import patch -from uuid import UUID - -from scripts.active_rectification_event_engine import _candidate_datetimes -from scripts.jyotish_api_server import ( - API_COMMAND_MAP, - TECHNIQUE_EXAMPLE_ENDPOINTS, - BadRequest, - JyotishAPIHandler, -) -from scripts.rectification.api_service import diagnostics, score_candidates -from scripts.rectification.candidate_contrast import ( - MAX_PUBLIC_CLUSTERS, - select_signature_representatives, -) -from scripts.rectification.contracts import normalize_rectification_request -from scripts.rectification.decision_policy import build_candidate_decisions -from scripts.rectification.scoring_service import ( - build_event_contribution_matrix, - calculation_spec, - sample_event_dates, - score_from_matrix, - sha256, -) - -EVENT_ID = "00000000-0000-4000-8000-000000000001" - - -def event(index: int, domain: str, event_kind: str, *, precision: str = "day"): - return { - "id": f"00000000-0000-4000-8000-{index:012d}", - "domain": domain, - "event_kind": event_kind, - "date_start": "2016-09-15", - "date_end": "2016-09-15", - "precision": precision, - "summary": event_kind, - } - - -def request( - *, - precision: str = "month", - event_kind: str = "education_milestone", - domain: str = "education", - start_time: str = "05:13", - end_time: str = "05:15", - date_start: str = "2016-09-01", - date_end: str = "2016-09-30", -): - return { - "birth_date": "1997-08-08", - "start_time": start_time, - "end_time": end_time, - "lat": 36.419, - "lon": 114.213, - "tz": 8, - "events": [{ - "id": EVENT_ID, - "domain": domain, - "event_kind": event_kind, - "date_start": date_start, - "date_end": date_end, - "precision": precision, - "summary": "大学入学", - }], - } - - -class RectificationV5ServicesTest(unittest.TestCase): - def test_event_contract_v2_accepts_native_kinds_and_retains_background_events(self): - supported = { - "education": ("education_start", "education_completion", "education_interruption", "education_change"), - "career": ("career_entry", "career_change", "promotion", "career_pressure", "career_exit", "business_start"), - "relationship": ("relationship_start", "relationship_commitment", "relationship_separation", "relationship_end"), - "relocation": ("relocation", "foreign_move", "return", "home_change"), - "finance": ("finance_gain", "finance_loss", "income_change", "asset_change"), - "health": ("self_health_event", "pressure_period"), - "family": ("family_event",), - "appearance": ("appearance_note",), - "marks": ("birthmark_or_scar",), - "occupation": ("occupation_note",), - "horary": ("horary_query",), - "other": ("other",), - } - - for domain, kinds in supported.items(): - for event_kind in kinds: - normalized = normalize_rectification_request( - request(domain=domain, event_kind=event_kind), - today=date(2026, 7, 28), - ) - self.assertEqual(normalized["events"][0]["domain"], domain) - self.assertEqual(normalized["events"][0]["event_kind"], event_kind) - - def test_event_contract_v2_preserves_server_provenance_and_enforces_self_scoring(self): - body = request(domain="career", event_kind="career_entry") - body["events"][0].update({ - "source_turn_id": "33333333-3333-4333-8333-333333333333", - "subject": "self", - "date_source": "user_quote", - "date_reliability": "month_exact", - "date_corroboration": "劳动合同", - "date_conflict_status": "none", - }) - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - event_value = normalized["events"][0] - self.assertEqual(event_value["source_turn_id"], "33333333-3333-4333-8333-333333333333") - self.assertEqual(event_value["subject"], "self") - self.assertEqual(event_value["date_source"], "user_quote") - self.assertEqual(event_value["date_reliability"], "month_exact") - self.assertEqual(event_value["date_corroboration"], "劳动合同") - self.assertEqual(event_value["date_conflict_status"], "none") - - body["events"][0]["subject"] = "family" - with self.assertRaisesRegex(ValueError, "subject must be self for scoreable events"): - normalize_rectification_request(body, today=date(2026, 7, 28)) - - def test_background_only_events_are_retained_without_invoking_the_scoring_engine(self): - body = request() - body["events"] = [ - event(2, "other", "other", precision="year"), - event(3, "horary", "horary_query", precision="day"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - - def fail_if_called(_request): - self.fail("background events must not reach the scoring engine") - - built = build_event_contribution_matrix(normalized, row_provider=fail_if_called) - - self.assertEqual(built["candidate_times"], []) - self.assertEqual(built["matrix"], {}) - self.assertEqual(built["date_sensitivity"], []) - - def test_family_events_are_scoreable_and_reach_the_engine(self): - body = request() - body["events"] = [event(1, "family", "family_event")] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - seen = [] - - def rows(value): - seen.append(value["events"][0]["domain"]) - event_value = value["events"][0] - return [{ - "time": "05:13", - "score": 4, - "evidence": [{ - "event_id": event_value["id"], - "domain": event_value["domain"], - "candidate_time": "05:13", - "rule_ids": ["vim_md_domain_house", "d1-rashi", "d12-dwadashamsha"], - "points": 4, - }], - "missing_layers": [], - }] - - built = build_event_contribution_matrix(normalized, row_provider=rows) - self.assertEqual(seen, ["family"]) - self.assertEqual(built["matrix"][normalized["events"][0]["id"]]["05:13"]["technique_layers"], [ - "d1-rashi", "d12-dwadashamsha", "d3-drekkana", "d7-saptamsha", "vim_md_domain_house", - ]) - - def test_declared_date_precision_changes_real_contribution_weight(self): - def rows(value): - event = value["events"][0] - return [{ - "time": "05:13", - "score": 10, - "evidence": [{ - "event_id": event["id"], - "domain": event["domain"], - "candidate_time": "05:13", - "rule_ids": ["vim_md_domain_house"], - "points": 10, - }], - "missing_layers": [], - }] - - cases = { - "day": request(precision="day", event_kind="education_start", date_start="2016-09-15", date_end="2016-09-15"), - "month": request(precision="month", event_kind="education_start"), - "year": request( - precision="year", - event_kind="education_start", - date_start="2016-01-01", - date_end="2016-12-31", - ), - } - points = {} - for precision, body in cases.items(): - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - built = build_event_contribution_matrix(normalized, row_provider=rows) - points[precision] = built["matrix"][EVENT_ID]["05:13"]["points"] - - self.assertEqual(points, {"day": 10, "month": 8, "year": 5}) - - def test_calculation_spec_hash_matches_typescript_for_integral_timezone(self): - normalized = normalize_rectification_request(request(), today=date(2026, 7, 28)) - self.assertEqual( - sha256(calculation_spec(normalized)), - "d68a59ae345a87bcdf7ad45fee913d3aca02c553f896ce6c173a8bd4ab327af3", - ) - - def test_cross_midnight_range_preserves_next_day_datetimes_and_typescript_hash(self): - normalized = normalize_rectification_request( - request(start_time="23:00", end_time="03:59"), - today=date(2026, 7, 28), - ) - - candidates = _candidate_datetimes(normalized) - - self.assertEqual(len(candidates), 300) - self.assertEqual(candidates[0].isoformat(), "1997-08-08T23:00:00") - self.assertEqual(candidates[60].isoformat(), "1997-08-09T00:00:00") - self.assertEqual(candidates[-1].isoformat(), "1997-08-09T03:59:00") - self.assertEqual( - sha256(calculation_spec(normalized)), - "1923a1ee2fa873f1a26c97b23d05cfee38ec38071b60076a014ad17b2844cedd", - ) - - def test_candidate_range_boundaries_stay_bounded_and_equal_is_one_minute(self): - full_day = normalize_rectification_request( - request(start_time="00:00", end_time="23:59"), - today=date(2026, 7, 28), - ) - equal = normalize_rectification_request( - request(start_time="05:13", end_time="05:13"), - today=date(2026, 7, 28), - ) - - self.assertEqual(len(_candidate_datetimes(full_day)), 1_440) - self.assertEqual(len(_candidate_datetimes(equal)), 1) - with self.assertRaisesRegex(ValueError, "end_time must be HH:MM"): - normalize_rectification_request( - request(start_time="00:00", end_time="24:00"), - today=date(2026, 7, 28), - ) - - def test_daytime_candidate_range_remains_on_birth_date(self): - normalized = normalize_rectification_request(request(), today=date(2026, 7, 28)) - - candidates = _candidate_datetimes(normalized) - - self.assertEqual([value.isoformat() for value in candidates], [ - "1997-08-08T05:13:00", - "1997-08-08T05:14:00", - "1997-08-08T05:15:00", - ]) - - def test_shared_validator_retains_background_events_and_rejects_non_self_health(self): - background = normalize_rectification_request( - request(domain="family", event_kind="family_event"), today=date(2026, 7, 28) - ) - self.assertEqual(background["events"][0]["event_kind"], "family_event") - with self.assertRaisesRegex(ValueError, "event_kind does not match domain"): - normalize_rectification_request( - request(domain="family", event_kind="family_bereavement"), today=date(2026, 7, 28) - ) - with self.assertRaisesRegex(ValueError, "event_kind does not match domain"): - normalize_rectification_request(request(domain="health_pressure", event_kind="family_health_event"), today=date(2026, 7, 28)) - normalized = normalize_rectification_request(request(domain="health_pressure", event_kind="self_health_event"), today=date(2026, 7, 28)) - self.assertEqual(normalized["events"][0]["event_kind"], "self_health_event") - - def test_relationship_end_is_native_and_uses_pressure_semantics(self): - normalized = normalize_rectification_request( - request(domain="relationship", event_kind="relationship_end", precision="day"), - today=date(2026, 7, 28), - ) - - def rows(value): - event_value = value["events"][0] - return [{ - "time": "05:13", "score": 10, - "evidence": [{ - "event_id": EVENT_ID, "domain": "relationship", "candidate_time": "05:13", - "rule_ids": ["controlled_transit_saturn_domain_house", f"event_kind:{event_value['event_kind']}"], - "points": 10, - }], - "missing_layers": [], - }] - - built = build_event_contribution_matrix(normalized, row_provider=rows) - contribution = built["matrix"][EVENT_ID]["05:13"] - self.assertIn("event_kind_profile:relationship_end:pressure", contribution["rule_ids"]) - self.assertGreater(contribution["points"], 10) - - def test_relationship_start_and_change_use_distinct_rule_conditioned_profiles(self): - def relationship_rows(_value): - return [ - { - "time": "05:13", "score": 10, - "evidence": [{ - "event_id": EVENT_ID, "domain": "relationship", "candidate_time": "05:13", - "rule_ids": ["vim_md_domain_house", "vim_ad_functional_benefic_auxiliary"], - "points": 10, - }], - "missing_layers": [], - }, - { - "time": "05:14", "score": 9, - "evidence": [{ - "event_id": EVENT_ID, "domain": "relationship", "candidate_time": "05:14", - "rule_ids": ["controlled_transit_saturn_domain_house", "vim_ad_functional_malefic_auxiliary"], - "points": 9, - }], - "missing_layers": [], - }, - ] - - start = normalize_rectification_request( - request(domain="relationship", event_kind="relationship_start"), today=date(2026, 7, 28) - ) - change = normalize_rectification_request( - request(domain="relationship", event_kind="relationship_change"), today=date(2026, 7, 28) - ) - - start_matrix = build_event_contribution_matrix(start, row_provider=relationship_rows) - change_matrix = build_event_contribution_matrix(change, row_provider=relationship_rows) - - self.assertGreater(start_matrix["matrix"][EVENT_ID]["05:13"]["points"], start_matrix["matrix"][EVENT_ID]["05:14"]["points"] ) - self.assertGreater(change_matrix["matrix"][EVENT_ID]["05:14"]["points"], change_matrix["matrix"][EVENT_ID]["05:13"]["points"] ) - self.assertEqual(change_matrix["date_sensitivity"][0]["sample_winners"], ["05:14", "05:14", "05:14"]) - self.assertNotIn("event_kind_profile", change_matrix["matrix"][EVENT_ID]["05:14"]["technique_layers"]) - - def test_relationship_kind_profile_does_not_create_points_without_activation(self): - normalized = normalize_rectification_request( - request(domain="relationship", event_kind="relationship_change", precision="day"), - today=date(2026, 7, 28), - ) - - def rows(_value): - return [{ - "time": "05:13", "score": 0, - "evidence": [{ - "event_id": EVENT_ID, "domain": "relationship", "candidate_time": "05:13", - "rule_ids": ["no_domain_activation", "event_kind:relationship_change"], - "points": 0, - }], - "missing_layers": [], - }] - - built = build_event_contribution_matrix(normalized, row_provider=rows) - self.assertEqual(built["matrix"][EVENT_ID]["05:13"]["points"], 0) - - def test_date_sampling_preserves_declared_range_and_uses_bounded_samples(self): - base = request()["events"][0] - self.assertEqual(sample_event_dates({**base, "precision": "month"}), ["2016-09-01", "2016-09-15", "2016-09-30"]) - year = {**base, "precision": "year", "date_start": "2016-01-01", "date_end": "2016-12-31"} - self.assertEqual(len(sample_event_dates(year)), 12) - ranged = {**base, "precision": "range", "date_start": "2015-01-01", "date_end": "2016-12-31"} - self.assertLessEqual(len(sample_event_dates(ranged)), 12) - - def test_contribution_matrix_and_leave_out_diagnostics_use_matrix_math(self): - normalized = normalize_rectification_request(request(), today=date(2026, 7, 28)) - - def rows(value): - sampled = value["events"][0]["date"] - shift = {"2016-09-01": 0, "2016-09-15": 1, "2016-09-30": 2}[sampled] - return [{ - "time": candidate, - "score": points + shift, - "evidence": [{ - "event_id": EVENT_ID, - "domain": "education", - "candidate_time": candidate, - "rule_ids": ["D24:test"], - "points": points + shift, - }], - "missing_layers": ["KP_cusps"], - } for candidate, points in [("05:13", 9), ("05:14", 10), ("05:15", 8)]] - - built = build_event_contribution_matrix(normalized, row_provider=rows) - scored = score_from_matrix(normalized, built) - self.assertEqual(built["matrix"][EVENT_ID]["05:14"]["points"], 8.8) - self.assertEqual(scored[1]["score"], 8.8) - self.assertEqual(built["missing_layers"], ["KP_cusps"]) - - def test_formal_score_and_diagnostics_endpoints_share_the_service_bundle(self): - normalized = normalize_rectification_request(request(), today=date(2026, 7, 28)) - built = { - "candidate_times": ["05:13", "05:14"], - "matrix": {EVENT_ID: { - "05:13": {"points": 10, "rule_ids": ["D24:a"], "technique_layers": ["D24"]}, - "05:14": {"points": 8, "rule_ids": ["D24:b"], "technique_layers": ["D24"]}, - }}, - "date_sensitivity": [{ - "event_id": EVENT_ID, - "declared_date_range": {"start": "2016-09-01", "end": "2016-09-30", "precision": "month"}, - "sample_dates": ["2016-09-01", "2016-09-15", "2016-09-30"], - "winner_retention_rate": 1, - "score_variance": 1, - "sample_winners": ["05:13", "05:13", "05:13"], - }], - "missing_layers": ["KP_cusps"], - "static_contexts": [{"feature": {"time": "05:13"}}, {"feature": {"time": "05:14"}}], - } - feature = { - "calculation_spec_hash": "0" * 64, - "algorithm_version": "rectification-v5-matrix-scoring-2", - "candidate_count": 2, - "feature_hash": "1" * 64, - "features": [{"time": "05:13"}, {"time": "05:14"}], - } - with patch("scripts.rectification.api_service.build_event_contribution_matrix", return_value=built), patch( - "scripts.rectification.api_service.build_candidate_feature_snapshot", return_value=feature - ): - scored = score_candidates(normalized) - diagnostic_result = diagnostics(normalized) - self.assertFalse(scored["can_confirm_exact_minute"]) - # 原值: assertIn("event_contribution_matrix", scored) - # 新值: 默认 assertNotIn;include_internal=True 时仍在 - # 原因: BUG-1325,前台没有读取点,默认响应不再带内部矩阵 - self.assertNotIn("event_contribution_matrix", scored) - self.assertNotIn("candidate_decision_receipt", scored) - internal = score_candidates(normalized, include_internal=True) - self.assertIn("event_contribution_matrix", internal) - self.assertIn("candidate_decision_receipt", internal) - self.assertEqual(diagnostic_result["diagnostics"]["leave_one_event_out_retention_rate"], 1) - self.assertFalse(diagnostic_result["can_confirm_exact_minute"]) - - def test_score_endpoint_returns_candidate_decision_receipt_v2_and_real_execution_ledger(self): - body = request() - body["events"] = [ - event(1, "education", "education_start"), - event(2, "career", "promotion", precision="month"), - event(3, "finance", "finance_gain"), - event(5, "family", "family_event"), - event(4, "other", "other", precision="year"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - scored_ids = [item["id"] for item in normalized["events"] if item["domain"] != "other"] - built = { - "candidate_times": ["05:13", "05:14", "05:15"], - "matrix": { - event_id: { - "05:13": {"points": 4, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]}, - "05:14": {"points": 2, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]}, - "05:15": {"points": 1, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]}, - } - for event_id in scored_ids - }, - "date_sensitivity": [ - { - "event_id": event_id, - "declared_date_range": {"start": "2016-09-15", "end": "2016-09-15", "precision": "day"}, - "sample_dates": ["2016-09-15"], - "winner_retention_rate": 1, - "score_variance": 0, - "sample_winners": ["05:13"], - } - for event_id in scored_ids - ], - "missing_layers": [], - "static_contexts": [], - } - diagnostic_values = { - "primary_cluster_retention_rate": 1, - "leave_one_event_out_retention_rate": .9, - "leave_one_domain_out_retention_rate": .9, - "date_sensitivity_retention_rate": .9, - "neighbor_support_minutes": 1, - "primary_secondary_margin_percent": 30, - "event_date_sensitivity": built["date_sensitivity"], - } - feature = { - "calculation_spec_hash": "0" * 64, - "algorithm_version": "rectification-v5-matrix-scoring-2", - "candidate_count": 3, - "feature_hash": "1" * 64, - "features": [], - } - with patch("scripts.rectification.api_service.build_event_contribution_matrix", return_value=built), patch( - "scripts.rectification.api_service.build_candidate_feature_snapshot", return_value=feature - ), patch("scripts.rectification.api_service.run_diagnostics", return_value=diagnostic_values): - first = score_candidates(normalized) - second = score_candidates(normalized) - - self.assertEqual(first["event_contract_version"], "rectification-event-contract-v2") - self.assertEqual(first["candidate_decisions"], second["candidate_decisions"]) - self.assertEqual(sum(item["relative_support"] for item in first["candidate_decisions"]), 100) - for rank, candidate in enumerate(first["candidate_decisions"], start=1): - self.assertEqual(set(candidate), { - "candidate_id", - "rank", - "time", - "relative_support", - "tied_minute_count", - "cluster_times", - "cluster_start", - "cluster_end", - }) - self.assertEqual(candidate["rank"], rank) - UUID(candidate["candidate_id"]) - - # 原值: first["candidate_decision_receipt"] - # 新值: first["decision_receipt"](同一个对象) - # 原因: BUG-1325,默认响应不再重复挂回执 - receipt = first["decision_receipt"] - self.assertEqual(receipt["receipt_version"], "candidate-decision-receipt-v2") - self.assertTrue(receipt["selection_allowed"]) - self.assertTrue(receipt["acceptance_allowed"]) - self.assertFalse(receipt["confirmation_allowed"]) - self.assertTrue(receipt["gates"]["domain_diversity"]["passed"]) - self.assertTrue(receipt["gates"]["date_quality"]["passed"]) - self.assertTrue(receipt["gates"]["exact_confirmation"]["fail_closed"]) - self.assertEqual(receipt["gates"]["exact_confirmation"]["external_validation_status"], "not_evaluated") - self.assertNotEqual(receipt["gates"]["exact_confirmation"]["external_validation_status"], "fail") - - self.assertEqual(first["decision_receipt"], receipt) - # 原值: policy-v3(C2 holdout 校准默认仍 proportional,未 bump);新值: policy-v4;原因: R1 区间门槛 3 件 2 域 → 4 件 3 域(BUG-1193) - self.assertEqual(first["decision_policy_version"], "rectification-candidate-policy-v4") - self.assertTrue(receipt["display_allowed"]) - self.assertTrue(receipt["accept_allowed"]) - self.assertFalse(receipt["confirm_allowed"]) - self.assertIsNotNone(receipt["representative_candidate_id"]) - self.assertEqual(receipt["representative_time"], "05:13") - - entries = first["execution_ledger"] - background = next(item for item in entries if item.get("event_id") == normalized["events"][4]["id"]) - self.assertEqual(background["status"], "retained_not_scored") - executed = next(item for item in entries if item.get("event_id") == normalized["events"][0]["id"]) - self.assertEqual(executed["technique_layers"], ["vim_md_domain_house"]) - - def test_diagnostics_endpoint_mirrors_candidate_decision_policy_fields(self): - normalized = normalize_rectification_request(request(), today=date(2026, 7, 28)) - scored = { - "result_id": "00000000-0000-4000-8000-000000000099", - "algorithm_version": "rectification-v5-matrix-scoring-2", - "event_contract_version": "rectification-event-contract-v2", - "decision_policy_version": "rectification-candidate-policy-v2", - "calculation_spec_hash": "0" * 64, - "candidate_decisions": [], - "candidate_decision_receipt": {}, - "decision_receipt": {}, - "execution_ledger_version": "rectification-execution-ledger-v2", - "execution_ledger": [], - "diagnostics": {}, - "missing_layers": [], - "display_allowed": False, - "selection_allowed": False, - "acceptance_allowed": False, - "propose_allowed": False, - "confirmation_allowed": False, - "representative_candidate_id": None, - "representative_time": None, - "overall_confidence": "low", - "margin_percent": 0.0, - } - with patch("scripts.rectification.api_service.score_candidates", return_value=scored): - result = diagnostics(normalized) - - for field in ( - "display_allowed", - "selection_allowed", - "acceptance_allowed", - "propose_allowed", - "confirmation_allowed", - "representative_candidate_id", - "representative_time", - "overall_confidence", - "margin_percent", - ): - self.assertEqual(result[field], scored[field]) - self.assertFalse(result["can_confirm_exact_minute"]) - - def test_single_domain_or_quantized_top_tie_blocks_candidate_acceptance(self): - body = request() - body["events"] = [ - event(1, "career", "career_entry"), - event(2, "career", "promotion"), - event(3, "career", "career_change"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - built = { - "candidate_times": ["05:13", "05:14"], - "matrix": { - item["id"]: { - "05:13": {"points": 3.333346, "rule_ids": ["D10:test"], "technique_layers": ["D10"]}, - "05:14": {"points": 3.333333, "rule_ids": ["D10:test"], "technique_layers": ["D10"]}, - } - for item in normalized["events"] - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - diagnostic_values = { - "primary_cluster_retention_rate": 1, - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "neighbor_support_minutes": 1, - "primary_secondary_margin_percent": 50, - } - with patch("scripts.rectification.api_service.build_event_contribution_matrix", return_value=built), patch( - "scripts.rectification.api_service.build_candidate_feature_snapshot", return_value={} - ), patch("scripts.rectification.api_service.run_diagnostics", return_value=diagnostic_values): - result = score_candidates(normalized) - - # 原值: result["candidate_decision_receipt"];新值: result["decision_receipt"];原因: BUG-1325 - receipt = result["decision_receipt"] - self.assertFalse(receipt["acceptance_allowed"]) - self.assertIn("insufficient_domain_diversity", receipt["reasons"]) - self.assertIn("tied_top_score", receipt["reasons"]) - self.assertIn("tied_top_score", receipt["confirmation_reasons"]) - self.assertNotIn("tied_top_score", receipt["acceptance_reasons"]) - self.assertEqual(result["candidate_decisions"][0]["tied_minute_count"], 2) - self.assertEqual(receipt["tie_policy"]["score_quantum"], .0001) - self.assertEqual(receipt["tie_policy"]["absolute_tolerance"], .0001) - - def test_two_domain_quantized_top_tie_allows_adoption_but_blocks_confirmation(self): - body = request() - body["events"] = [ - event(1, "career", "career_entry"), - event(2, "career", "promotion"), - event(3, "education", "education_start"), - event(4, "family", "family_event"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - built = { - "candidate_times": ["05:13", "05:14"], - "matrix": { - item["id"]: { - "05:13": {"points": 3.333346, "rule_ids": ["D10:test"], "technique_layers": ["D10"]}, - "05:14": {"points": 3.333333, "rule_ids": ["D10:test"], "technique_layers": ["D10"]}, - } - for item in normalized["events"] - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - diagnostic_values = { - "primary_cluster_retention_rate": 1, - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "neighbor_support_minutes": 1, - "primary_secondary_margin_percent": 50, - } - with patch("scripts.rectification.api_service.build_event_contribution_matrix", return_value=built), patch( - "scripts.rectification.api_service.build_candidate_feature_snapshot", return_value={} - ), patch("scripts.rectification.api_service.run_diagnostics", return_value=diagnostic_values): - result = score_candidates(normalized) - - # 原值: result["candidate_decision_receipt"];新值: result["decision_receipt"];原因: BUG-1325 - receipt = result["decision_receipt"] - self.assertTrue(receipt["acceptance_allowed"]) - self.assertTrue(receipt["selection_allowed"]) - self.assertFalse(receipt["confirmation_allowed"]) - self.assertIn("tied_top_score", receipt["confirmation_reasons"]) - self.assertNotIn("tied_top_score", receipt["acceptance_reasons"]) - self.assertEqual(result["candidate_decisions"][0]["tied_minute_count"], 2) - self.assertFalse(result["can_confirm_exact_minute"]) - - def test_low_date_quality_blocks_acceptance_even_with_multiple_domains_and_a_unique_candidate(self): - body = request() - body["events"] = [ - event(1, "education", "education_start", precision="year"), - event(2, "career", "promotion", precision="year"), - event(3, "finance", "finance_gain", precision="year"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - built = { - "candidate_times": ["05:13", "05:14"], - "matrix": { - item["id"]: { - "05:13": {"points": 4, "rule_ids": ["test"], "technique_layers": ["test"]}, - "05:14": {"points": 1, "rule_ids": ["test"], "technique_layers": ["test"]}, - } - for item in normalized["events"] - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - diagnostic_values = { - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "primary_secondary_margin_percent": 50, - } - with patch("scripts.rectification.api_service.build_event_contribution_matrix", return_value=built), patch( - "scripts.rectification.api_service.build_candidate_feature_snapshot", return_value={} - ), patch("scripts.rectification.api_service.run_diagnostics", return_value=diagnostic_values): - result = score_candidates(normalized) - - # 原值: result["candidate_decision_receipt"];新值: result["decision_receipt"];原因: BUG-1325 - receipt = result["decision_receipt"] - self.assertTrue(result["candidate_decisions"]) - self.assertFalse(receipt["acceptance_allowed"]) - self.assertFalse(receipt["gates"]["date_quality"]["passed"]) - self.assertIn("low_date_quality", receipt["reasons"]) - self.assertFalse(result["can_confirm_exact_minute"]) - - def test_http_registry_exposes_all_v5_endpoints(self): - expected = { - "rectification-v5-candidate-features": "/api/rectification/v5/candidate-features", - "rectification-v5-score": "/api/rectification/v5/score", - "rectification-v5-diagnostics": "/api/rectification/v5/diagnostics", - "rectification-v5-versions": "/api/rectification/v5/versions", - } - for command, endpoint in expected.items(): - self.assertEqual(API_COMMAND_MAP[command], endpoint) - self.assertIn(endpoint, TECHNIQUE_EXAMPLE_ENDPOINTS) - - def test_engine_scoring_versions_match_score_identity(self): - from scripts.rectification.api_service import engine_scoring_versions - from scripts.rectification.decision_policy import POLICY_VERSION - from scripts.rectification.scoring_service import ALGORITHM_VERSION - - versions = engine_scoring_versions() - self.assertEqual(versions["algorithm_version"], ALGORITHM_VERSION) - self.assertEqual(versions["decision_policy_version"], POLICY_VERSION) - handler = object.__new__(JyotishAPIHandler) - payload = handler._compute_rectification_v5_versions() - self.assertEqual(payload["algorithm_version"], ALGORITHM_VERSION) - self.assertEqual(payload["decision_policy_version"], POLICY_VERSION) - self.assertEqual(payload["endpoint"], "rectification_v5_versions") - - def test_zero_evidence_returns_declared_window_report(self): - body = request(start_time="23:58", end_time="00:02") - body["events"] = [] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - - result = score_candidates(normalized) - report = result["rectification_report"] - - self.assertEqual(report["candidate_range"]["start_time"], "23:58") - self.assertEqual(report["candidate_range"]["end_time"], "00:02") - self.assertEqual(report["candidate_range"]["width_minutes"], 5) - self.assertIsNone(report["representative_time"]) - self.assertEqual(report["evidence"], []) - self.assertFalse(report["candidate_range"]["representative_is_unique"]) - self.assertIn("do_not_apply_as_birth_time_truth", result["next_step_codes"]) - - def test_report_exposes_evidence_excluded_candidates_and_diagnostics_consistently(self): - body = request() - body["events"] = [ - event(1, "education", "education_start"), - event(2, "career", "promotion"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - built = { - "candidate_times": ["05:13", "05:14", "05:15"], - "matrix": { - item["id"]: { - "05:13": {"points": 4, "rule_ids": ["D10:test"], "technique_layers": ["D10"]}, - "05:14": {"points": 4, "rule_ids": ["D9:test"], "technique_layers": ["D9"]}, - "05:15": {"points": -1, "rule_ids": ["D1:test"], "technique_layers": ["D1"]}, - } - for item in normalized["events"] - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [ - {"feature": {"time": "05:13", "ascendant_sign_index": 1}}, - {"feature": {"time": "05:14", "ascendant_sign_index": 2}}, - {"feature": {"time": "05:15", "ascendant_sign_index": 3}}, - ], - } - diagnostic_values = { - "primary_cluster_retention_rate": 1, - "leave_one_event_out_retention_rate": 1, - "leave_one_domain_out_retention_rate": 1, - "date_sensitivity_retention_rate": 1, - "neighbor_support_minutes": 1, - "primary_secondary_margin_percent": 30, - } - with patch("scripts.rectification.api_service.build_event_contribution_matrix", return_value=built), patch( - "scripts.rectification.api_service.build_candidate_feature_snapshot", return_value={} - ), patch("scripts.rectification.api_service.run_diagnostics", return_value=diagnostic_values): - scored = score_candidates(normalized) - diagnostic_result = diagnostics(normalized) - - report = scored["rectification_report"] - self.assertEqual(report["candidate_range"]["start_time"], "05:13") - self.assertEqual(report["candidate_range"]["end_time"], "05:14") - self.assertEqual(report["representative_time"], "05:13") - self.assertEqual([row["status"] for row in report["evidence"]], ["supporting", "supporting"]) - self.assertEqual(report["evidence"][0]["methods"], ["D10"]) - self.assertGreaterEqual(len(report["excluded_candidates"]), 1) - self.assertEqual(scored["candidate_summary"]["stability"]["label"], scored["overall_confidence"]) - self.assertEqual(diagnostic_result["rectification_report"], report) - self.assertEqual(diagnostic_result["next_step_codes"], scored["next_step_codes"]) - - def test_http_handler_enforces_subject_and_event_kind_boundaries(self): - handler = object.__new__(JyotishAPIHandler) - retained = handler._rectification_v5_request(request(domain="family", event_kind="family_event")) - self.assertEqual(retained["events"][0]["event_kind"], "family_event") - with self.assertRaisesRegex(BadRequest, "event_kind does not match domain"): - handler._rectification_v5_request(request(domain="family", event_kind="family_bereavement")) - with self.assertRaisesRegex(BadRequest, "event_kind does not match domain"): - handler._rectification_v5_request(request(domain="health_pressure", event_kind="family_health_event")) - normalized = handler._rectification_v5_request( - request(domain="health_pressure", event_kind="self_health_event") - ) - self.assertEqual(normalized["events"][0]["event_kind"], "self_health_event") - - def test_v4_compatibility_and_v5_score_handlers_share_the_v5_service(self): - handler = object.__new__(JyotishAPIHandler) - result = {"result_id": "00000000-0000-4000-8000-000000000099", "can_confirm_exact_minute": False} - with patch("scripts.rectification.api_service.score_candidates", return_value=result) as scorer: - v5 = handler._compute_rectification_v5_score(request()) - v4 = handler._compute_active_rectification_events_v4(request()) - self.assertEqual(scorer.call_count, 2) - self.assertEqual(v5["endpoint"], "rectification_v5_score") - self.assertEqual(v4["endpoint"], "active_rectification_events_v4") - self.assertEqual(v5["result_id"], v4["result_id"]) - self.assertFalse(v5["can_confirm_exact_minute"]) - self.assertFalse(v4["can_confirm_exact_minute"]) - - def test_minute_step_default_keeps_calculation_spec_hash_and_full_grid(self): - normalized = normalize_rectification_request(request(), today=date(2026, 7, 28)) - self.assertNotIn("minute_step", normalized) - self.assertEqual( - sha256(calculation_spec(normalized)), - "d68a59ae345a87bcdf7ad45fee913d3aca02c553f896ce6c173a8bd4ab327af3", - ) - candidates = _candidate_datetimes(normalized) - self.assertEqual(len(candidates), 3) - with_step = normalize_rectification_request({**request(), "minute_step": 1}, today=date(2026, 7, 28)) - self.assertNotIn("minute_step", with_step) - self.assertEqual( - [value.isoformat() for value in candidates], - [value.isoformat() for value in _candidate_datetimes(with_step)], - ) - - def test_minute_step_ten_yields_one_hundred_forty_four_full_day_candidates(self): - normalized = normalize_rectification_request( - {**request(start_time="00:00", end_time="23:59"), "minute_step": 10}, - today=date(2026, 7, 28), - ) - self.assertEqual(normalized["minute_step"], 10) - self.assertEqual(calculation_spec(normalized)["minuteStep"], 10) - candidates = _candidate_datetimes(normalized) - self.assertEqual(len(candidates), 144) - self.assertEqual(candidates[0].isoformat(), "1997-08-08T00:00:00") - self.assertEqual(candidates[1].isoformat(), "1997-08-08T00:10:00") - self.assertEqual(candidates[-1].isoformat(), "1997-08-08T23:50:00") - - def test_block_scan_five_periods_sum_to_one_hundred(self): - from scripts.rectification.api_service import BLOCK_SCAN_PERIODS, block_scan - from uuid import uuid4 - - events = [ - { - "id": str(uuid4()), - "domain": domain, - "event_kind": kind, - "date_start": start, - "date_end": end, - "precision": precision, - "summary": kind, - } - for domain, kind, start, end, precision in ( - ("education", "education_start", "2016-09-01", "2016-09-30", "month"), - ("relationship", "relationship_end", "2024-08-08", "2024-08-08", "day"), - ("relocation", "relocation", "2023-07-01", "2023-07-31", "month"), - ) - ] - normalized = normalize_rectification_request( - { - "birth_date": "1998-03-15", - "start_time": "00:00", - "end_time": "23:59", - "lat": 39.9042, - "lon": 116.4074, - "tz": 8.0, - "minute_step": 10, - "events": events, - }, - today=date(2026, 7, 28), - ) - result = block_scan(normalized) - self.assertEqual(result["candidate_count"], 144) - self.assertEqual(len(result["blocks"]), 5) - self.assertEqual( - [(row["period"], row["start_time"], row["end_time"]) for row in result["blocks"]], - list(BLOCK_SCAN_PERIODS), - ) - self.assertEqual(round(sum(float(row["relative_support"]) for row in result["blocks"]), 1), 100.0) - self.assertFalse(result["acceptance_allowed"]) - self.assertFalse(result["selection_allowed"]) - self.assertEqual(result["precision_stage"]["current"], "block_scan") - self.assertEqual(result["discriminating_event_probes"], []) - self.assertEqual(result["decision_receipt"]["precision_stage"]["current"], "block_scan") - - def test_block_scan_seven_events_finishes_within_fifteen_seconds(self): - import time - from uuid import uuid4 - from scripts.rectification.api_service import block_scan - - events = [ - { - "id": str(uuid4()), - "domain": domain, - "event_kind": kind, - "date_start": start, - "date_end": end, - "precision": precision, - "summary": kind, - } - for domain, kind, start, end, precision in ( - ("education", "education_start", "2016-09-01", "2016-09-30", "month"), - ("relationship", "relationship_end", "2024-08-08", "2024-08-08", "day"), - ("relocation", "relocation", "2023-07-01", "2023-07-31", "month"), - ("career", "career_entry", "2018-07-01", "2018-07-31", "month"), - ("finance", "income_change", "2021-03-01", "2021-03-31", "month"), - ("health", "self_health_event", "2020-11-01", "2020-11-30", "month"), - ("family", "family_event", "2019-05-01", "2019-05-31", "month"), - ) - ] - normalized = normalize_rectification_request( - { - "birth_date": "1998-03-15", - "start_time": "00:00", - "end_time": "23:59", - "lat": 39.9042, - "lon": 116.4074, - "tz": 8.0, - "minute_step": 10, - "events": events, - }, - today=date(2026, 7, 28), - ) - started = time.time() - result = block_scan(normalized) - elapsed = time.time() - started - self.assertEqual(result["candidate_count"], 144) - self.assertLessEqual(elapsed, 15, f"block_scan took {elapsed:.1f}s") - - def test_block_scan_equal_scores_share_evenly_and_length_does_not_win(self): - from scripts.rectification.api_service import block_scan - - def grid(score_for): - return [ - {"time": f"{hour:02d}:{minute:02d}", "score": score_for(hour), "supporting_event_ids": []} - for hour in range(24) - for minute in range(0, 60, 10) - ] - - equal_rows = grid(lambda _hour: 12.0) - morning_rows = grid(lambda hour: 20.0 if 4 <= hour <= 7 else 10.0) - dummy = { - "result_id": "00000000-0000-4000-8000-000000000099", - "algorithm_version": "test", - "calculation_spec": {}, - "calculation_spec_hash": "abc", - "decision_receipt": {}, - } - request_body = { - "birth_date": "1998-03-15", - "start_time": "00:00", - "end_time": "23:59", - "lat": 39.9042, - "lon": 116.4074, - "tz": 8.0, - "minute_step": 10, - "events": [], - } - with patch("scripts.rectification.api_service.score_candidates", return_value={**dummy, "candidate_scores": equal_rows}): - equal = block_scan(request_body) - self.assertEqual([row["relative_support"] for row in equal["blocks"]], [20.0, 20.0, 20.0, 20.0, 20.0]) - self.assertEqual([row["candidate_count"] for row in equal["blocks"]], [24, 24, 36, 30, 30]) - with patch("scripts.rectification.api_service.score_candidates", return_value={**dummy, "candidate_scores": morning_rows}): - morning = block_scan(request_body) - shares = {row["period"]: row["relative_support"] for row in morning["blocks"]} - self.assertEqual(max(shares, key=shares.get), "early_morning") - self.assertGreater(shares["early_morning"], shares["afternoon"]) - self.assertEqual(shares["afternoon"], 0.0) - - def test_block_scan_custom_three_blocks_sum_to_one_hundred(self): - from scripts.rectification.api_service import block_scan - - dummy = { - "result_id": "00000000-0000-4000-8000-000000000099", - "algorithm_version": "test", - "calculation_spec": {}, - "calculation_spec_hash": "abc", - "decision_receipt": {}, - } - rows = [ - {"time": f"{hour:02d}:{minute:02d}", "score": 12.0, "supporting_event_ids": []} - for hour in range(12, 18) - for minute in range(0, 60, 10) - if not (hour == 17 and minute > 50) - ] - request_body = { - "birth_date": "1998-03-15", - "start_time": "12:00", - "end_time": "17:59", - "lat": 39.9042, - "lon": 116.4074, - "tz": 8.0, - "minute_step": 10, - "events": [], - "blocks": [ - {"label": "sub_1", "start_time": "12:00", "end_time": "13:59"}, - {"label": "sub_2", "start_time": "14:00", "end_time": "15:59"}, - {"label": "sub_3", "start_time": "16:00", "end_time": "17:59"}, - ], - } - with patch("scripts.rectification.api_service.score_candidates", return_value={**dummy, "candidate_scores": rows}): - result = block_scan(request_body) - self.assertEqual(len(result["blocks"]), 3) - self.assertEqual(round(sum(float(row["relative_support"]) for row in result["blocks"]), 1), 100.0) - shares = sorted(float(row["relative_support"]) for row in result["blocks"]) - self.assertEqual(shares, [33.3, 33.3, 33.4]) - - def test_block_scan_rejects_overlapping_or_out_of_window_blocks(self): - from scripts.rectification.contracts import normalize_rectification_request - - base = { - "birth_date": "1998-03-15", - "start_time": "12:00", - "end_time": "17:59", - "lat": 39.9042, - "lon": 116.4074, - "tz": 8.0, - "events": [], - } - with self.assertRaises(ValueError): - normalize_rectification_request({ - **base, - "blocks": [ - {"label": "sub_1", "start_time": "12:00", "end_time": "14:00"}, - {"label": "sub_2", "start_time": "13:30", "end_time": "15:00"}, - ], - }, today=date(2026, 7, 28)) - with self.assertRaises(ValueError): - normalize_rectification_request({ - **base, - "blocks": [ - {"label": "sub_1", "start_time": "03:00", "end_time": "04:00"}, - ], - }, today=date(2026, 7, 28)) - - def test_compare_returns_ledger_and_windows_by_candidate_time(self): - from scripts.rectification.refinement_packet import build_refinement_packet - - body = request() - body["events"] = [ - event(1, "education", "education_start"), - event(2, "career", "promotion", precision="month"), - event(3, "finance", "finance_gain"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - times = ["05:13", "05:14", "05:15"] - scored_ids = [item["id"] for item in normalized["events"]] - built = { - "candidate_times": times, - "matrix": { - event_id: { - "05:13": {"points": 4, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]}, - "05:14": {"points": 2, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]}, - "05:15": {"points": 1, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]}, - } - for event_id in scored_ids - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - packet = build_refinement_packet( - normalized, - built, - representative_time="05:13", - candidate_times=times, - column_times=times, - include_discriminators=False, - ) - ledgers = packet["event_dasha_ledger_by_time"] - windows = packet["prospective_windows_by_time"] - self.assertEqual(set(ledgers), {"05:13", "05:14", "05:15"}) - self.assertEqual(set(windows), {"05:13", "05:14", "05:15"}) - for clock in times: - self.assertRegex(clock, r"^[0-2]\d:[0-5]\d$") - self.assertIsInstance(ledgers[clock], list) - self.assertIsInstance(windows[clock], list) - self.assertEqual(ledgers["05:13"], packet["event_dasha_ledger"]) - self.assertGreater(len(packet["event_dasha_ledger"]), 0) - self.assertIn("year_month", packet["event_dasha_ledger"][0]) - self.assertEqual(packet["event_dasha_ledger"][0]["year_month"], "2016-09") - - def test_compare_ledgers_cover_all_engine_candidate_times(self): - from scripts.rectification.refinement_packet import ( - build_refinement_packet, - column_times_for_compare, - ) - - body = request() - body["events"] = [ - event(1, "education", "education_start"), - event(2, "career", "promotion", precision="month"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - times = ["04:47", "04:49", "04:51", "04:53", "04:55"] - scored_ids = [item["id"] for item in normalized["events"]] - built = { - "candidate_times": times, - "matrix": { - event_id: { - clock: {"points": 4, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]} - for clock in times - } - for event_id in scored_ids - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - self.assertEqual(column_times_for_compare(times, "04:49"), times) - packet = build_refinement_packet( - normalized, - built, - representative_time="04:49", - candidate_times=times, - include_discriminators=False, - ) - ledgers = packet["event_dasha_ledger_by_time"] - windows = packet["prospective_windows_by_time"] - self.assertEqual(set(ledgers), set(times)) - self.assertEqual(set(windows), set(times)) - self.assertLess(packet["column_compare_ms"], 1000) - - def test_compare_ledgers_cover_seventeen_engine_candidates(self): - from scripts.rectification.refinement_packet import ( - COLUMN_COMPARE_BUDGET_MS, - build_refinement_packet, - column_times_for_compare, - ) - - times = [f"14:{minute:02d}" for minute in range(17)] - self.assertEqual(column_times_for_compare(times, "14:16"), times) - overflow = [f"{index // 60:02d}:{index % 60:02d}" for index in range(65)] - self.assertEqual(len(column_times_for_compare(overflow, overflow[0])), MAX_PUBLIC_CLUSTERS) - - body = request() - body["events"] = [ - event(1, "education", "education_start"), - event(2, "career", "promotion", precision="month"), - ] - normalized = normalize_rectification_request(body, today=date(2026, 7, 28)) - scored_ids = [item["id"] for item in normalized["events"]] - built = { - "candidate_times": times, - "matrix": { - event_id: { - clock: {"points": 4, "rule_ids": ["vim_md_domain_house"], "technique_layers": ["vim_md_domain_house"]} - for clock in times - } - for event_id in scored_ids - }, - "date_sensitivity": [], - "missing_layers": [], - "static_contexts": [], - } - packet = build_refinement_packet( - normalized, - built, - representative_time="14:16", - candidate_times=times, - include_discriminators=False, - ) - self.assertEqual(set(packet["event_dasha_ledger_by_time"]), set(times)) - self.assertEqual(set(packet["prospective_windows_by_time"]), set(times)) - self.assertLess(packet["column_compare_ms"], COLUMN_COMPARE_BUDGET_MS) - subset = build_refinement_packet( - normalized, - built, - representative_time="14:00", - candidate_times=times, - column_times=times[:3], - include_discriminators=False, - ) - self.assertEqual(set(subset["event_dasha_ledger_by_time"]), set(times[:3])) - body["column_times"] = times[:3] - self.assertEqual( - normalize_rectification_request(body, today=date(2026, 7, 28))["column_times"], - times[:3], - ) - - def test_hour_window_keeps_all_seventeen_signature_clusters_including_late_tail(self): - rows, contexts = _hour_window_signature_fixture() - public = select_signature_representatives(rows, contexts) - times = {row["time"] for row in public} - self.assertEqual(MAX_PUBLIC_CLUSTERS, 64) - self.assertEqual(len(public), 17) - self.assertTrue(times & {"14:46", "14:47", "14:48", "14:49", "14:50", "14:51"}) - self.assertIn("15:00", {time for row in rows for time in [row["time"]]}) - decisions = build_candidate_decisions( - rows, - result_id="00000000-0000-4000-8000-000000000623", - static_contexts=contexts, - ) - self.assertEqual(len(decisions), 17) - late = next(item for item in decisions if item["time"] in {"14:46", "14:47", "14:48", "14:49", "14:50", "14:51"}) - self.assertEqual(late["cluster_start"], "14:46") - self.assertEqual(late["cluster_end"], "14:51") - self.assertEqual(late["cluster_times"][0], "14:46") - self.assertEqual(late["cluster_times"][-1], "14:51") - - def test_cluster_coverage_not_representative_minute_sets_credible_span(self): - times = _clock_span("14:40", "14:45") - rows = [ - {"time": time, "score": 20 if time == "14:40" else 11, "evidence": [], "missing_layers": []} - for time in times - ] - contexts = [_signature_context(time, 3) for time in times] - decisions = build_candidate_decisions( - rows, - result_id="00000000-0000-4000-8000-000000000624", - static_contexts=contexts, - ) - self.assertEqual(len(decisions), 1) - self.assertEqual(decisions[0]["time"], "14:40") - self.assertEqual(decisions[0]["cluster_start"], "14:40") - self.assertEqual(decisions[0]["cluster_end"], "14:45") - self.assertEqual(decisions[0]["cluster_times"], times) - - def test_adjacent_low_score_merge_keeps_the_window_tail(self): - rows = [] - contexts = [] - for index in range(65): - time = f"{index // 60:02d}:{index % 60:02d}" - score = 1 if index >= 63 else 20 - rows.append({"time": time, "score": score, "evidence": [], "missing_layers": []}) - contexts.append(_signature_context(time, index)) - public = select_signature_representatives(rows, contexts) - self.assertEqual(len(public), 64) - covered = {time for row in public for time in row.get("cluster_times", [row["time"]])} - self.assertIn("01:04", covered) - - -def _clock_span(start: str, end: str) -> list[str]: - start_minutes = int(start[:2]) * 60 + int(start[3:5]) - end_minutes = int(end[:2]) * 60 + int(end[3:5]) - return [f"{minute // 60:02d}:{minute % 60:02d}" for minute in range(start_minutes, end_minutes + 1)] - - -def _signature_context(time: str, signature_index: int) -> dict: - hour, minute = (int(part) for part in time.split(":")) - return { - "candidate_at": datetime(1997, 8, 8, hour, minute), - "ascendant_index": signature_index % 12, - "planet_longitudes": {"Moon": 13.0 * (signature_index % 27)}, - "feature": { - "time": time, - "ascendant_sign_index": signature_index % 12, - "moon_degree": 13.0 * (signature_index % 27), - "varga_ascendants": { - "D4": (signature_index // 12) % 12, - "D9": (signature_index // 3) % 12, - "D10": (signature_index // 5) % 12, - "D24": (signature_index // 7) % 12, - "D12": (signature_index // 11) % 12, - }, - }, - } - - -def _hour_window_signature_fixture() -> tuple[list[dict], list[dict]]: - ranges = [ - ("14:00", "14:03"), - ("14:04", "14:06"), - ("14:07", "14:09"), - ("14:10", "14:12"), - ("14:13", "14:15"), - ("14:16", "14:18"), - ("14:19", "14:21"), - ("14:22", "14:24"), - ("14:25", "14:28"), - ("14:29", "14:32"), - ("14:33", "14:36"), - ("14:37", "14:39"), - ("14:40", "14:45"), - ("14:46", "14:51"), - ("14:52", "14:53"), - ("14:54", "14:57"), - ("14:58", "15:00"), - ] - rows: list[dict] = [] - contexts: list[dict] = [] - for index, (start, end) in enumerate(ranges): - times = _clock_span(start, end) - for offset, time in enumerate(times): - score = 30 + index if offset == 0 else 10 + index - if start == "14:46": - score = 90 if offset == 0 else 80 - rows.append({"time": time, "score": score, "evidence": [], "missing_layers": []}) - contexts.append(_signature_context(time, index)) - return rows, contexts - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_rectification_v5_vedastro_validation.py b/tests/test_rectification_v5_vedastro_validation.py deleted file mode 100644 index 5761e0b75..000000000 --- a/tests/test_rectification_v5_vedastro_validation.py +++ /dev/null @@ -1,399 +0,0 @@ -from __future__ import annotations - -import pytest - -from scripts.jyotish_api_server import ( - API_COMMAND_MAP, - TECHNIQUE_EXAMPLE_ENDPOINTS, - BadRequest, - JyotishAPIHandler, - _attach_vedastro_minute_sensitive_to_score, -) - - -def request(candidate_times=None): - events = [ - { - "id": "00000000-0000-4000-8000-000000000001", - "domain": "education", - "event_kind": "education_milestone", - "date_start": "2016-09-01", - "date_end": "2016-09-30", - "precision": "month", - "summary": "private education summary that must not be returned", - }, - { - "id": "00000000-0000-4000-8000-000000000002", - "domain": "career", - "event_kind": "career_change", - "date_start": "2020-05-01", - "date_end": "2020-05-01", - "precision": "day", - "summary": "private career summary that must not be returned", - }, - { - "id": "00000000-0000-4000-8000-000000000003", - "domain": "career", - "event_kind": "career_change", - "date_start": "2021-06-01", - "date_end": "2021-06-01", - "precision": "day", - "summary": "newer career event wins the bounded selection", - }, - { - "id": "00000000-0000-4000-8000-000000000004", - "domain": "relationship", - "event_kind": "relationship_change", - "date_start": "2022-01-01", - "date_end": "2022-12-31", - "precision": "year", - "summary": "private relationship summary that must not be returned", - }, - { - "id": "00000000-0000-4000-8000-000000000005", - "domain": "finance", - "event_kind": "finance_change", - "date_start": "2023-03-01", - "date_end": "2023-03-31", - "precision": "month", - "summary": "private finance summary that must not be returned", - }, - { - "id": "00000000-0000-4000-8000-000000000006", - "domain": "health_pressure", - "event_kind": "self_health_event", - "date_start": "2024-04-01", - "date_end": "2024-04-30", - "precision": "month", - "summary": "private health summary that must not be returned", - }, - ] - return { - "birth_date": "1997-08-08", - "start_time": "05:00", - "end_time": "05:30", - "lat": 36.419, - "lon": 114.213, - "tz": 8, - "events": events, - "candidate_times": candidate_times if candidate_times is not None else ["05:13", "05:14"], - } - - -def minute_snapshot(case, *, same=False): - minute = case["minute"] - suffix = "same" if same else str(minute) - return { - "available": True, - "status": "ok", - "source": "vedastro_official", - "layers": { - "ascendant_house_boundaries": { - "status": "ok", - "fingerprint": f"asc-{suffix}", - "ascendant": {"sign": "Leo", "degree_in_sign": minute / 10}, - "houses": {"House1": {}}, - }, - "D9": {"status": "ok", "fingerprint": f"d9-{suffix}", "houses": {"House1": {}}, "planets": {}}, - "D10": {"status": "ok", "fingerprint": f"d10-{suffix}", "houses": {"House1": {}}, "planets": {}}, - "dasha_boundaries": {"status": "ok", "fingerprint": f"dasha-{suffix}", "boundary_count": 3}, - "kp_cusp_sub_lord": {"status": "unsupported", "reason": "not available"}, - }, - "raw_request": {"api_key": "secret"}, - "raw_response": {"private": True}, - } - - -def test_registry_exposes_independent_vedastro_validation_endpoint(): - endpoint = "/api/rectification/v5/vedastro-validate" - assert API_COMMAND_MAP["rectification-v5-vedastro-validate"] == endpoint - assert endpoint in TECHNIQUE_EXAMPLE_ENDPOINTS - - -def test_requires_exactly_two_distinct_candidate_times_before_running_vedastro(): - handler = object.__new__(JyotishAPIHandler) - for candidate_times in ([], ["05:13"], ["05:13", "05:14", "05:15"], ["05:13", "05:13"]): - with pytest.raises(BadRequest, match="candidate_times"): - handler._compute_rectification_v5_vedastro_validate(request(candidate_times)) - - -@pytest.mark.parametrize("dated", [False, True]) -def test_passes_only_when_official_layers_discriminate_and_primary_is_strictly_better(monkeypatch, dated): - range_calls = [] - minute_dates = [] - - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - minute_dates.append((case["year"], case["month"], case["day"])) - return minute_snapshot(case) - - @staticmethod - def run_range_scan_for_case(case, domain, start, end, case_id="user_chart"): - range_calls.append((case["minute"], domain, start, end)) - lift = 3 if case["minute"] == 13 else 1 - return { - "available": True, - "status": "ok", - "event_count": lift, - "top_event": {"event_id": f"event-{domain}"}, - "evidence_ledger": [{"signal_lift": lift}], - "raw_response": {"must_not": "leak"}, - } - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - monkeypatch.setenv("VEDASTRO_API_KEY", "must-not-leak") - - body = request() - if dated: - body["birth_date"] = "2000-03-01" - body["candidate_intervals"] = [{"start_at": "2000-02-29T05:13", "end_at": "2000-02-29T05:14"}] - result = object.__new__(JyotishAPIHandler)._compute_rectification_v5_vedastro_validate(body) - if dated: - assert minute_dates == [(2000, 2, 29), (2000, 2, 29)] - - assert result["status"] == "pass" - assert result["passed"] is True - assert result["can_confirm_exact_minute"] is False - assert result["candidate_times"] == {"primary": "05:13", "runner_up": "05:14"} - assert result["minute_sensitive_validation"]["discriminated"] is True - assert result["event_validation"]["search_events_primary_supports_local_winner"] is True - assert result["event_validation"]["supported_event_count"] == 3 - assert len(range_calls) == 6 - assert {call[1] for call in range_calls} == {"career", "marriage", "wealth"} - serialized = str(result) - assert "private" not in serialized - assert "raw_request" not in serialized - assert "raw_response" not in serialized - assert "must-not-leak" not in serialized - - -@pytest.mark.parametrize("mutation", ["missing_source", "missing_layer"]) -def test_missing_official_minute_response_cannot_pass(monkeypatch, mutation): - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - report = minute_snapshot(case) - if mutation == "missing_source": - report.pop("source") - else: - report["layers"].pop("D10") - return report - - @staticmethod - def run_range_scan_for_case(case, domain, start, end, case_id="user_chart"): - lift = 3 if case["minute"] == 13 else 1 - return { - "available": True, - "status": "ok", - "event_count": lift, - "top_event": {"event_id": f"event-{domain}"}, - "evidence_ledger": [{"signal_lift": lift}], - } - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = object.__new__(JyotishAPIHandler)._compute_rectification_v5_vedastro_validate(request()) - - assert result["status"] == "fail" - assert result["passed"] is False - assert result["can_confirm_exact_minute"] is False - assert "vedastro_official_response_missing" in result["blockers"] - - -def test_identical_minute_layers_cannot_pass(monkeypatch): - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - return minute_snapshot(case, same=True) - - @staticmethod - def run_range_scan_for_case(case, domain, start, end, case_id="user_chart"): - return { - "available": True, - "status": "ok", - "event_count": 1, - "top_event": {"event_id": f"event-{domain}"}, - "evidence_ledger": [{"signal_lift": 1}], - } - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = object.__new__(JyotishAPIHandler)._compute_rectification_v5_vedastro_validate(request()) - - assert result["status"] == "fail" - assert result["passed"] is False - assert result["can_confirm_exact_minute"] is False - assert "vedastro_minute_sensitive_layers_not_discriminated" in result["blockers"] - - -def test_search_events_disagreement_is_diagnostic_and_cannot_reverse_local_winner(monkeypatch): - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - return minute_snapshot(case) - - @staticmethod - def run_range_scan_for_case(case, domain, start, end, case_id="user_chart"): - lift = 1 if case["minute"] == 13 else 3 - return { - "available": True, - "status": "ok", - "event_count": lift, - "top_event": {"event_id": f"event-{domain}"}, - "evidence_ledger": [{"signal_lift": lift}], - } - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = object.__new__(JyotishAPIHandler)._compute_rectification_v5_vedastro_validate(request()) - - assert result["status"] == "pass" - assert result["passed"] is True - assert result["event_validation"]["search_events_primary_supports_local_winner"] is False - assert result["blockers"] == [] - assert result["can_confirm_exact_minute"] is False - - -def test_timeout_is_returned_as_safe_failure(monkeypatch): - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - raise TimeoutError("secret upstream URL and key") - - @staticmethod - def run_range_scan_for_case(case, domain, start, end, case_id="user_chart"): - raise RuntimeError("secret raw response") - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = object.__new__(JyotishAPIHandler)._compute_rectification_v5_vedastro_validate(request()) - - assert result["status"] == "fail" - assert result["passed"] is False - assert result["can_confirm_exact_minute"] is False - assert "vedastro_timeout" in result["blockers"] - assert "vedastro_exception" in result["blockers"] - assert "secret" not in str(result) - - -def _score_request(): - return { - "birth_date": "1997-08-08", - "lat": 36.419, - "lon": 114.213, - "tz": 8, - } - - -def _scored_result(*, acceptance=True): - receipt = { - "acceptance_allowed": acceptance, - "confirmation_allowed": False, - "gates": {"exact_confirmation": {"external_validation_status": "not_evaluated"}}, - "technique_audit_table": [ - {"technique": "VedAstro 分钟级校验", "status": "blocked", "note": "官方分钟级校验尚未评估。"}, - {"technique": "唯一分钟确认", "status": "blocked", "note": "本会话以代表性时间收口,不确认唯一分钟。"}, - ], - } - return { - "candidate_decisions": [ - {"time": "05:13", "rank": 1}, - {"time": "05:14", "rank": 2}, - ], - "decision_receipt": receipt, - "candidate_decision_receipt": receipt, - "confirmation_allowed": False, - } - - -def test_v5_score_attaches_minute_sensitive_pass_without_search_events(monkeypatch): - range_calls = [] - - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - return minute_snapshot(case) - - @staticmethod - def run_range_scan_for_case(case, domain, start, end, case_id="user_chart"): - range_calls.append((domain, start, end)) - return {"available": True, "status": "ok"} - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = _attach_vedastro_minute_sensitive_to_score(_scored_result(), _score_request()) - exact = result["decision_receipt"]["gates"]["exact_confirmation"] - assert exact["external_validation_status"] == "passed" - assert exact["vedastro_minute_sensitive"]["discriminated"] is True - assert result["confirmation_allowed"] is False - audit = {row["technique"]: row for row in result["decision_receipt"]["technique_audit_table"]} - assert audit["VedAstro 分钟级校验"]["status"] == "executed" - assert "已通过" in audit["VedAstro 分钟级校验"]["note"] - assert audit["唯一分钟确认"]["status"] == "blocked" - assert range_calls == [] - serialized = str(result) - assert "36.419" not in serialized - assert "114.213" not in serialized - assert "asc-" not in serialized - - -def test_v5_score_marks_identical_minute_snapshots_failed_not_not_evaluated(monkeypatch): - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - return minute_snapshot(case, same=True) - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = _attach_vedastro_minute_sensitive_to_score(_scored_result(), _score_request()) - exact = result["decision_receipt"]["gates"]["exact_confirmation"] - assert exact["external_validation_status"] == "failed" - assert exact["vedastro_minute_sensitive"]["reason"] == "vedastro_minute_sensitive_layers_not_discriminated" - assert result["confirmation_allowed"] is False - - -def test_v5_score_timeout_stays_not_evaluated(monkeypatch): - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - raise TimeoutError("secret upstream URL") - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = _attach_vedastro_minute_sensitive_to_score(_scored_result(), _score_request()) - exact = result["decision_receipt"]["gates"]["exact_confirmation"] - assert exact["external_validation_status"] == "not_evaluated" - assert exact["vedastro_minute_sensitive"]["reason"] == "vedastro_minute_snapshot_timeout" - assert "secret" not in str(result) - assert result["confirmation_allowed"] is False - - -def test_v5_score_skips_vedastro_until_local_acceptance(monkeypatch): - calls = [] - - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - calls.append(True) - return minute_snapshot(case) - - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = _attach_vedastro_minute_sensitive_to_score( - _scored_result(acceptance=False), - _score_request(), - ) - exact = result["decision_receipt"]["gates"]["exact_confirmation"] - assert exact["external_validation_status"] == "not_evaluated" - assert calls == [] - - -def test_v5_score_join_timeout_stays_not_evaluated(monkeypatch): - import time - - class Adapter: - @staticmethod - def run_rectification_minute_snapshot_for_case(case, case_id="user_chart"): - time.sleep(0.4) - return minute_snapshot(case) - - monkeypatch.setattr("scripts.jyotish_api_server._foreground_vedastro_budget_seconds", lambda: 0.05) - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: Adapter) - result = _attach_vedastro_minute_sensitive_to_score(_scored_result(), _score_request()) - exact = result["decision_receipt"]["gates"]["exact_confirmation"] - assert exact["external_validation_status"] == "not_evaluated" - assert exact["vedastro_minute_sensitive"]["reason"] == "vedastro_minute_snapshot_timeout" - assert result["confirmation_allowed"] is False diff --git a/tests/test_rectification_validation_integrity_gate.py b/tests/test_rectification_validation_integrity_gate.py deleted file mode 100644 index 7833ff441..000000000 --- a/tests/test_rectification_validation_integrity_gate.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Collect research integrity regressions in the existing rectification quick gate.""" - -from tests.test_reported_offset_research import ( # noqa: F401 - test_cross_midnight_real_engine_scores_match_candidate_date_replay, - test_offset_beyond_radius_has_no_truth_candidate, - test_opaque_tie_break_is_independent_of_truth_and_input_order, - test_recorded_specification_and_all_prespecified_cells, - test_shifted_window_preserves_dates_across_midnight, - test_zero_offset_centres_on_truth_and_has_complete_grid, - test_sweep_changed_frozen_identity_fails_before_scoring, -) -from tests.test_sealed_holdout_contract_freshness import ( # noqa: F401 - test_changed_frozen_identity_fails_before_any_replay, - test_contract_tracks_actual_current_scorer_and_dataset_audit, - test_functional_roles_are_part_of_the_production_identity, - test_fixed_protocol_rerun_is_auditable_but_never_independent_blind, - test_frozen_record_matches_dataset_scorer_and_evaluator_bytes, - test_extended_identity_drift_rejected_even_when_legacy_hash_unchanged, - test_historical_artifacts_are_byte_preserved_not_refreshed, -) diff --git a/tests/test_repo_privacy_markers.py b/tests/test_repo_privacy_markers.py index 887158561..1e304d862 100644 --- a/tests/test_repo_privacy_markers.py +++ b/tests/test_repo_privacy_markers.py @@ -190,10 +190,9 @@ def _collision_spans(path: str, source: str, rules: tuple[Rule, ...]) -> list[tu marker = next((r.value for r in rules if r.code == "R003"), None) if marker is None: return [] - service_path = "tests/test_rectification_v5_services.py" replay_path = "references/oracle/pyjhora_multi_case_panchanga_gulika_replay_2026_07_23.json" report_path = "frontend/tests/fixtures/report-density-fictional-reader.json" - if path not in {service_path, replay_path, report_path}: + if path not in {replay_path, report_path}: return [] try: tree = ast.parse(source) @@ -235,27 +234,6 @@ def _collision_spans(path: str, source: str, rules: tuple[Rule, ...]) -> list[tu return [(offset, offset + len(marker))] except (ValueError, KeyError, IndexError, AttributeError, TypeError): return [] - if path == service_path: - name = "test_hour_window_keeps_all_seventeen_signature_clusters_including_late_tail" - functions = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == name] - if len(functions) != 1: - return [] - spans = [] - for node in ast.walk(functions[0]): - # 原值: node.lineno not in {1182, 1190} - # 新值: node.lineno not in {1195, 1203} - # 原因: BUG-1325 在本文件前面加了三栏注释,这两处时钟集合整段下移,数值本身没变 - if not isinstance(node, ast.Set) or node.lineno not in {1195, 1203}: - continue - try: - values = ast.literal_eval(node) - except (ValueError, TypeError): - continue - if values == {f"14:{minute:02}" for minute in range(46, 52)} and len(node.elts) == 6: - for child in node.elts: - if isinstance(child, ast.Constant) and child.value == marker: - spans.append(_node_span(source, child)) - return spans try: data = json.loads(source) case = data["cases"][1] @@ -576,7 +554,6 @@ def test_repository_scan_includes_new_tracked_and_all_protected_files(monkeypatc @pytest.mark.parametrize("path,count", [ - ("tests/test_rectification_v5_services.py", 2), ("references/oracle/pyjhora_multi_case_panchanga_gulika_replay_2026_07_23.json", 1), ]) def test_reviewed_numerical_collisions_are_exact_nodes_only(path: str, count: int) -> None: diff --git a/tests/test_reported_offset_research.py b/tests/test_reported_offset_research.py deleted file mode 100644 index d8a6dd963..000000000 --- a/tests/test_reported_offset_research.py +++ /dev/null @@ -1,151 +0,0 @@ -from __future__ import annotations - -import json -from datetime import datetime, timedelta - -import pytest - -from scripts.research import reported_offset_sweep as sweep -from scripts.research.sealed_holdout_rerun import DATASET, opaque_order - - -def public_case(): - return json.loads(DATASET.read_text(encoding="utf-8"))["cases"][0] - - -def test_zero_offset_centres_on_truth_and_has_complete_grid(): - case = public_case() - truth = datetime.fromisoformat(f"{case['birth']['date']}T{case['birth']['time']}:00") - request, candidates = sweep.shifted_window(case, 0, 15) - assert candidates[15] == truth - assert len(candidates) == 31 - assert request["start_time"] == candidates[0].strftime("%H:%M") - assert request["end_time"] == candidates[-1].strftime("%H:%M") - assert truth in candidates - assert not any("truth" in key or "offset" in key for key in request) - - -@pytest.mark.parametrize("offset", [-30, -20, 20, 30]) -def test_offset_beyond_radius_has_no_truth_candidate(offset): - case = public_case() - truth = datetime.fromisoformat(f"{case['birth']['date']}T{case['birth']['time']}:00") - _, candidates = sweep.shifted_window(case, offset, 15) - assert truth not in candidates - rows = [{"time": moment.strftime("%H:%M"), "score": 1} for moment in candidates] - metrics = sweep.reveal_metrics(rows, candidates, candidates, truth, "test", "test") - assert metrics["truth_in_window"] is False - assert metrics["true_rank"] is None - assert metrics["delivery_covers_truth"] is False - - -def test_opaque_tie_break_is_independent_of_truth_and_input_order(): - # Explicitly synthetic unit inputs, not a fabricated engine-contract fixture. - moments = [datetime(2000, 1, 1, 12) + timedelta(minutes=i) for i in range(3)] - rows = [{"time": moment.strftime("%H:%M"), "score": 1} for moment in moments] - ordered = opaque_order("test", "synthetic", rows) - assert ordered == opaque_order("test", "synthetic", list(reversed(rows))) - winner = next(moment for moment in moments if moment.strftime("%H:%M") == ordered[0]["time"]) - for truth in moments: - metrics = sweep.reveal_metrics(rows, moments, moments, truth, "test", "synthetic") - assert metrics["top_1_hit"] is (truth == winner) - assert metrics["true_rank"] == 1 + next(i for i, row in enumerate(ordered) if row["time"] == truth.strftime("%H:%M")) - - -@pytest.mark.parametrize("clock,offset", [("00:02", -5), ("23:58", 5)]) -def test_shifted_window_preserves_dates_across_midnight(clock, offset): - case = public_case() - # Synthetic boundary mutation of the public case; no real user's birth data. - case["birth"] = {**case["birth"], "time": clock} - request, candidates = sweep.shifted_window(case, offset, 15) - truth = datetime.fromisoformat(f"{case['birth']['date']}T{clock}:00") - assert candidates[15] == truth + timedelta(minutes=offset) - assert request["birth_date"] == candidates[0].date().isoformat() - rows = [{"time": moment.strftime("%H:%M"), "score": int(moment == truth)} for moment in candidates] - metrics = sweep.reveal_metrics(rows, candidates, candidates, truth, "test", "synthetic") - assert metrics["top_1_minute_error"] == 0 - assert metrics["truth_in_window"] is True - assert metrics["delivery_covers_truth"] is True - assert metrics["delivery_width_minutes"] == 31 - - -def test_cross_midnight_real_engine_scores_match_candidate_date_replay(monkeypatch): - case = json.loads(DATASET.read_text(encoding="utf-8"))["cases"][5] - request, candidates = sweep.shifted_window(case, 0, 60) - assert len({candidate.date() for candidate in candidates}) == 2 - contexts = sweep.compute_candidate_static_contexts(request, candidates=candidates) - calls = [] - build = sweep.build_event_contribution_matrix - def traced(request, **kwargs): - calls.append(len(kwargs["static_contexts"])) - return build(request, **kwargs) - with monkeypatch.context() as patch: - patch.setattr(sweep, "build_event_contribution_matrix", traced) - native = sweep.score_window(request, contexts) - assert calls == [len(contexts)] - expected = [] - for context in contexts: - dated = {**request, "birth_date": context["candidate_at"].date().isoformat()} - built = sweep.build_event_contribution_matrix(dated, static_contexts=[context]) - expected.extend(sweep.score_from_matrix(dated, built)) - assert native == expected - native_matrix = sweep.build_event_contribution_matrix(request, static_contexts=contexts) - native_rows = sweep.score_from_matrix(request, native_matrix) - assert native_rows == expected - - -def test_recorded_specification_and_all_prespecified_cells(): - report = json.loads(sweep.REPORT.read_text(encoding="utf-8")) - spec = report["specification"] - assert spec["ayanamsa"] == "raman" - assert spec["node_mode"] == "mean" - assert spec["radii_minutes"] == list(sweep.RADII) - assert spec["offsets_minutes"] == list(sweep.OFFSETS) - assert spec["minute_step"] == 1 - assert spec["implementation_sha256_prefix"] == spec["implementation_sha256"][:16] - assert spec["dataset_sha256"] == sweep.file_sha256(DATASET) - assert spec["evaluator_sha256"] == sweep.file_sha256(sweep.ROOT / "scripts/research/reported_offset_sweep.py") - assert spec["production_scoring_sha256"] == sweep.implementation_sha256(spec["production_scoring_files"]) - assert spec["research_implementation_sha256"] == sweep.implementation_sha256(spec["research_files"]) - assert spec["replay_revision"] == "native_candidate_date_v3" - frozen = json.loads(sweep.FREEZE.read_text(encoding="utf-8")) - assert report["frozen_record"] == spec == frozen - sweep.verify_frozen_record(frozen, sweep.freeze_record()) - assert report["implementation_hash_matches_at_replay"] is True - assert report["dataset_hash_matches_at_replay"] is True - assert frozen["frozen_at_utc"] <= report["replay_started_at_utc"] <= report["replay_finished_at_utc"] - assert spec["official_valid_independent_blind"] is False - assert spec["official_blind_trial_count"] == 0 - assert spec["results_previously_seen"] is True - assert spec["must_not_use_for_tuning"] is True - assert spec["truth_hidden_from_ranker"] is True - assert spec["is_blind_evaluation"] is False - assert report["trial_count"] == 20 * len(sweep.RADII) * len(sweep.OFFSETS) - assert len(report["summary"]) == len(sweep.RADII) * len(sweep.OFFSETS) - assert report["summary"] == sweep.summarize(report["trials"], sweep.RADII, sweep.OFFSETS) - assert {(row["case_ordinal"], row["radius_minutes"], row["offset_minutes"]) for row in report["trials"]} == { - (case, radius, offset) for case in range(1, 21) for radius in sweep.RADII for offset in sweep.OFFSETS - } - assert report["widening_geometry"]["radius_120_scored"] is False - for trial in report["trials"]: - assert not ({"predicted_time", "birth", "latitude", "longitude"} & trial.keys()) - for row in report["summary"]: - expected = float(abs(row["offset_minutes"]) <= row["radius_minutes"]) - assert row["truth_in_window_rate"] == expected - assert row["delivery_coverage_rate"] <= expected - assert row["top_1_rate"] <= expected - assert report["historical_comparison"] == sweep.historical_comparison( - sweep.LEGACY_REPORT, report["trials"], ("case_ordinal", "radius_minutes", "offset_minutes"), - ) - - -@pytest.mark.parametrize("key", ["dataset_sha256", "production_scoring_sha256", "research_implementation_sha256", "evaluator_sha256"]) -def test_sweep_changed_frozen_identity_fails_before_scoring(tmp_path, monkeypatch, key): - frozen = sweep.freeze_record() - frozen[key] = "0" * 64 - path = tmp_path / "bad-freeze.json" - path.write_text(json.dumps(frozen), encoding="utf-8") - def unexpected(*args, **kwargs): - raise AssertionError("must reject identity before scoring") - monkeypatch.setattr(sweep, "compute_candidate_static_contexts", unexpected) - with pytest.raises(ValueError, match=f"frozen_record_mismatch:{key}"): - sweep.run(freeze_path=path) diff --git a/tests/test_research_timing.py b/tests/test_research_timing.py index 339e27272..08a7be866 100644 --- a/tests/test_research_timing.py +++ b/tests/test_research_timing.py @@ -173,8 +173,6 @@ def test_rectification_modules_do_not_import_the_research_package() -> None: paths = list((ROOT / "scripts").glob("rectification*.py")) paths.extend((ROOT / "scripts").glob("birth_time*.py")) for name in ( - "active_rectification_scoring.py", - "dynamic_rectification.py", "birth_time_rectifier.py", "active_rectification_events.py", ): diff --git a/tests/test_scoring_research.py b/tests/test_scoring_research.py deleted file mode 100644 index 1e3827420..000000000 --- a/tests/test_scoring_research.py +++ /dev/null @@ -1,159 +0,0 @@ -"""Regression tests for the 2026-09-29 scoring-method research scaffold. - -Pure helpers use fictional inputs. The one integration test reconciles the -research recording scorer against the production scorer on a public v4 case -(task hard line 4: zero difference before any experiment). -""" -from __future__ import annotations - -import json -from pathlib import Path - -import pytest - -import scripts.research.scoring_research_lib as lib - -ROOT = Path(__file__).resolve().parents[1] -HOLDOUT_V4 = ROOT / "references" / "real_case_calibration" / "minute_rectification_holdout_v4.json" - - -def test_estimate_lr_rewards_discriminating_feature_and_leaves_noise_near_zero() -> None: - examples = [] - for _ in range(20): - examples.append(({"good": 1.0, "noise": 1.0}, True)) - examples.append(({"good": 1.0, "noise": 0.0}, True)) - for _ in range(80): - examples.append(({"noise": 1.0}, False)) - examples.append(({"noise": 0.0}, False)) - table = lib.estimate_lr(examples, alpha=1.0) - assert table.positives == 40 and table.negatives == 160 - assert table.present["good"] > 1.5 - assert table.absent["good"] < -1.5 - assert abs(table.present["noise"]) < 0.05 - # reward-only policy clips the negative absent term; naive-Bayes keeps it - assert table.weight("good", allow_negative=False) == (table.present["good"], 0.0) - assert table.weight("good", allow_negative=True) == (table.present["good"], table.absent["good"]) - - -def test_loo_folds_never_contain_the_held_out_case() -> None: - folds = lib.loo_folds(["a", "b", "c"]) - assert [held for held, _ in folds] == ["a", "b", "c"] - for held, training in folds: - assert held not in training and len(training) == 2 - - -def test_event_feature_matrix_is_the_fraction_of_sample_dates() -> None: - store = lib.FeatureStore() - store.put("e1", "1990-01-15", "10:00", ["vim_md_domain_house", "event_kind:career"], ["pranapada_in_target_house"]) - store.put("e1", "1990-02-15", "10:00", ["vim_ad_domain_lord"], []) - store.put("e1", "1990-01-15", "10:02", ["no_domain_activation"], []) - store.put("e1", "1990-02-15", "10:02", ["no_domain_activation"], []) - matrix = lib.event_feature_matrix(store, "e1", ["10:00", "10:02"], include_extras=True) - assert matrix["10:00"] == {"vim_md_domain_house": 0.5, "vim_ad_domain_lord": 0.5, "pranapada_in_target_house": 0.5} - assert matrix["10:02"] == {} - without = lib.event_feature_matrix(store, "e1", ["10:00"], include_extras=False) - assert "pranapada_in_target_house" not in without["10:00"] - - -def test_scoring_rule_filter_drops_event_kind_and_constant_rules() -> None: - assert lib.is_scoring_rule("vim_md_domain_varga") - assert lib.is_scoring_rule("controlled_transit_jupiter_domain_house") - assert not lib.is_scoring_rule("event_kind:career") - assert not lib.is_scoring_rule("event_kind_profile:career:change") - assert not lib.is_scoring_rule("no_domain_activation") - assert not lib.is_scoring_rule("occupation_auxiliary_not_primary") - assert not lib.is_scoring_rule("kp_asc_sublord_is_vim_md") # extras are a separate namespace - assert lib.is_extra_feature("vim_md_domain_varga_d60") - - -def test_weighted_provider_scores_each_sample_from_the_store() -> None: - store = lib.FeatureStore() - store.put("e1", "1990-01-15", "10:00", ["vim_md_domain_house"], ["kp_asc_sublord_is_vim_md"]) - store.put("e1", "1990-01-15", "10:02", [], []) - table = lib.LRTable( - alpha=1.0, positives=1, negatives=1, - present={"vim_md_domain_house": 1.0, "kp_asc_sublord_is_vim_md": 0.5}, - absent={"vim_md_domain_house": -0.25, "kp_asc_sublord_is_vim_md": -0.1}, - support={}, - ) - request = {"events": [{"id": "e1", "date": "1990-01-15", "domain": "career"}]} - a1 = lib.make_weighted_provider(store, table, variant="A1")(request) - a2 = lib.make_weighted_provider(store, table, variant="A2")(request) - a3 = lib.make_weighted_provider(store, table, variant="A3", scale=2.0)(request) - assert [(r["time"], r["score"]) for r in a1] == [("10:00", 1.0), ("10:02", 0.0)] - assert [(r["time"], r["score"]) for r in a2] == [("10:00", 1.5), ("10:02", 0.0)] - assert [(r["time"], r["score"]) for r in a3] == [("10:00", 3.0), ("10:02", -0.7)] - assert a1[0]["evidence"][0]["rule_ids"] == ["vim_md_domain_house"] - - -def _probe() -> dict: - return {"expected_outcomes": [ - {"answer_class": "yes", "supports": ["10:00"], "conflicts": ["10:04"]}, - {"answer_class": "no", "supports": ["10:04"], "conflicts": ["10:00"]}, - ]} - - -def test_scaled_answer_halves_the_delta_and_never_counts_a_conflict() -> None: - scores = {"10:00": 10.0, "10:02": 10.0, "10:04": 10.0} - conflicts = {time: 0 for time in scores} - weak, weak_conflicts, weak_elim = lib.apply_scaled_answer(scores, conflicts, set(), _probe(), "no", list(scores), 0.5) - assert weak == {"10:00": 9.0, "10:02": 10.0, "10:04": 11.0} - assert weak_conflicts == conflicts and weak_elim == set() - full, full_conflicts, _ = lib.apply_scaled_answer(scores, conflicts, set(), _probe(), "no", list(scores), 1.0) - assert full == {"10:00": 8.0, "10:02": 10.0, "10:04": 12.0} - assert full_conflicts["10:00"] == 1 - - -def test_absent_years_are_gaps_strictly_inside_each_domain_span() -> None: - events = [ - {"domain": "career", "date": "2017-05-01", "precision": "day"}, - {"domain": "career", "date": "2019", "precision": "year"}, - {"domain": "career", "date": "2025-02", "precision": "month"}, - {"domain": "relocation", "date": "2000", "precision": "year"}, - ] - assert lib.absent_years(events) == {"career": [2018, 2020, 2021, 2022, 2023, 2024]} - - -def test_degrade_and_upgrade_precision_helpers() -> None: - events = [{"id": "a", "domain": "career", "date": "2017-05-20", "precision": "day"}, - {"id": "b", "domain": "career", "date": "2019", "precision": "year"}] - spoken = lib.degrade_to_year(events) - assert spoken[0]["precision"] == "year" and spoken[0]["date"] == "2017" - assert spoken[1] == events[1] - upgraded = lib.upgrade_to_month(spoken, {"a"}, {e["id"]: e for e in events}) - assert upgraded[0]["precision"] == "month" and upgraded[0]["date"] == "2017-05" - shifted = lib.shift_day_events_by_months(events, seed="fictional") - assert shifted[0]["shift_months"] in {-3, -2, -1, 1, 2, 3} - assert shifted[1] == events[1] - assert lib.drop_events(events, 1, seed="x") != events and len(lib.drop_events(events, 1, seed="x")) == 1 - - -def test_softmax_and_proportional_percent_sum_to_about_one_hundred() -> None: - scores = {"10:00": 12.0, "10:02": 11.0, "10:04": 9.0} - assert abs(sum(lib.percent_proportional(scores).values()) - 100) <= 2 - soft = lib.percent_softmax(scores) - assert abs(sum(soft.values()) - 100) <= 2 and soft["10:00"] > soft["10:02"] > soft["10:04"] - assert lib.calibration_bins([(0.9, True), (0.02, False)])[-1]["observed_rate"] == 1.0 - - -@pytest.mark.skipif(not HOLDOUT_V4.exists(), reason="v4 open set not present") -def test_recording_scorer_reconciles_with_production_on_a_public_case() -> None: - from scripts.active_rectification_event_engine import compute_candidate_static_contexts - from scripts.rectification.scoring_service import build_event_contribution_matrix, score_from_matrix - from scripts.research.minute_resolution_sweep import scoring_request_for - - case = json.loads(HOLDOUT_V4.read_text(encoding="utf-8"))["cases"][0] - request = scoring_request_for({**case, "candidate_radius_minutes": 10}, 10) - contexts = compute_candidate_static_contexts(request) - production = score_from_matrix(request, build_event_contribution_matrix(request, static_contexts=contexts)) - store = lib.FeatureStore() - built = build_event_contribution_matrix( - request, row_provider=lib.make_recording_provider(contexts, store, lib.d60_charts(contexts)), static_contexts=contexts, - ) - research = score_from_matrix(request, built) - outcome = lib.reconcile_rows(production, research) - assert outcome["changed"] == 0, outcome - assert outcome["candidates"] == len(contexts) == 11 - # extras were recorded alongside the production rules - recorded = {name for cells in store.rows.values() for cell in cells.values() for name in cell["extras"]} - assert any(name.startswith("kp_") for name in recorded) or any(name.endswith("_in_target_house") for name in recorded) diff --git a/tests/test_sealed_holdout_contract_freshness.py b/tests/test_sealed_holdout_contract_freshness.py deleted file mode 100644 index ec3b08f8e..000000000 --- a/tests/test_sealed_holdout_contract_freshness.py +++ /dev/null @@ -1,262 +0,0 @@ -from __future__ import annotations - -import json -from pathlib import Path - -import pytest - -from scripts.minute_rectification_blind_eval import implementation_sha256, summarize_trials -from scripts.rectification.sealed_holdout import holdout_passed, load_sealed_minute_holdout -from scripts.research.sealed_holdout_rerun import ( - ARCHIVE, DATASET, FREEZE, REPORT, LEGACY_REPORT, PRODUCTION_FILES, file_sha256, - freeze_record, historical_comparison, implementation_identity, run, -) - -ROOT = Path(__file__).resolve().parents[1] -MIDNIGHT_DATE_ANCHOR_PRODUCTION_FILES = { - "scripts/rectification/candidate_window.py", - "scripts/rectification/decision_policy.py", - "scripts/rectification/refinement_packet.py", - "scripts/rectification/api_service.py", -} -IDENTITY_FORBIDDEN_PREFIXES = ( - "references/rectification_sealed_holdout.v1.json", - "docs/research/sealed_holdout_rerun_midnight_anchor_2026_09_21", - "docs/research/reported_offset_midnight_anchor_2026_09_21", - "docs/research/sealed_holdout_rerun_quality_wording_2026_09_29", - "docs/research/reported_offset_quality_wording_2026_09_29", - "docs/research/sealed_holdout_rerun_functional_v2_2026_10_02", - "docs/research/reported_offset_functional_v2_2026_10_02", - "docs/research/sealed_holdout_rerun_upstream_sync4_2026_10_02", - "docs/research/reported_offset_upstream_sync4_2026_10_02", - "docs/research/sealed_holdout_rerun_upstream_sync5_2026_10_02", - "docs/research/reported_offset_upstream_sync5_2026_10_02", - "docs/research/sealed_holdout_rerun_astrologer_rulings_batch1_2026_10_03", - "docs/research/reported_offset_astrologer_rulings_batch1_2026_10_03", - # 原值: 身份清单只排除到 batch1 冻结路径 - # 新值: 再排除 upstream_sync6_2026_10_07 两份冻结路径 - # 原因: ERR-110,D5/D11 与 scoring-11 改了冻结文件,另存新记录,旧记录留在清单外 - "docs/research/sealed_holdout_rerun_upstream_sync6_2026_10_07", - "docs/research/reported_offset_upstream_sync6_2026_10_07", - # 原值: 排除到 upstream_sync6_2026_10_07 - # 新值: 再排除 ephemeris_nutation_2026_10_08 两份冻结路径 - # 原因: ERR-110,章动修正与 scoring-12 改了冻结身份,另存新记录,旧记录留在清单外(BUG-1275) - "docs/research/sealed_holdout_rerun_ephemeris_nutation_2026_10_08", - "docs/research/reported_offset_ephemeris_nutation_2026_10_08", - # 原值: 排除到 ephemeris_nutation_2026_10_08 - # 新值: 再排除 scoring_perf_2026_10_13 两份冻结路径 - # 原因: BUG-1323~1325 改了冻结身份文件,输出不变,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_scoring_perf_2026_10_13", - "docs/research/reported_offset_scoring_perf_2026_10_13", - # 原值: 排除到 scoring_perf_2026_10_13 - # 新值: 再排除 upstream_sync8_2026_10_18 两份冻结路径 - # 原因: sync8 改了冻结身份文件,输出不变,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_upstream_sync8_2026_10_18", - "docs/research/reported_offset_upstream_sync8_2026_10_18", - # 原值: 排除到 upstream_sync8_2026_10_18 - # 新值: 再排除 upstream_sync9b_2026_10_28 两份冻结路径(追加,不替换上面的) - # 原因: sync9b 改了扩展身份里的 scripts/varga.py,回放输出不变,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_upstream_sync9b_2026_10_28", - "docs/research/reported_offset_upstream_sync9b_2026_10_28", - # 原值: 排除到 upstream_sync9b_2026_10_28 - # 新值: 再排除 d60_mapping_2026_10_29 两份冻结路径(追加,不替换上面的) - # 原因: BUG-1500 修正生产 D60 映射,varga.py 变了,回放输出不变,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_d60_mapping_2026_10_29", - "docs/research/reported_offset_d60_mapping_2026_10_29", - # 原值: 排除到 d60_mapping_2026_10_29 - # 新值: 再排除 data_audit_2026_11_04 两份冻结路径(追加,不替换上面的) - # 原因: 数据核对 BUG-1545 / BUG-1546 改了冻结身份文件,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_data_audit_2026_11_04", - "docs/research/reported_offset_data_audit_2026_11_04", - # 原值: 排除到 data_audit_2026_11_04 - # 新值: 再排除 moon_paksha_2026_11_04 两份冻结路径(追加,不替换上面的) - # 原因: BUG-1557 月亮 Paksha 口径改了冻结身份里的 shadbala.py,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_moon_paksha_2026_11_04", - "docs/research/reported_offset_moon_paksha_2026_11_04", - # 原值: 排除到 moon_paksha_2026_11_04 - # 新值: 再排除各分支中间记录 audit_g / audit_h / audit_j 与合并后的 audit_wave2_2026_11_04 冻结路径(追加,不替换上面的) - # 原因: 数据核对第二波 BUG-1560 / BUG-1561(varga.py、divisional_charts_extended.py)、BUG-1566 / BUG-1567(jaimini.py)、BUG-1270 / BUG-1576(shadbala.py)改了冻结身份文件,ERR-110 在合并后的代码上另存一份新记录;各分支的 audit_g / audit_h / audit_j 只对各自分支成立,原样保留为中间记录 - "docs/research/sealed_holdout_rerun_audit_g_2026_11_04", - "docs/research/reported_offset_audit_g_2026_11_04", - "docs/research/sealed_holdout_rerun_audit_h_2026_11_04", - "docs/research/reported_offset_audit_h_2026_11_04", - "docs/research/sealed_holdout_rerun_audit_j_2026_11_04", - "docs/research/reported_offset_audit_j_2026_11_04", - "docs/research/sealed_holdout_rerun_audit_wave2_2026_11_04", - "docs/research/reported_offset_audit_wave2_2026_11_04", - # 原值: 排除到 audit_wave2_2026_11_04 - # 新值: 再排除 d30_venus_2026_11_04 两份冻结路径(追加,不替换上面的) - # 原因: 产品 2026-11-04 决定 BUG-1560(varga.py 偶数星座 D30)与 BUG-1570(白羊 / 天蝎金星功能凶)入算、scoring-13,冻结身份与回放结果都变了,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_d30_venus_2026_11_04", - "docs/research/reported_offset_d30_venus_2026_11_04", - # 原值: 排除到 d30_venus_2026_11_04 - # 新值: 再排除 astrologer_166_2026_11_04 两份冻结路径(追加,不替换上面的) - # 原因: #166 占星师裁定(BUG-1581~1589,产品 2026-11-04 决定交付)改了 shadbala.py、jaimini.py、varga.py、divisional_charts_extended.py,scoring-14,冻结身份与回放结果都变了,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_astrologer_166_2026_11_04", - "docs/research/reported_offset_astrologer_166_2026_11_04", - # 原值: 排除到 astrologer_166_2026_11_04;新值: 再排除 astrologer_166b_2026_11_04(追加) - # 原因: #166 第二批(BUG-1590~1598)改了 functional_benefics.py、jaimini.py、narayana_dasha.py、shadbala.py、varga.py,scoring-15,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_astrologer_166b_2026_11_04", - "docs/research/reported_offset_astrologer_166b_2026_11_04", - # 原值: 排除到 astrologer_166b_2026_11_04;新值: 再排除 astrologer_166c_2026_11_05(追加) - # 原因: #166 占星师 2026-11-05 答复(BUG-1622~1626)改了 shadbala.py 的标签与共用水星规则函数,数值不变,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_astrologer_166c_2026_11_05", - "docs/research/reported_offset_astrologer_166c_2026_11_05", - # 原值: 排除到 astrologer_166c_2026_11_05;新值: 再排除 astrologer_166d_2026_11_05(追加) - # 原因: BUG-1622~1626 改号改了 shadbala.py 与回放脚本的注释,ERR-110 另存新记录 - "docs/research/sealed_holdout_rerun_astrologer_166d_2026_11_05", - "docs/research/reported_offset_astrologer_166d_2026_11_05", - "docs/research/history/", - "artifacts/", -) - - -def read(path): - return json.loads(path.read_text(encoding="utf-8")) - - -def test_midnight_date_anchor_modules_remain_in_extended_identity(): - dataset = read(DATASET) - identity = implementation_identity() - legacy = set(dataset["frozen_scoring"]["files"]) - assert len(legacy) == 12 - assert MIDNIGHT_DATE_ANCHOR_PRODUCTION_FILES <= set(PRODUCTION_FILES) - assert MIDNIGHT_DATE_ANCHOR_PRODUCTION_FILES <= set(identity["production_scoring_files"]) - assert MIDNIGHT_DATE_ANCHOR_PRODUCTION_FILES.isdisjoint(legacy) - for path in sorted(MIDNIGHT_DATE_ANCHOR_PRODUCTION_FILES): - assert (ROOT / path).is_file() - assert identity["file_sha256"][path] == file_sha256(ROOT / path) - assert not any( - path == prefix or path.startswith(prefix) - for path in identity["file_sha256"] - for prefix in IDENTITY_FORBIDDEN_PREFIXES - ) - - -def test_functional_roles_are_part_of_the_production_identity(): - """BUG-1181: functional benefic / malefic roles feed the event matrix, so a - change there must invalidate the frozen records like any scorer change.""" - identity = implementation_identity() - assert "scripts/functional_benefics.py" in PRODUCTION_FILES - assert identity["file_sha256"]["scripts/functional_benefics.py"] == file_sha256(ROOT / "scripts/functional_benefics.py") - - -def test_contract_tracks_actual_current_scorer_and_dataset_audit(): - dataset = read(DATASET) - contract = read(ROOT / "references/rectification_sealed_holdout.v1.json") - actual_hash = implementation_sha256(dataset["frozen_scoring"]["files"]) - assert contract["current_tree_scorer"]["implementation_sha256"] == actual_hash - assert contract["current_tree_scorer"]["extended_identity"] == implementation_identity() - historical_contract = read(ARCHIVE / "references/rectification_sealed_holdout.v1.json") - runtime_keys = ("status", "valid_public_aa_cases", "required_cases", "top_1_rate", "confirmation_coverage_rate", "sealed_benchmark_id") - for key in runtime_keys: - assert type(contract[key]) is type(historical_contract[key]) - assert contract[key] == historical_contract[key] - assert contract["source_audit_status"] == dataset["source_audit_status"] - assert contract["evaluated_on"] == read(REPORT)["evaluated_on"] - assert contract["status"] == "not_ready" - assert contract["confirmation_coverage_rate"] == 0.0 - assert holdout_passed(load_sealed_minute_holdout()) is False - - -def test_frozen_record_matches_dataset_scorer_and_evaluator_bytes(): - frozen = read(FREEZE) - actual = freeze_record() - assert {key: value for key, value in frozen.items() if key != "frozen_at_utc"} == { - key: value for key, value in actual.items() if key != "frozen_at_utc" - } - assert frozen["dataset_sha256"] == file_sha256(DATASET) - assert len(frozen["files"]) == 12 - assert read(DATASET)["frozen_scoring"]["implementation_sha256"] == frozen["historical_frozen_sha256"] - assert frozen["extended_identity"] == implementation_identity() - assert set(PRODUCTION_FILES) <= set(frozen["extended_identity"]["production_scoring_files"]) - assert {"scripts/rectification/scoring_service.py", "scripts/rectification/dasha_transition_proximity.py"} <= set(PRODUCTION_FILES) - assert MIDNIGHT_DATE_ANCHOR_PRODUCTION_FILES <= set(PRODUCTION_FILES) - for path, digest in frozen["extended_identity"]["file_sha256"].items(): - assert digest == file_sha256(ROOT / path) - - -def test_fixed_protocol_rerun_is_auditable_but_never_independent_blind(): - report = read(REPORT) - contract = read(ROOT / "references/rectification_sealed_holdout.v1.json") - scorer = contract["current_tree_scorer"] - rerun = contract["current_tree_fixed_protocol_rerun"] - assert report["frozen_record"] == read(FREEZE) - assert report["frozen_record"]["frozen_at_utc"] <= report["replay_started_at_utc"] <= report["replay_finished_at_utc"] - assert scorer["extended_identity"] == report["frozen_record"]["extended_identity"] - assert rerun["extended_identity"] == scorer["extended_identity"] - assert rerun["freeze_record_path"] == FREEZE.relative_to(ROOT).as_posix() - assert report["historical_comparison"] == historical_comparison(LEGACY_REPORT, report["trials"], ("case_ordinal",)) - assert report["trial_count"] == len(report["trials"]) == 20 - assert report["excluded_cases"] == [] - aggregate = summarize_trials(report["trials"], read(DATASET)["release_metrics"]) - assert report["metrics"] == aggregate["metrics"] == scorer["metrics"] - assert report["metric_gates_passed"] == aggregate["metric_gates_passed"] - assert scorer["source_report"] == REPORT.relative_to(ROOT).as_posix() - assert scorer["implementation_sha256"] == report["frozen_record"]["implementation_sha256"] - assert scorer["fixed_protocol_rerun_trial_count"] == report["trial_count"] - assert scorer["fixed_protocol_rerun_hash_matches"] is True - assert scorer["official_eval_trial_count"] == report["official_blind_trial_count"] == 0 - assert scorer["official_eval_implementation_hash_matches"] is False - for item in (rerun, report): - assert item["official_valid_independent_blind"] is False - assert item["is_blind_evaluation"] is False - assert item["truth_hidden_from_ranker"] is True - assert item["results_previously_seen"] is True - assert item["verified_minute_claim_allowed"] is False - assert rerun["must_not_claim_as_release_metrics"] is True - assert all(row["event_count"] == 3 for row in report["trials"]) - # Never persist actual candidate/truth times or coordinates in report artifacts. - for row in report["trials"]: - assert not ({"predicted_time", "published_truth_revealed_after_ranking", "latitude", "longitude"} & row.keys()) - - -def test_changed_frozen_identity_fails_before_any_replay(tmp_path, monkeypatch): - frozen = read(FREEZE) - frozen["implementation_sha256"] = "0" * 64 - path = tmp_path / "bad-freeze.json" - path.write_text(json.dumps(frozen), encoding="utf-8") - def unexpected(*args, **kwargs): - raise AssertionError("must reject identity before scoring") - monkeypatch.setattr("scripts.research.sealed_holdout_rerun.build_feature_fact_rows", unexpected) - with pytest.raises(ValueError, match="frozen_record_mismatch:implementation_sha256"): - run(path) - - -@pytest.mark.parametrize("path", ["scripts/rectification/scoring_service.py", "scripts/rectification/dasha_transition_proximity.py"]) -def test_extended_identity_drift_rejected_even_when_legacy_hash_unchanged(tmp_path, monkeypatch, path): - from scripts.research import sealed_holdout_rerun as replay - frozen = replay.freeze_record() - freeze_path = tmp_path / "extended-freeze.json" - freeze_path.write_text(json.dumps(frozen), encoding="utf-8") - original = replay.implementation_identity - def changed(dataset=DATASET): - actual = original(dataset) - actual["file_sha256"][path] = "0" * 64 - return actual - monkeypatch.setattr(replay, "implementation_identity", changed) - def unexpected(*args, **kwargs): - raise AssertionError("extended drift must reject before shadow scoring") - monkeypatch.setattr(replay, "build_feature_fact_rows", unexpected) - assert frozen["implementation_sha256"] == replay.freeze_record()["implementation_sha256"] - with pytest.raises(ValueError, match="frozen_record_mismatch:extended_identity"): - replay.run(freeze_path) - - -def test_historical_artifacts_are_byte_preserved_not_refreshed(): - manifest = read(ARCHIVE / "manifest.json") - assert file_sha256(ARCHIVE / "manifest.json") == "6102a26a840be207b5858b3a4c0509274468ae9071e86d308cbbac7371d6864e" - assert len(manifest["files"]) == 8 - for record in manifest["files"]: - archived = ROOT / record["archive_path"] - assert archived.stat().st_size == record["size_bytes"] - assert file_sha256(archived) == record["sha256"] - old_freeze = ROOT / "docs/research/sealed_holdout_rerun_2026_09_20.freeze.json" - assert old_freeze.read_bytes() == (ARCHIVE / old_freeze.relative_to(ROOT)).read_bytes() - assert file_sha256(old_freeze) == "d17651cb50224acdd1af7a4692c777ed169b216a962a0675371254ce561d0921" - assert FREEZE != old_freeze - for name, digest in ( - ("reported_offset_2026_09_20.json", "9878f2b50c957a470fafcb2ed0a9eb16405c3f6fa422ea50f467e84b0189ace1"), - ("sealed_holdout_rerun_2026_09_20.json", "40df220bfcb51a683b31fbd626896e47a5aed7ee4f30ff669543691f7ce53c1e"), - ): - assert file_sha256(ARCHIVE / "docs/research" / name) == digest diff --git a/tests/test_timing_rectification_reviewer_freeze_status_2026_07_23.py b/tests/test_timing_rectification_reviewer_freeze_status_2026_07_23.py deleted file mode 100644 index ff3cfa0d6..000000000 --- a/tests/test_timing_rectification_reviewer_freeze_status_2026_07_23.py +++ /dev/null @@ -1,36 +0,0 @@ -import json -from pathlib import Path - -from scripts.timing_rectification_reviewer_freeze_status_2026_07_23 import build_report - - -ROOT = Path(__file__).resolve().parents[1] -STATUS = ROOT / "references/real_case_calibration/timing_rectification_reviewer_freeze_status_2026_07_23.json" -INDEX = ROOT / "references/oracle/evidence_packet_index_2026_07_19.json" - - -def test_reviewer_1_confirmation_is_recorded_without_blind_replay_upgrade() -> None: - data = json.loads(STATUS.read_text(encoding="utf-8")) - - assert data == build_report() - assert data["claim_status"] == "one_reviewer_confirmed_second_required" - assert data["truth_matrix_allowed"] is False - assert data["production_tuning_allowed"] is False - assert data["reviewer_1"]["confirmation_text"] == "我确认这 3 个候选案例可以作为第一轮 holdout。" - assert data["reviewer_2_required"] is True - assert data["summary"] == { - "case_count": 3, - "reviewer_1_confirmed_count": 3, - "reviewer_2_confirmed_count": 0, - "ready_for_blind_replay_count": 0, - } - assert "does not satisfy the two-reviewer freeze requirement" in data["boundary"] - - -def test_reviewer_freeze_status_is_indexed_as_human_review_required() -> None: - packets = {packet["packet_id"]: packet for packet in json.loads(INDEX.read_text(encoding="utf-8"))["packets"]} - packet = packets["timing_rectification_reviewer_freeze_status_2026_07_23"] - - assert packet["claim_status"] == "one_reviewer_confirmed_second_required" - assert packet["consumer_policy"] == "human_review_required" - assert "reviewer 2 is still missing" in packet["claim_boundary"] diff --git a/tests/test_varga_resolution_research.py b/tests/test_varga_resolution_research.py deleted file mode 100644 index ddd6c27aa..000000000 --- a/tests/test_varga_resolution_research.py +++ /dev/null @@ -1,221 +0,0 @@ -"""Regression tests for the varga-resolution research scripts -(TASK-rectification-varga-resolution-research-20260930). - -Pure-function tests run on synthetic data. The reproduction test reads the -committed baseline JSON and locks the numbers the brief was written from; it is -skipped when the JSON has not been generated in this checkout. -""" - -from __future__ import annotations - -import json -import unittest -from pathlib import Path - -from scripts.research import varga_resolution_lib as vr - -ROOT = Path(__file__).resolve().parents[1] -BASELINE = ROOT / "docs" / "research" / "varga_resolution_baseline_2026_09_30.json" - - -def _signs(pattern: dict[str, list[int]], radius: int) -> dict[int, dict[str, int]]: - """Build {offset: {varga: sign}} from per-varga sign lists covering -radius..radius.""" - out: dict[int, dict[str, int]] = {} - for position, offset in enumerate(range(-radius, radius + 1)): - out[offset] = {name: values[position] for name, values in pattern.items()} - return out - - -class ClockTests(unittest.TestCase): - def test_offset_nearest_across_midnight(self) -> None: - self.assertEqual(vr.offset_of("00:05", "23:55"), 10) - self.assertEqual(vr.offset_of("23:50", "00:10"), -20) - self.assertEqual(vr.offset_of("12:00", "12:00"), 0) - - def test_lmt_era_flag(self) -> None: - self.assertTrue(vr.is_lmt_era({"birth": {"date": "1859-05-22", "time": "04:55"}})) - self.assertFalse(vr.is_lmt_era({"birth": {"date": "1900-01-01", "time": "04:55"}})) - - -class SegmentTests(unittest.TestCase): - def setUp(self) -> None: - # radius 3 → offsets -3..3; D9 changes sign at offset 0, D10 at offset -2 and +2. - self.signs = _signs({ - "D1": [4, 4, 4, 4, 4, 4, 4], - "D9": [7, 7, 7, 8, 8, 8, 8], - "D10": [1, 2, 2, 2, 2, 3, 3], - "D12": [0, 0, 1, 1, 2, 2, 3], - }, 3) - - def test_single_varga_segments(self) -> None: - d9 = vr.segments_for(self.signs, ("D9",)) - self.assertEqual([(s["start"], s["end"], s["key"]) for s in d9], [(-3, -1, (7,)), (0, 3, (8,))]) - self.assertEqual(vr.segment_index_of(d9, 0), 1) - self.assertEqual(vr.segment_index_of(d9, -3), 0) - self.assertIsNone(vr.segment_index_of(d9, 9)) - - def test_joint_segments_split_on_any_change(self) -> None: - joint = vr.segments_for(self.signs, ("D1", "D9", "D10")) - self.assertEqual([(s["start"], s["end"]) for s in joint], [(-3, -3), (-2, -1), (0, 1), (2, 3)]) - self.assertEqual(vr.distinct_signs(self.signs, 3, ("D1",)), 1) - self.assertEqual(vr.distinct_signs(self.signs, 3, ("D10",)), 3) - self.assertEqual(vr.distinct_signs(self.signs, 1, ("D9", "D10")), 2) - - def test_count_table_shape(self) -> None: - table = vr.count_table({"a": self.signs, "b": self.signs}, radii=(1, 3)) - self.assertEqual(table["3"]["D1"], {"single": 2, "n": 2, "mean": 1.0, "max": 1}) - self.assertEqual(table["1"]["D9"]["mean"], 2.0) - self.assertEqual(table["3"]["D1xD9xD10"]["max"], 4) - - -class ShareTests(unittest.TestCase): - def setUp(self) -> None: - self.true_time = "10:00" - self.signs = _signs({"D9": [7, 7, 7, 8, 8, 8, 8]}, 3) - self.segments = vr.segments_for(self.signs, ("D9",)) - - def test_segment_shares_and_truth(self) -> None: - weights = {"09:58": 1.0, "09:59": 1.0, "10:00": 3.0, "10:02": 1.0} - share = vr.segment_shares(weights, self.segments, self.true_time) - self.assertEqual(share["truth_segment"], 1) - self.assertEqual(share["top_segment"], 1) - self.assertTrue(share["top_is_truth"]) - self.assertTrue(share["truth_retained"]) - self.assertAlmostEqual(share["top_share"], 4 / 6, places=6) - self.assertEqual(share["alive_segments"], 2) - - def test_truth_segment_can_be_lost(self) -> None: - share = vr.segment_shares({"09:57": 2.0}, self.segments, self.true_time) - self.assertFalse(share["truth_retained"]) - self.assertFalse(share["top_is_truth"]) - self.assertEqual(share["alive_segments"], 1) - - def test_minute_weights_modes(self) -> None: - state = { - "valid": [ - {"time": "09:58", "score": 4.0, "cluster_times": ["09:58", "10:00"]}, - {"time": "10:02", "score": -1.0, "cluster_times": ["10:02"]}, - ], - "public": [], - "eliminated": set(), - "scores": {"09:58": 4.0, "10:02": -1.0}, - } - raw = vr.minute_weights(state, "raw") - self.assertEqual(raw, {"09:58": 2.0, "10:00": 2.0, "10:02": 0.0}) - percent = vr.minute_weights(state, "percent") - self.assertAlmostEqual(percent["09:58"] + percent["10:00"], 1.0) - uniform = vr.minute_weights(state, "uniform") - self.assertEqual(set(uniform.values()), {1.0}) - - -class InformationGainTests(unittest.TestCase): - def setUp(self) -> None: - self.true_time = "10:00" - self.signs = _signs({"D9": [7, 7, 7, 8, 8, 8, 8]}, 3) - self.segments = vr.segments_for(self.signs, ("D9",)) - self.weights = {"09:57": 1.0, "09:58": 1.0, "09:59": 1.0, "10:00": 1.0, "10:01": 1.0, "10:02": 1.0, "10:03": 1.0} - - @staticmethod - def _probe(yes: list[str], no: list[str]) -> dict: - return {"expected_outcomes": [ - {"answer_class": "yes", "supports": yes, "conflicts": no}, - {"answer_class": "no", "supports": no, "conflicts": yes}, - ]} - - def test_probe_aligned_with_segment_boundary_has_full_gain(self) -> None: - aligned = self._probe(["09:57", "09:58", "09:59"], ["10:00", "10:01", "10:02", "10:03"]) - within = self._probe(["10:00", "10:01"], ["10:02", "10:03"]) - gain_aligned = vr.segment_information_gain(aligned, self.weights, self.segments, self.true_time) - gain_within = vr.segment_information_gain(within, self.weights, self.segments, self.true_time) - self.assertGreater(gain_aligned, gain_within) - # aligned probe resolves the two-segment variable completely: gain == H(prior) - self.assertAlmostEqual(gain_aligned, vr._entropy([3.0, 4.0]), places=5) - self.assertAlmostEqual(gain_within, 0.0, places=6) - - def test_selection_prefers_aligned_probe_first(self) -> None: - public = [{"time": t, "score": 1.0, "cluster_times": [t]} for t in self.weights] - within = self._probe(["10:00", "10:01"], ["10:02", "10:03"]) - aligned = self._probe(["09:57", "09:58", "09:59"], ["10:00", "10:01", "10:02", "10:03"]) - state = vr.select_probes_by_segment(public, [within, aligned], self.segments, self.true_time, ask_count=1) - self.assertIs(state["asked"][0], aligned) - self.assertEqual(state["answered"], 1) - - def test_stop_rule_stops_before_asking(self) -> None: - public = [{"time": t, "score": (5.0 if t >= "10:00" else 0.0), "cluster_times": [t]} for t in self.weights] - aligned = self._probe(["09:57", "09:58", "09:59"], ["10:00", "10:01", "10:02", "10:03"]) - state = vr.select_probes_by_segment(public, [aligned], self.segments, self.true_time, ask_count=1, stop_share=0.8) - self.assertEqual(state["asked"], []) - - -class ThresholdTests(unittest.TestCase): - def test_full_fit_table(self) -> None: - points = [(0.95, True), (0.85, True), (0.75, False), (0.65, True), (0.55, False)] - table = {row["threshold"]: row for row in vr.threshold_table(points)} - self.assertEqual(table[0.9], {"threshold": 0.9, "n": 1, "accuracy": 1.0}) - self.assertEqual(table[0.5]["n"], 5) - self.assertAlmostEqual(table[0.5]["accuracy"], 0.6) - - def test_loo_threshold_never_sees_the_held_out_case(self) -> None: - points = [(0.95, True)] * 6 + [(0.55, False)] * 6 - result = vr.loo_threshold(points, target=0.8, min_training=3) - self.assertEqual(result["confident_n"], 6) - self.assertEqual(result["confident_accuracy"], 1.0) - self.assertEqual(result["not_confident_n"], 6) - self.assertEqual(result["no_threshold_folds"], 0) - - def test_loo_threshold_reports_when_no_threshold_reaches_target(self) -> None: - points = [(0.9, False), (0.9, False), (0.9, True), (0.6, False), (0.6, False), (0.6, True)] - result = vr.loo_threshold(points, target=0.9, min_training=3) - self.assertEqual(result["confident_n"], 0) - self.assertEqual(result["no_threshold_folds"], 6) - - -class FlipTests(unittest.TestCase): - def test_flipped_answers_invert_exactly_k(self) -> None: - probes = [ - {"expected_outcomes": [{"answer_class": "yes", "supports": ["10:00"], "conflicts": ["10:02"]}]}, - {"expected_outcomes": [{"answer_class": "no", "supports": ["10:00"], "conflicts": ["10:02"]}]}, - {"expected_outcomes": [{"answer_class": "yes", "supports": ["10:02"], "conflicts": []}]}, - ] - base = [vr.optimal_answer(p, "10:00") for p in probes] - flipped = vr.flipped_answers(probes, "10:00", flips=1, seed="s") - changed = [i for i, (a, b) in enumerate(zip(base, flipped)) if a != b] - self.assertEqual(len(changed), 1) - self.assertIn(flipped[changed[0]], {"yes", "no"}) - # deterministic for the same seed - self.assertEqual(flipped, vr.flipped_answers(probes, "10:00", flips=1, seed="s")) - - -@unittest.skipUnless(BASELINE.exists(), "baseline JSON not generated in this checkout") -class BaselineReproductionTests(unittest.TestCase): - """Locks the two tables the brief was written from (77 v5 cases, raman / mean).""" - - @classmethod - def setUpClass(cls) -> None: - cls.payload = json.loads(BASELINE.read_text(encoding="utf-8")) - - def test_table1_signs_per_window(self) -> None: - table = self.payload["table1_signs_per_window"] - self.assertEqual(table["10"]["D1"]["single"], 64) - self.assertEqual(table["15"]["D1"]["single"], 51) - self.assertEqual(table["30"]["D1"]["single"], 37) - self.assertEqual(table["60"]["D1"]["single"], 10) - self.assertEqual(table["15"]["D9"]["mean"], 3.22) - self.assertEqual(table["15"]["D1xD9xD10"]["mean"], 5.27) - self.assertEqual(table["10"]["D1xD9xD10"]["mean"], 3.84) - - def test_table2_delivery_interval(self) -> None: - table = self.payload["table2_delivery_interval"] - self.assertEqual(table["10"]["truth_in_range"], 76) - self.assertEqual(table["10"]["D1"]["single"], 75) - self.assertEqual(table["10"]["D9"]["le2"], 68) - self.assertEqual(table["10"]["D9"]["mode_is_truth"], 68) - self.assertEqual(table["10"]["D10"]["le2"], 63) - self.assertEqual(table["10"]["D10"]["mode_is_truth"], 65) - self.assertEqual(table["10"]["D1xD9xD10"]["single"], 15) - self.assertEqual(table["30"]["D9"]["le2"], 24) - self.assertEqual(table["60"]["D10"]["mode_is_truth"], 25) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_varga_segments_api.py b/tests/test_varga_segments_api.py index da7bc03a2..1ee6b4962 100644 --- a/tests/test_varga_segments_api.py +++ b/tests/test_varga_segments_api.py @@ -5,26 +5,6 @@ import pytest from scripts import domain_calculation_service from scripts.rectification_varga_segments_api import scan_varga_segments -from scripts.research import varga_resolution_lib as vr - - -@pytest.mark.parametrize("radius", [10, 30, 60]) -def test_scan_matches_research_every_minute(radius, tmp_path): - case = vr.load_cases()[0] # Public AA calibration fixture, never a user profile. - origin = vr.birth_datetime(case) - body = {"start_at": (origin - timedelta(minutes=radius)).strftime("%Y-%m-%dT%H:%M"), - "end_at": (origin + timedelta(minutes=radius)).strftime("%Y-%m-%dT%H:%M"), - "latitude": case["birth"]["latitude"], "longitude": case["birth"]["longitude"], - "timezone_offset": case["birth"]["timezone_offset"], "target_charts": ["D1", "D9", "D10"]} - actual = scan_varga_segments(body, cache_dir=tmp_path) - signs = vr.signs_per_minute(case, radius, vargas=("D1", "D9", "D10")) - assert actual["window_minutes"] == 2 * radius + 1 - assert [minute["signs"] for minute in actual["minutes"]] == [signs[offset] for offset in range(-radius, radius + 1)] - for chart in body["target_charts"]: - expected = vr.segments_for(signs, (chart,)) - assert [(row["start"] - radius, row["end"] - radius, row["sign"]) for row in actual["segments"][chart]] == [(row["start"], row["end"], row["key"][0]) for row in expected] - assert scan_varga_segments(body, cache_dir=tmp_path) == actual - assert len(list(tmp_path.glob("*.json"))) == 1 def test_midnight_keeps_dates_and_offsets(tmp_path): diff --git a/tests/test_varga_style_calibration_report.py b/tests/test_varga_style_calibration_report.py deleted file mode 100644 index 6cfe1368a..000000000 --- a/tests/test_varga_style_calibration_report.py +++ /dev/null @@ -1,89 +0,0 @@ -from __future__ import annotations - -import json -import unittest -from pathlib import Path - -from scripts.rectification.varga_style_calibration_report import summarize - -ROOT = Path(__file__).resolve().parents[1] - - -def _answer(group: str, answer_class: str, recorded: str, chosen: str) -> dict: - other = "天蝎座" if recorded == "天秤座" else "天秤座" - yes_sign = chosen if answer_class == "yes" else other - weak_sign = chosen if answer_class == "weak_yes" else (recorded if recorded != yes_sign else other) - return { - "group": group, - "answer_class": answer_class, - "recorded_sign": recorded, - "options": [ - {"answer_class": "yes", "sign": yes_sign}, - {"answer_class": "weak_yes", "sign": weak_sign}, - ], - } - - -def _case(case_id: str, source: str, answers: list[dict], before: int = 2, after: int = 2) -> dict: - return { - "case_id_hash": case_id, - "birth_time_source": source, - "recorded_minute": "04:51", - "uncertainty_before_minutes": before, - "uncertainty_after_minutes": after, - "answers": answers, - } - - -class VargaStyleCalibrationReportTest(unittest.TestCase): - def test_random_third_and_high_hit_rate(self) -> None: - random_third = { - "cases": [ - _case("a", "hospital_record", [_answer("d9", "yes", "天秤座", "天秤座")]), - _case("b", "hospital_record", [_answer("d9", "yes", "天秤座", "天蝎座")]), - _case("c", "hospital_record", [_answer("d9", "weak_yes", "天秤座", "天蝎座")]), - ] - } - random_report = summarize(random_third) - self.assertEqual(random_report["d9"]["n"], 3) - self.assertEqual(random_report["d9"]["hit_rate"], 0.333) - self.assertEqual(random_report["d10"]["n"], 0) - self.assertIsNone(random_report["d10"]["hit_rate"]) - - high = { - "cases": [ - _case(str(index), "hospital_record", [ - _answer("d10", "yes", "巨蟹座", "巨蟹座" if index < 9 else "狮子座"), - ]) - for index in range(10) - ] - } - high_report = summarize(high) - self.assertEqual(high_report["d10"]["n"], 10) - self.assertEqual(high_report["d10"]["hit_rate"], 0.9) - - def test_filters_non_hospital_and_wide_uncertainty(self) -> None: - payload = { - "cases": [ - _case("hospital", "hospital_record", [_answer("nakshatra", "yes", "角宿", "角宿")]), - _case("approx", "approximate", [_answer("nakshatra", "yes", "角宿", "角宿")]), - _case("wide", "hospital_record", [_answer("nakshatra", "yes", "角宿", "角宿")], before=15, after=15), - ] - } - report = summarize(payload) - self.assertEqual(report["nakshatra"]["n"], 1) - self.assertEqual(report["nakshatra"]["hit_rate"], 1.0) - - def test_summary_has_no_case_ids(self) -> None: - payload = { - "cases": [ - _case("secret-hash", "hospital_record", [_answer("d9", "yes", "天秤座", "天秤座")]), - ] - } - dumped = json.dumps(summarize(payload), ensure_ascii=False) - self.assertNotIn("secret-hash", dumped) - self.assertNotIn("04:51", dumped) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_vedastro_negative_day_20261028.py b/tests/test_vedastro_negative_day_20261028.py index 725fa32fe..255e2804d 100644 --- a/tests/test_vedastro_negative_day_20261028.py +++ b/tests/test_vedastro_negative_day_20261028.py @@ -9,10 +9,7 @@ import time import pytest import scripts.vedastro_foreground as foreground -from scripts.rectification import vedastro_validate_cache as validate_cache -from scripts.jyotish_api_server import JyotishAPIHandler from scripts.vedastro_consultation_snapshot import DEFERRED_IN_CONSULTATION, lookup_negative_snapshot, store_negative_snapshot -from tests.test_rectification_v5_vedastro_validation import request BODY = {"year": 1990, "month": 3, "day": 14, "hour": 9, "minute": 30, "lat": 31.23, "lon": 121.47, "tz": 8, "ayanamsa": "lahiri", "today": "2026-10-28"} @@ -120,51 +117,6 @@ class FailingAdapter: raise TimeoutError("rate limited") -def test_a_failed_rectification_check_is_kept_for_the_evidence_and_pair(monkeypatch): - FailingAdapter.calls = 0 - monkeypatch.setattr("scripts.jyotish_api_server._load_local_module", lambda name: FailingAdapter) - handler = object.__new__(JyotishAPIHandler) - first = handler._compute_rectification_v5_vedastro_validate(request()) - calls = FailingAdapter.calls - second = handler._compute_rectification_v5_vedastro_validate(request()) - assert calls > 0 and FailingAdapter.calls == calls, "no VedAstro call the second time" - assert second == first and "vedastro_timeout" in first["blockers"] - # Another pair is other evidence. - handler._compute_rectification_v5_vedastro_validate(request(["05:14", "05:13"])) - assert FailingAdapter.calls > calls - - -def test_a_decided_result_is_not_kept(): - key = validate_cache.validation_key({"a": 1}, ["05:13", "05:14"]) - assert not validate_cache.remember_if_service_failure(key, {"passed": True, "blockers": []}) - assert not validate_cache.remember_if_service_failure(key, {"passed": False, "blockers": ["vedastro_minute_sensitive_layers_not_discriminated"]}) - assert validate_cache.remembered_failure(key) is None - assert validate_cache.remember_if_service_failure(key, {"passed": False, "blockers": ["vedastro_timeout"]}, now=1000.0) - assert validate_cache.remembered_failure(key, now=1000.0 + validate_cache.KEEP_SECONDS - 1) is not None - assert validate_cache.remembered_failure(key, now=1000.0 + validate_cache.KEEP_SECONDS + 1) is None - - -def test_the_check_stops_starting_calls_at_its_budget(): - now = [0.0] - seen = [] - budget = validate_cache.ValidateBudget(lambda: 4.0, seconds=11.0, clock=lambda: now[0]) - - def safe_call(call, *args, **kwargs): - from scripts.vedastro_runtime_context import timeout_override_seconds - seen.append(timeout_override_seconds()) - return call(*args, **kwargs) - - work = lambda: {"status": "ok"} - assert budget.call(safe_call, work) == {"status": "ok"} - now[0] = 8.5 - budget.call(safe_call, work) - now[0] = 10.5 - skipped = budget.call(safe_call, work) - assert seen == [None, 2.5], "full timeout with time to spare, the rest near the end" - assert skipped == {"available": False, "status": "timeout", "_failure_kind": "timeout"} - assert validate_cache.VALIDATE_BUDGET_SECONDS < 12, "under the frontend's 12 s wait" - - @pytest.fixture(autouse=True) def _fresh_executor_state(): yield