diff --git a/frontend/src/components/chart-choice/astrologer-stage.tsx b/frontend/src/components/chart-choice/astrologer-stage.tsx index f39d0d277..aafbec05a 100644 --- a/frontend/src/components/chart-choice/astrologer-stage.tsx +++ b/frontend/src/components/chart-choice/astrologer-stage.tsx @@ -16,6 +16,7 @@ import { isEventDate, isTied, offsetText, + provisionalCoverageText, pythonEngineText, readyEventCount, tieText, @@ -289,6 +290,7 @@ function Outcome({ packet, chartChoiceTime }: { readonly packet: AstrologerPacke
{pythonEngineText(result)}
{result.match_rate_same_for_all_candidates ?范围里每个分钟的吻合率都一样,这些事分不出前后。
: null} {result.stay_near_reported ?前几名分数挨得很近,按她的规则先以报的时间为主,这个时间只作候选。
: null} + {provisionalCoverageText(result) ?{provisionalCoverageText(result)}
: null}\{provisionalCoverageText\(result\)\}<\/p>/); + // Her method's result is display-only: nothing on the stage posts to the adopt route. + assert.doesNotMatch(stage, /chart-choice\/adopt/); + const adopt = readFileSync(new URL("../src/app/api/chart-choice/adopt/route.ts", import.meta.url), "utf8"); + assert.doesNotMatch(adopt, /python_engine|astrologer|winning_segment/); +}); diff --git a/scripts/active_rectification_event_engine.py b/scripts/active_rectification_event_engine.py index f980907cd..3cf1e0b32 100644 --- a/scripts/active_rectification_event_engine.py +++ b/scripts/active_rectification_event_engine.py @@ -25,6 +25,7 @@ from scripts.active_rectification_events import ( LifeEvent, RectificationEventRequest, adjudicate_candidate_rows, + independent_events, precision_weight, ) @@ -719,8 +720,9 @@ def _candidate_row( moon_longitude = planet_longitudes["Moon"] evidence: list[CandidateEvidence] = [] missing_layers: list[str] = [] + layer_points: dict[str, dict[str, float]] = {} - for event in request["events"]: + for event in independent_events(request["events"])[0]: event_at = _event_datetime(event) prefixes, _ = DOMAIN_CONFIG[event["domain"]] domain_vargas = [varga_charts[prefix] for prefix in prefixes] @@ -763,6 +765,8 @@ def _candidate_row( arudha_padas=arudha_padas, functional=context.get("functional_profile"), )) + # Comparability policy (占星师 2026-11-08 验收清单 §6): points of each layer actually computed. + event_layers = layer_points.setdefault(event["id"], {"dasha_varga_core": evidence[-1]["points"]}) transit_rules = _controlled_transit_rules( request, event, @@ -770,15 +774,19 @@ def _candidate_row( DOMAIN_CONFIG[event["domain"]][1], context.get("_transit_chart_cache"), ) + transit_points = 0.25 * len(transit_rules) * precision_weight(event["precision"]) + event_layers["controlled_transit"] = transit_points if transit_rules: evidence[-1]["rule_ids"].extend(transit_rules) - evidence[-1]["points"] = round(evidence[-1]["points"] + 0.25 * len(transit_rules) * precision_weight(event["precision"]), 4) + evidence[-1]["points"] = round(evidence[-1]["points"] + transit_points, 4) av_rules, av_points = _ashtakavarga_auxiliary( chart, ascendant_index, DOMAIN_CONFIG[event["domain"]][1], context.get("ashtakavarga_result"), ) + if context.get("ashtakavarga_result") is not None: + event_layers["Ashtakavarga"] = av_points * precision_weight(event["precision"]) if av_rules: evidence[-1]["rule_ids"].extend(av_rules) evidence[-1]["points"] = round(evidence[-1]["points"] + av_points * precision_weight(event["precision"]), 4) @@ -788,6 +796,8 @@ def _candidate_row( vimshottari, context.get("shadbala_result"), ) + if context.get("shadbala_result") is not None: + event_layers["Shadbala"] = shadbala_points * precision_weight(event["precision"]) if shadbala_rules: evidence[-1]["rule_ids"].extend(shadbala_rules) evidence[-1]["points"] = round(evidence[-1]["points"] + shadbala_points * precision_weight(event["precision"]), 4) @@ -800,6 +810,7 @@ def _candidate_row( missing_layers + [layer for layer in context["feature"]["blocked_layers"] if layer not in OBSERVATION_ONLY_LAYERS] )), + "layer_points": layer_points, } @@ -881,16 +892,20 @@ def adjudicate_event_candidate_rows( normalized = json.dumps(request, ensure_ascii=True, sort_keys=True, separators=(",", ":")) fingerprint = hashlib.sha256(normalized.encode("utf-8")).hexdigest() input_contract, input_hash = _canonical_input_contract(request) - leave_one_out = _leave_one_event_out(rows, request["events"]) - return adjudicate_candidate_rows( + # A repeated fact (same domain, date and precision) is the same test, not independent support (§6). + events, duplicate_ids = independent_events(request["events"]) + leave_one_out = _leave_one_event_out(rows, events) + result = adjudicate_candidate_rows( rows, - event_count=len(request["events"]), - domain_count=len({event["domain"] for event in request["events"]}), + event_count=len(events), + domain_count=len({event["domain"] for event in events}), request_fingerprint=fingerprint, canonical_input_hash=input_hash, calculation_contract=input_contract, leave_one_event_out=leave_one_out, ) + result["duplicate_event_ids"] = duplicate_ids + return result def compute_event_candidate_rows( diff --git a/scripts/active_rectification_events.py b/scripts/active_rectification_events.py index 945646ecc..ae7614ad8 100644 --- a/scripts/active_rectification_events.py +++ b/scripts/active_rectification_events.py @@ -84,6 +84,8 @@ class CandidateScoreRow(TypedDict): score: float evidence: list[CandidateEvidence] missing_layers: list[str] + # Per scored event, the points of each evidence layer that was actually computed (comparability policy). + layer_points: NotRequired[dict[str, dict[str, float]]] class WinningSegment(TypedDict): @@ -110,6 +112,10 @@ class CandidateResult(TypedDict): calculation_contract: dict[str, Any] stability_diagnostics: dict[str, Any] missing_layers: list[str] + leader_status: NotRequired[str] + provisional_leader: NotRequired[WinningSegment | None] + comparable_leader: NotRequired[WinningSegment | None] + coverage_comparison: NotRequired[dict[str, Any]] candidate_ranking_summary: NotRequired[list[dict[str, Any]]] candidate_summary: NotRequired[dict[str, Any]] @@ -164,6 +170,25 @@ def build_candidate_result_summary(result: dict[str, Any]) -> dict[str, Any]: } +def independent_events(events: Sequence[LifeEvent]) -> tuple[list[LifeEvent], list[str]]: + """Keep the first event of each (domain, date, precision); return the dropped ids. + + The score of an event depends only on those three fields, so a repeated entry is the same test + re-run, not independent support (占星师 2026-11-08 验收清单 §6). + """ + seen: set[tuple[str, str, str]] = set() + kept: list[LifeEvent] = [] + duplicates: list[str] = [] + for event in events: + key = (str(event["domain"]), str(event["date"]).strip(), str(event["precision"])) + if key in seen: + duplicates.append(str(event["id"])) + continue + seen.add(key) + kept.append(event) + return kept, duplicates + + def precision_weight(precision: EventPrecision) -> float: """Return the fixed evidence weight for a declared date precision.""" match precision: @@ -266,6 +291,109 @@ def build_stability_diagnostics( } +COMPARABILITY_POLICY: Final = "common_evidence_coverage_v1" +# Layers whose absence drops the whole event for that candidate (the event is not scored at all). +EVENT_GATING_LAYERS: Final[frozenset[str]] = frozenset({ + "Narayana", "Narayana_MD_AD", "Vimshottari_MD_AD_PD", + "D2", "D3", "D4", "D6", "D7", "D8", "D9", "D10", "D11", "D12", "D24", "D30", "D60", +}) + + +def _coverage_units(row: CandidateScoreRow) -> dict[tuple[str, str], float]: + """(event, layer) -> points for every evidence unit this candidate actually computed. + + Rows that carry ``layer_points`` expose each layer; older rows expose one opaque unit per scored event. + """ + explicit = row.get("layer_points") + if isinstance(explicit, dict): + return { + (str(event_id), str(layer)): float(points) + for event_id, layers in explicit.items() + for layer, points in layers.items() + } + return {(str(item["event_id"]), "event_total"): float(item["points"]) for item in row["evidence"]} + + +def assess_leader_comparability( + rows: Sequence[CandidateScoreRow], + provisional_leader: WinningSegment | None, +) -> dict[str, Any]: + """Explicit comparability policy (占星师 2026-11-08 验收清单 §6 / §9 / §10). + + Raw totals are only comparable when every candidate computed the same evidence units. When coverage + differs, the raw-total leader stays ``provisional_leader`` (and keeps ``winning_segment``), and the + candidates are re-ranked over the units that *every* candidate has; that leader is ``comparable_leader``. + A unit one candidate lacks is dropped for all candidates, so it never counts as 0, negative or an old + algorithm score, and a candidate cannot lead by computing less. When the differing layer is folded into + another unit (no per-layer points), the comparison is ``not_reducible`` and there is no comparable leader. + """ + units = [_coverage_units(row) for row in rows] + row_layers = [set(row["missing_layers"]) for row in rows] + unit_keys = [set(item) for item in units] + equal = all(keys == unit_keys[0] for keys in unit_keys) and all(layers == row_layers[0] for layers in row_layers) + common = set.intersection(*unit_keys) if unit_keys else set() + base: dict[str, Any] = { + "policy": COMPARABILITY_POLICY, + "candidate_count": len(rows), + "common_unit_count": len(common), + "candidate_unit_counts": { + "min": min((len(keys) for keys in unit_keys), default=0), + "max": max((len(keys) for keys in unit_keys), default=0), + }, + } + if equal: + return { + **base, + "status": "comparable", + "comparison": "raw_totals", + "candidates_with_extra_coverage": 0, + "comparable_leader": provisional_leader, + "leader_changed": False, + } + separable = {layer for keys in unit_keys for _, layer in keys} - {"event_total"} + differing = set.union(*row_layers) - set.intersection(*row_layers) + unexplained = sorted(layer for layer in differing if layer not in EVENT_GATING_LAYERS and layer not in separable) + extra = sum(1 for keys in unit_keys if keys != common) + if unexplained: + return { + **base, + "status": "provisional_unequal_coverage", + "comparison": "not_reducible", + "unreducible_layers": unexplained, + "candidates_with_extra_coverage": extra, + "comparable_leader": None, + "leader_changed": None, + } + common_rows: list[CandidateScoreRow] = [ + { + "time": row["time"], + "score": round(sum(points for key, points in unit.items() if key in common), 4), + "evidence": [], + "missing_layers": [], + } + for row, unit in zip(rows, units, strict=True) + ] + common_top = max(row["score"] for row in common_rows) + common_segments = _top_segments(common_rows, common_top) + comparable = _winning_segment(common_segments[0]) if len(common_segments) == 1 else None + return { + **base, + "status": "provisional_unequal_coverage", + "comparison": "common_coverage", + "candidates_with_extra_coverage": extra, + "common_top_score": common_top, + "common_scores": [{"time": row["time"], "score": row["score"]} for row in common_rows], + "comparable_leader": comparable, + "comparable_tied": len(common_segments) != 1, + "leader_changed": ( + comparable is None + or provisional_leader is None + or (comparable["start_time"], comparable["end_time"]) + != (provisional_leader["start_time"], provisional_leader["end_time"]) + ), + } + + def adjudicate_candidate_rows( rows: Sequence[CandidateScoreRow], *, @@ -298,6 +426,10 @@ def adjudicate_candidate_rows( "leave_one_event_out": leave_one_event_out or {"status": "not_evaluated", "runs": []}, }, "missing_layers": [], + "leader_status": "no_leader", + "provisional_leader": None, + "comparable_leader": None, + "coverage_comparison": {"policy": COMPARABILITY_POLICY, "status": "no_candidate_rows"}, } ranked_scores = sorted({row["score"] for row in rows}, reverse=True) @@ -318,6 +450,9 @@ def adjudicate_candidate_rows( reasons.append("missing_mandatory_layers") segment = _winning_segment(segments[0]) if len(segments) == 1 else None + comparability = assess_leader_comparability(rows, segment) + if comparability["status"] != "comparable": + reasons.append("unequal_evidence_coverage") if segment and segment["width_minutes"] > 15: reasons.append("winning_interval_too_wide") if margin < 10: @@ -350,7 +485,9 @@ def adjudicate_candidate_rows( and neighbor_stability["all_required_passed"] and (leave_one_event_out or {}).get("status") == "pass" and not missing_layers + and comparability["status"] == "comparable" and not any(reason in reasons for reason in ( + "unequal_evidence_coverage", "tied_leader", "insufficient_events", "insufficient_domains", @@ -393,6 +530,15 @@ def adjudicate_candidate_rows( "leave_one_event_out": leave_one_event_out or {"status": "not_evaluated", "runs": []}, }, "missing_layers": missing_layers, + # winning_segment stays the raw-total leader; it is only "comparable" when coverage is equal. + "leader_status": ( + "no_single_leader" if segment is None + else "comparable" if comparability["status"] == "comparable" + else "provisional_unequal_coverage" + ), + "provisional_leader": segment, + "comparable_leader": comparability["comparable_leader"], + "coverage_comparison": {key: value for key, value in comparability.items() if key != "comparable_leader"}, "candidate_ranking_summary": ranking_summary, } diff --git a/scripts/chart_choice/astrologer.py b/scripts/chart_choice/astrologer.py index 0f1de4a5f..c918bc54c 100644 --- a/scripts/chart_choice/astrologer.py +++ b/scripts/chart_choice/astrologer.py @@ -357,6 +357,40 @@ def parse_events(raw: Any, birth: datetime) -> list[dict[str, Any]]: return events +def _independent_events(events: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[str]]: + """First event of each (category, date); the ids of the repeats (验收清单 §6).""" + seen: set[tuple[str, str]] = set() + kept, duplicates = [], [] + for event in events: + key = (event["category"], event["date"]) + if key in seen: + duplicates.append(event["id"]) + continue + seen.add(key) + kept.append(event) + return kept, duplicates + + +def leader_coverage(final_ranked: list[dict[str, Any]]) -> dict[str, Any]: + """Whether the candidates' match rates rest on the same Dasha levels (验收清单 §6 / §9 / §10). + + ``score_minute`` divides by each candidate's own available maximum (BUG-1759), so when some + candidates lack a Narayana level that others have, their totals are not directly comparable and the + leader is only provisional. The ranking itself is unchanged (her method). + """ + signatures = { + s["time"]: tuple(sorted((e["id"], level) for e in s["events"] for level in e["chain"].get("unavailable") or ())) + for s in final_ranked + } + distinct = set(signatures.values()) + unequal = len(distinct) > 1 + return { + "status": "provisional_unequal_coverage" if unequal else "comparable", + "candidates_missing_layers": sum(1 for sig in signatures.values() if sig), + "missing_layers": sorted({level for sig in signatures.values() for _, level in sig}), + } + + def _dasha_score(event: dict[str, Any], row: dict[str, Any]) -> tuple[float, dict[str, Any]]: """rectification-engine.js scoreDasha (MD / AD), plus PD and Narayana MD / AD (see module doc).""" cat = EVENT_CATEGORIES[event["category"]] @@ -673,6 +707,10 @@ def evaluate(body: dict[str, Any]) -> dict[str, Any]: rows = scan(req, start, end) base = min(rows, key=lambda r: abs((r["at"] - reported).total_seconds())) events = parse_events(body.get("events"), start) + # 原值:同类别同日期的事件重复录入时各算一件。 + # 新值:只算第一件,其余记入 duplicate_event_ids(同类别同日期的打分输入完全相同,是同一次检验)。 + # 原因:占星师 2026-11-08 验收清单 §6(重复事实不得当独立支持)。 + events, duplicate_event_ids = _independent_events(events) marks = body.get("birthmarks") or [] if not isinstance(marks, list) or any(m not in BIRTHMARK_PARTS for m in marks): raise ChartChoiceInputError("birthmarks must be a list of known body parts") @@ -772,6 +810,7 @@ def evaluate(body: dict[str, Any]) -> dict[str, Any]: "match_rate_same_for_all_candidates": len({s["match_rate"] for s in ranked}) == 1, "ranking": [{k: s[k] for k in ("time", "offset", "total", "match_rate")} for s in final_ranked[:10]], "python_engine": python_engine, + "leader_coverage": leader_coverage(final_ranked), } stages.append({"id": "report", "label": "结果", "status": "done" if result else "waiting", "summary": (_report_summary(result) if result else "事件够了才出结果。")}) @@ -808,6 +847,7 @@ def evaluate(body: dict[str, Any]) -> dict[str, Any]: "coverage": cov, "decision_plan": plan, "result": result, + "duplicate_event_ids": duplicate_event_ids, "technique_contract": contract, "transit": {"status": "blocked", "reason": "上游合同:行运(Gochara)没有独立的反例验证,不参与打分。"}, "caveat": CAVEAT, diff --git a/scripts/chart_choice/astrologer_engine.py b/scripts/chart_choice/astrologer_engine.py index a4761f68a..b547c2585 100644 --- a/scripts/chart_choice/astrologer_engine.py +++ b/scripts/chart_choice/astrologer_engine.py @@ -100,6 +100,7 @@ REASON_CN: Final = { "insufficient_events": "事件少于 3 件", "insufficient_domains": "事件领域少于 2 个", "missing_mandatory_layers": "有必需的层没算出来", + "unequal_evidence_coverage": "各候选分钟算出的层不一样,总分不能直接比", "winning_interval_too_wide": "领先的一段超过 15 分钟", "lead_margin_below_medium_threshold": "领先第二名不到 10%", "neighbor_stability_not_passed": "和前后几分钟拉不开", @@ -195,6 +196,7 @@ def _score_event(event: dict[str, Any], domain: str, row: dict[str, Any], vim: t if isinstance(lon, int | float) and int(lon // 30) in arudha: rules.append(f"{label}_arudha_auxiliary") points += 0.35 + core_points = points kp = ctx["kp"] if kp: for lord, label in ((vim[0], "kp_dba_md"), (vim[1], "kp_dba_ad"), (vim[2], "kp_dba_pd")): @@ -215,8 +217,12 @@ def _score_event(event: dict[str, Any], domain: str, row: dict[str, Any], vim: t if sb_rules: rules.extend(sb_rules) weighted = round(weighted + sb_points * weight, 4) + # Comparability policy (占星师 2026-11-08 验收清单 §6): per-layer points; KP only when its cusps computed. + layers = {"dasha_varga_core": core_points * weight, "Ashtakavarga": av_points * weight, "Shadbala": sb_points * weight} + if kp: + layers[KP_MISSING_LAYER] = (points - core_points) * weight return {"event_id": event["id"], "domain": domain, "candidate_time": row["at"].strftime("%H:%M"), - "rule_ids": rules or ["no_domain_activation"], "points": weighted} + "rule_ids": rules or ["no_domain_activation"], "points": weighted, "_layer_points": layers} def _context(row: dict[str, Any], lat: float, lon: float, ayanamsa: str) -> dict[str, Any]: @@ -254,17 +260,28 @@ def score_rows(events: list[dict[str, Any]], rows: list[dict[str, Any]], *, lat: # K3 (占星师 2026-11-08 第五轮逐项答复): one scoring run never mixes functional tables. functional_benefics.assert_single_functional_profile(profiles, run="chart_choice") evidence = [] + layer_points: dict[str, dict[str, float]] = {} + missing = [] if ctx["kp"] else [KP_MISSING_LAYER] for event in events: domain = CATEGORY_DOMAIN.get(event["category"]) if domain is None: continue vim, nar = active(event, row) - evidence.append(_score_event(event, domain, row, vim, nar, ctx)) + if nar[0] is None or nar[1] is None: + # 原值:来源版 Narayana 定不出时该级按 0 分计入总分,missing_layers 不记。 + # 新值:与 upstream ``_candidate_row`` 相同,该事件不计分并记 Narayana_MD_AD。 + # 原因:占星师 2026-11-08 验收清单 §6(缺层不能变成 0 分)。 + missing.append("Narayana_MD_AD") + continue + item = _score_event(event, domain, row, vim, nar, ctx) + layer_points[item["event_id"]] = item.pop("_layer_points") + evidence.append(item) out.append({ "time": row["at"].strftime("%H:%M"), "score": round(sum(e["points"] for e in evidence), 4), "evidence": evidence, - "missing_layers": [] if ctx["kp"] else [KP_MISSING_LAYER], + "layer_points": layer_points, + "missing_layers": sorted(set(missing)), "kp_cusps": {str(h): ctx["kp"][h] for h in (1, 4, 7, 10)} if ctx["kp"] else None, "functional": {k: ctx["functional_raw"].get(k) for k in ("functional_benefics", "functional_malefics")}, }) @@ -308,6 +325,10 @@ def verdict(events: list[dict[str, Any]], rows: list[dict[str, Any]]) -> dict[st "margin_percent": adjudicated["margin_percent"], "reasons": reasons, "reasons_cn": [REASON_CN.get(r, r) for r in reasons], + # Raw-total leader vs the leader over the evidence every candidate has (验收清单 §6 / §9 / §10). + "leader_status": adjudicated["leader_status"], + "comparable_top_time": (adjudicated["comparable_leader"] or {}).get("representative_time"), + "missing_layers": adjudicated["missing_layers"], "leave_one_event_out": loo.get("status"), "ranking": [{"time": r["time"], "score": r["score"]} for r in sorted(rows, key=lambda r: (-r["score"], r["time"]))[:10]], "top_evidence": adjudicated.get("evidence", []), diff --git a/tests/test_rectification_comparability_bug1801.py b/tests/test_rectification_comparability_bug1801.py new file mode 100644 index 000000000..a675301ac --- /dev/null +++ b/tests/test_rectification_comparability_bug1801.py @@ -0,0 +1,187 @@ +"""BUG-1801: a rectification leader is only comparable when every candidate computed the same evidence. + +占星师 2026-11-08 验收清单 §6 / §9 / §10: ``adjudicate_candidate_rows`` built ``winning_segment`` from raw +totals even when candidates had different evidence coverage, so a candidate could lead by "computing less, +losing fewer points". The raw-total leader is now ``provisional_leader``; ``comparable_leader`` re-ranks over +the evidence units every candidate has. Synthetic, anonymous rows only. +""" +from __future__ import annotations + +from scripts.active_rectification_event_engine import adjudicate_event_candidate_rows +from scripts.active_rectification_events import ( + adjudicate_candidate_rows, + assess_leader_comparability, + independent_events, +) +from scripts.chart_choice import astrologer, astrologer_engine + +DOMAINS = ["career", "relationship", "finance", "career", "relationship"] + + +def _row(time: str, points: dict[str, float], missing: list[str] | None = None) -> dict: + return { + "time": time, + "score": round(sum(points.values()), 4), + "evidence": [ + {"event_id": event_id, "domain": DOMAINS[int(event_id[1:]) - 1], "candidate_time": time, + "rule_ids": ["synthetic"], "points": value} + for event_id, value in points.items() + ], + "missing_layers": missing or [], + } + + +def _adjudicate(rows: list[dict]) -> dict: + return adjudicate_candidate_rows( + rows, event_count=5, domain_count=3, request_fingerprint="synthetic-bug1801", + leave_one_event_out={"status": "pass", "runs": []}, + ) + + +def test_her_reproduction_12_00_is_only_a_provisional_leader() -> None: + """Her case: 12:00 / 12:01, totals 10 / 8, the second lacks the Narayana AD for one event; 5 events, 3 domains.""" + full = _row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2}) + short = _row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_MD_AD"]) + + result = _adjudicate([full, short]) + + assert result["top_score"] == 10 and result["second_score"] == 8 + assert result["winning_segment"]["representative_time"] == "12:00" + assert result["provisional_leader"] == result["winning_segment"] + assert result["leader_status"] == "provisional_unequal_coverage" + assert result["confidence"] == "low" + assert result["can_apply"] is False + assert "missing_mandatory_layers" in result["reasons"] + assert "unequal_evidence_coverage" in result["reasons"] + # Over the four events both candidates have, they tie: the comparable leader is the 2-minute segment, + # not the single minute 12:00. + assert result["comparable_leader"]["width_minutes"] == 2 + assert result["coverage_comparison"]["leader_changed"] is True + comparison = result["coverage_comparison"] + assert comparison["comparison"] == "common_coverage" + assert comparison["common_unit_count"] == 4 + assert {row["time"]: row["score"] for row in comparison["common_scores"]} == {"12:00": 8, "12:01": 8} + + +def test_unequal_coverage_flips_the_leader_once_only_common_layers_are_compared() -> None: + """12:00 never computed the event that penalises it, so it wins raw totals by computing less.""" + computed_less = _row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_MD_AD"]) + computed_all = _row("12:01", {"e1": 3, "e2": 3, "e3": 2, "e4": 2, "e5": -3}) + + result = _adjudicate([computed_less, computed_all]) + + assert result["provisional_leader"]["representative_time"] == "12:00" + assert result["comparable_leader"]["representative_time"] == "12:01" + assert result["coverage_comparison"]["leader_changed"] is True + assert result["can_apply"] is False + # The missing event is dropped for both candidates: it is neither 0 for 12:00 nor kept as -3 for 12:01. + assert {row["time"]: row["score"] for row in result["coverage_comparison"]["common_scores"]} == {"12:00": 8, "12:01": 10} + + +def test_equal_coverage_keeps_the_existing_semantics() -> None: + rows = [_row("12:00", {"e1": 3, "e2": 2, "e3": 2, "e4": 2, "e5": 2}), + _row("12:01", {"e1": 1, "e2": 1, "e3": 1, "e4": 1, "e5": 1})] + + result = _adjudicate(rows) + + assert result["leader_status"] == "comparable" + assert result["comparable_leader"] == result["winning_segment"] == result["provisional_leader"] + assert "unequal_evidence_coverage" not in result["reasons"] + assert result["coverage_comparison"]["comparison"] == "raw_totals" + + +def test_a_folded_auxiliary_layer_cannot_be_reduced_and_gives_no_comparable_leader() -> None: + """Old rows fold Ashtakavarga into each event's points; one candidate lacking it is not reducible.""" + rows = [_row("12:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 2}, ["Ashtakavarga"]), + _row("12:01", {"e1": 2, "e2": 2, "e3": 2, "e4": 2, "e5": 1.8})] + + comparison = assess_leader_comparability(rows, None) + + assert comparison["status"] == "provisional_unequal_coverage" + assert comparison["comparison"] == "not_reducible" + assert comparison["unreducible_layers"] == ["Ashtakavarga"] + assert comparison["comparable_leader"] is None + + +def test_per_layer_points_drop_an_auxiliary_layer_for_every_candidate() -> None: + with_sav = _row("12:00", {"e1": 2.2, "e2": 2.2}) + with_sav["layer_points"] = {"e1": {"dasha_varga_core": 2, "Ashtakavarga": 0.2}, + "e2": {"dasha_varga_core": 2, "Ashtakavarga": 0.2}} + without_sav = _row("12:01", {"e1": 2.1, "e2": 2.0}, ["Ashtakavarga"]) + without_sav["layer_points"] = {"e1": {"dasha_varga_core": 2.1}, "e2": {"dasha_varga_core": 2.0}} + + comparison = assess_leader_comparability([with_sav, without_sav], None) + + assert comparison["comparison"] == "common_coverage" + assert comparison["comparable_leader"]["representative_time"] == "12:01" + assert {row["time"]: row["score"] for row in comparison["common_scores"]} == {"12:00": 4.0, "12:01": 4.1} + + +def test_a_repeated_fact_is_one_test_not_independent_support() -> None: + events = [ + {"id": "a", "domain": "career", "date": "2019-07", "precision": "month"}, + {"id": "b", "domain": "career", "date": "2019-07", "precision": "month", "summary": "same entry"}, + {"id": "c", "domain": "relationship", "date": "2019-07", "precision": "month"}, + ] + kept, duplicates = independent_events(events) + assert [event["id"] for event in kept] == ["a", "c"] and duplicates == ["b"] + + request = {"birth_date": "2000-01-01", "start_time": "12:00", "end_time": "12:01", + "lat": 0.0, "lon": 0.0, "tz": 0.0, "events": events} + rows = [_row("12:00", {"e1": 2, "e3": 1}), _row("12:01", {"e1": 1, "e3": 1})] + for row in rows: + for item, event_id in zip(row["evidence"], ("a", "c"), strict=True): + item["event_id"] = event_id + result = adjudicate_event_candidate_rows(request, rows) + + assert result["event_count"] == 2 + assert result["duplicate_event_ids"] == ["b"] + + +def test_live_stage_dedupes_repeated_entries() -> None: + events = [{"id": "x", "category": "career", "date": "2013-07"}, + {"id": "y", "category": "career", "date": "2013-07"}, + {"id": "z", "category": "marriage", "date": "2013-07"}] + kept, duplicates = astrologer._independent_events(events) + assert [event["id"] for event in kept] == ["x", "z"] and duplicates == ["y"] + + +def test_live_python_engine_records_a_missing_narayana_instead_of_scoring_it_zero(monkeypatch) -> None: + """原值:live 阶段 Python 引擎 Narayana 定不出时该级按 0 分计、missing_layers 不记。 + 新值:该事件不计分、记 Narayana_MD_AD,覆盖不同时领先只是暂列。原因:占星师 2026-11-08 验收清单 §6。""" + body = {"lat": 39.9, "lon": 116.4, "tz": 8, "reported_at": "1990-05-03T08:05", + "start_at": "1990-05-03T08:00", "end_at": "1990-05-03T08:10", + "events": [{"category": "education", "date": "2008"}, {"category": "career", "date": "2013-07"}, + {"category": "marriage", "date": "2016-10-01"}, {"category": "father", "date": "2019"}, + {"category": "travel", "date": "2014"}]} + real = astrologer._active_narayana + + def blocked_at_0805(asc, planets, birth_at, event_at, *tables): + if birth_at.strftime("%H:%M") == "08:05" and event_at.year == 2013: + return None, None + return real(asc, planets, birth_at, event_at, *tables) + + monkeypatch.setattr(astrologer, "_active_narayana", blocked_at_0805) + result = astrologer.evaluate(body)["result"] + + engine = result["python_engine"] + assert "Narayana_MD_AD" in engine["missing_layers"] + assert engine["leader_status"] in {"provisional_unequal_coverage", "no_single_leader"} + assert "unequal_evidence_coverage" in engine["reasons"] + assert result["leader_coverage"]["status"] == "provisional_unequal_coverage" + assert result["leader_coverage"]["missing_layers"] == ["narayana_ad", "narayana_md"] + + +def test_live_python_engine_verdict_carries_the_two_leaders() -> None: + events = [{"id": f"e{i}", "category": category, "date": "2010"} for i, category in + enumerate(["career", "marriage", "finance_pos", "career", "marriage"], 1)] + rows = [{**_row("08:00", {"e1": 2, "e2": 2, "e3": 2, "e4": 2}, ["Narayana_MD_AD"]), "kp_cusps": {"1": {}}}, + {**_row("08:01", {"e1": 3, "e2": 3, "e3": 2, "e4": 2, "e5": -3}), "kp_cusps": {"1": {}}}] + + verdict = astrologer_engine.verdict(events, rows) + + assert verdict["top_time"] == "08:00" + assert verdict["leader_status"] == "provisional_unequal_coverage" + assert verdict["comparable_top_time"] == "08:01" + assert verdict["can_apply"] is False + assert "各候选分钟算出的层不一样,总分不能直接比" in verdict["reasons_cn"]