Skip to content

Commit b719a3d

Browse files
fix(python): align local score rounding with reference
1 parent 455e5b9 commit b719a3d

10 files changed

Lines changed: 4031 additions & 27 deletions

File tree

‎packages/ghfind-py/ghfind/_risk.py‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import math
1111
from typing import Any, Dict, List, Mapping, Optional, Tuple
1212

13+
from ._rounding import round_half_even
14+
1315
RISK_VERSION = "v10"
1416
TOTAL_CAP = 25.0
1517
CONTRIBUTION_CAP = 16.0
@@ -74,9 +76,9 @@ def _coverage(m: Mapping[str, Any]) -> Dict[str, float]:
7476
all_sample = max(0.0, _finite(m.get("recent_pr_sample")))
7577
all_total = max(1.0, min(_finite(m.get("total_pr_count")), 30.0))
7678
return {
77-
"repo": round(_clamp01(fetched / public_repos), 4),
78-
"merged_pr": round(_clamp01(merged_sample / merged_total), 4),
79-
"all_pr": round(_clamp01(all_sample / all_total), 4),
79+
"repo": round_half_even(_clamp01(fetched / public_repos), 4),
80+
"merged_pr": round_half_even(_clamp01(merged_sample / merged_total), 4),
81+
"all_pr": round_half_even(_clamp01(all_sample / all_total), 4),
8082
}
8183

8284

@@ -111,8 +113,8 @@ def _candidate(
111113
"flag": flag,
112114
"family": family,
113115
"disposition": "note",
114-
"severity": round(_clamp01(severity), 4),
115-
"confidence": round(_clamp01(confidence), 4),
116+
"severity": round_half_even(_clamp01(severity), 4),
117+
"confidence": round_half_even(_clamp01(confidence), 4),
116118
"penalty": 0.0,
117119
"detail": detail,
118120
"evidence": _evidence(m, observed, sample, threshold),
@@ -135,15 +137,15 @@ def _apply_cap(candidates: List[Dict[str, Any]], family: str, cap: float) -> flo
135137
raw_total = sum(item["raw"] for item in active)
136138
if raw_total <= 0:
137139
return 0.0
138-
target = round(min(cap, raw_total), 2)
140+
target = round_half_even(min(cap, raw_total), 2)
139141
factor = target / raw_total
140142
assigned = 0.0
141143
for index, item in enumerate(active):
142-
penalty = round(max(0.0, target - assigned), 2) if index == len(active) - 1 else round(item["raw"] * factor, 2)
144+
penalty = round_half_even(max(0.0, target - assigned), 2) if index == len(active) - 1 else round_half_even(item["raw"] * factor, 2)
143145
item["signal"]["penalty"] = penalty
144146
if penalty > 0:
145147
item["signal"]["disposition"] = "penalty"
146-
assigned = round(assigned + penalty, 2)
148+
assigned = round_half_even(assigned + penalty, 2)
147149
return assigned
148150

149151

@@ -195,7 +197,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
195197
trivial_raw = 8 * _clamp01((trivial_rate - TRIVIAL_RATE) / TRIVIAL_TRANSITION) * _sample_factor(merged_sample) if merged_sample >= MIN_CONTRIBUTION_SAMPLE and trivial_rate > TRIVIAL_RATE else 0.0
196198
if merged_sample > 0 and external_trivial > 0 and external_trivial / merged_sample > 0.3:
197199
detail = "外部热门仓库中的低实质 PR 比例偏高,但合并样本不足 20 个,仅作风险提示。" if merged_sample < MIN_CONTRIBUTION_SAMPLE else "外部热门仓库中的低实质 PR 比例达到量化阈值;仅统计他人仓库,不惩罚正常自提 PR。"
198-
_add_contribution(m, candidates, "trivial_pr_farming", trivial_raw, trivial_severity, detail, {"external_trivial_pr_count": external_trivial, "merged_pr_sample": merged_sample, "smoothed_rate": round(trivial_rate, 4)}, merged_sample, {"minimum_sample": MIN_CONTRIBUTION_SAMPLE, "smoothed_rate": TRIVIAL_RATE}, coverage_confidence)
200+
_add_contribution(m, candidates, "trivial_pr_farming", trivial_raw, trivial_severity, detail, {"external_trivial_pr_count": external_trivial, "merged_pr_sample": merged_sample, "smoothed_rate": round_half_even(trivial_rate, 4)}, merged_sample, {"minimum_sample": MIN_CONTRIBUTION_SAMPLE, "smoothed_rate": TRIVIAL_RATE}, coverage_confidence)
199201

200202
rejection_measured = m.get("maintainer_closed_unmerged_pr_count") is not None
201203
rejected = max(0.0, _finite(m.get("maintainer_closed_unmerged_pr_count"))) if rejection_measured else 0.0
@@ -206,7 +208,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
206208
rejection_raw = 4 * _clamp01((rejection_lower - REJECTION_WILSON_LOWER) / REJECTION_WILSON_LOWER) if rejection_measured and decided >= MIN_REJECTION_DECISIONS and rejection_lower >= REJECTION_WILSON_LOWER else 0.0
207209
if rejection_measured and decided > 0 and rejection_rate >= REJECTION_WILSON_LOWER:
208210
detail = "维护者关闭未合并的 PR 比例偏高,但样本量或 Wilson 95% 下界未达到扣分门槛,仅作风险提示。" if decided < MIN_REJECTION_DECISIONS or rejection_lower < REJECTION_WILSON_LOWER else "维护者关闭未合并的 PR 的 Wilson 95% 下界达到量化阈值。"
209-
_add_contribution(m, candidates, "high_pr_rejection", rejection_raw, rejection_severity, detail, {"maintainer_closed_unmerged_pr_count": rejected, "merged_pr_count": _finite(m.get("merged_pr_count")), "decided_pr_count": decided, "wilson_lower": round(rejection_lower, 4)}, decided, {"minimum_decisions": MIN_REJECTION_DECISIONS, "wilson_lower": REJECTION_WILSON_LOWER}, coverage_confidence)
211+
_add_contribution(m, candidates, "high_pr_rejection", rejection_raw, rejection_severity, detail, {"maintainer_closed_unmerged_pr_count": rejected, "merged_pr_count": _finite(m.get("merged_pr_count")), "decided_pr_count": decided, "wilson_lower": round_half_even(rejection_lower, 4)}, decided, {"minimum_decisions": MIN_REJECTION_DECISIONS, "wilson_lower": REJECTION_WILSON_LOWER}, coverage_confidence)
210212

211213
flood_sample = max(0.0, _finite(m.get("recent_pr_sample")))
212214
share = _clamp01(_finite(m.get("top_repo_pr_share")))
@@ -230,7 +232,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
230232
follow_raw = 4 * _clamp01((FOLLOW_RATIO - follower_ratio) / FOLLOW_RATIO) * _clamp01((following - FOLLOW_MINIMUM) / 3000) if following >= FOLLOW_MINIMUM and follower_ratio < FOLLOW_RATIO else 0.0
231233
follow: Optional[Dict[str, Any]] = None
232234
if follow_observed:
233-
follow = _candidate(m, "follow_farming", "social", 0.0, _clamp01((FOLLOW_RATIO - follower_ratio) / FOLLOW_RATIO), coverage_confidence, "关注数量与粉丝数量明显失衡;当前只有单次快照,没有关注增长时间序列,不能单独判定刷粉。", {"following": following, "followers": followers, "follower_ratio": round(follower_ratio, 4)}, threshold={"minimum_following": FOLLOW_MINIMUM, "follower_ratio": FOLLOW_RATIO})
235+
follow = _candidate(m, "follow_farming", "social", 0.0, _clamp01((FOLLOW_RATIO - follower_ratio) / FOLLOW_RATIO), coverage_confidence, "关注数量与粉丝数量明显失衡;当前只有单次快照,没有关注增长时间序列,不能单独判定刷粉。", {"following": following, "followers": followers, "follower_ratio": round_half_even(follower_ratio, 4)}, threshold={"minimum_following": FOLLOW_MINIMUM, "follower_ratio": FOLLOW_RATIO})
234236
candidates.append(follow)
235237

236238
engagement = m.get("top_repo_engagement_ratio")
@@ -252,7 +254,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
252254

253255
contribution_penalty = _apply_cap(candidates, "contribution", CONTRIBUTION_CAP)
254256
social_penalty = _apply_cap(candidates, "social", SOCIAL_CAP)
255-
total_penalty = round(min(TOTAL_CAP, contribution_penalty + social_penalty), 2)
257+
total_penalty = round_half_even(min(TOTAL_CAP, contribution_penalty + social_penalty), 2)
256258
signals = [item["signal"] for item in candidates]
257259
notes = []
258260
red_flags = []
@@ -264,13 +266,13 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
264266
note["penalty"] = 0.0
265267
note["disposition"] = "note"
266268
notes.append(note)
267-
risk_score = round(total_penalty / TOTAL_CAP * 100, 2)
269+
risk_score = round_half_even(total_penalty / TOTAL_CAP * 100, 2)
268270
level = "high" if risk_score >= HIGH_MINIMUM else "review" if risk_score >= REVIEW_MINIMUM else "none"
269271
assessment = {
270272
"version": RISK_VERSION,
271273
"risk_score": risk_score,
272274
"level": level,
273-
"confidence": round(_confidence(coverage) * 100, 2),
275+
"confidence": round_half_even(_confidence(coverage) * 100, 2),
274276
"applied_penalty": total_penalty,
275277
"signals": signals,
276278
"coverage": coverage,
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""Rounding used by the TypeScript and Go scoring implementations."""
2+
3+
import math
4+
5+
6+
def round_half_even(value: float, digits: int = 0) -> float:
7+
"""Match the reference's scaled half-even rule, including its tolerance."""
8+
factor = 10.0 ** digits
9+
scaled = value * factor
10+
# Python's round(value, digits) preserves large finite values and passes
11+
# through NaN/Infinity even when scaling cannot remain finite.
12+
if not math.isfinite(scaled):
13+
return value
14+
lower = math.floor(scaled)
15+
if abs(scaled - lower - 0.5) < 1e-9:
16+
rounded = lower if lower % 2 == 0 else lower + 1
17+
else:
18+
# Compare the fraction instead of adding 0.5: that addition can
19+
# round an already-integral binary64 value at or above 2**52.
20+
rounded = lower + (1 if scaled - lower >= 0.5 else 0)
21+
# Math.round retains negative zero; the half-even branch above can
22+
# instead produce positive zero, including for an exact negative half.
23+
if rounded == 0 and math.copysign(1.0, scaled) < 0:
24+
return -0.0
25+
return rounded / factor

‎packages/ghfind-py/ghfind/_score.py‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44
The number is the single source of truth; the LLM only writes prose/roast on top
55
of this output.
66
7-
Parity notes (why this reproduces the TS output bit-for-bit):
8-
- TS reimplemented Python's ``round()`` (round-half-to-even / banker's) as its own
9-
``round()``. Python's built-in ``round()`` IS banker's, so we use it directly for
10-
every TS ``round(...)`` call.
7+
Parity notes for TypeScript rounding:
8+
- TS and Go scale values before applying half-even with a tolerance around the
9+
midpoint; ``round_half_even`` mirrors that rule for the scoring calculations.
1110
- TS ``Math.round(...)`` is round-half-UP, NOT banker's. We replicate it with
1211
``_math_round`` = ``floor(x + 0.5)`` wherever the TS uses ``Math.round``.
1312
- ``??`` (nullish) defaults only on null/undefined; ``_nz`` mirrors that (defaults
@@ -22,6 +21,7 @@
2221
from typing import Any, Dict, List, Mapping, Optional
2322

2423
from ._risk import assess_risk
24+
from ._rounding import round_half_even
2525

2626
SUBSCORE_MAX: Dict[str, float] = {
2727
"account_maturity": 10,
@@ -52,7 +52,7 @@ def log_ratio(value: float, full_at: float) -> float:
5252

5353
def clamp_score(value: float) -> float:
5454
"""Clamp a score to [0, 100] and round to 2 decimals (banker's)."""
55-
return round(max(0, min(value, 100)), 2)
55+
return round_half_even(max(0, min(value, 100)), 2)
5656

5757

5858
def star_engagement_multiplier(ratio: Any) -> float:
@@ -393,7 +393,7 @@ def original_project_quality(m):
393393
* content_skill_discount(m)
394394
)
395395
project_substance = max(0, min(_nz(m.get("best_original_repo_quality_score"), 0), 1)) * 6
396-
return round(star_pts + project_substance, 1)
396+
return round_half_even(star_pts + project_substance, 1)
397397

398398

399399
def score(m: Mapping[str, Any]) -> Dict[str, Any]:
@@ -410,7 +410,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
410410
age_pts = min(m["account_age_years"] / 6.0, 1.0) * 7
411411
years = m["contribution_years_active"]
412412
span_pts = 0 if years == 0 else 1 if years == 1 else 2 if years == 2 else 3
413-
sub["account_maturity"] = round(age_pts + span_pts, 1)
413+
sub["account_maturity"] = round_half_even(age_pts + span_pts, 1)
414414

415415
# 2. Original Project Quality (18)
416416
sub["original_project_quality"] = max(original_project_quality(m), max(0,min(18,m.get("personal_original_project_quality_score",0))))
@@ -444,7 +444,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
444444
+ high_impact_core_pr_bonus(m) * (1-(1-presentation_discount(m))*.8)
445445
- author_self_closed_external_penalty(m)
446446
)
447-
sub["contribution_quality"] = round(
447+
sub["contribution_quality"] = round_half_even(
448448
saturate_toward(max(0, contribution_quality_raw), contribution_evidence_ceiling(m)),
449449
1,
450450
)
@@ -457,7 +457,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
457457
from ._presentation import ecosystem_presentation_discount
458458
external_share = min(1,max(0,_nz(m.get("external_merged_pr_count"),0))/max(1,m["merged_pr_count"]))
459459
ecosystem_raw = (prestige + depth) * ecosystem_presentation_discount(m) * (1-(1-content_skill_discount(m))*(1-external_share))
460-
sub["ecosystem_impact"] = round(
460+
sub["ecosystem_impact"] = round_half_even(
461461
ecosystem_raw,
462462
1,
463463
)
@@ -474,7 +474,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
474474
ratio = followers / following
475475
ratio_pts = 3 if ratio >= 2 else 2 if ratio >= 1 else 1.5 if ratio >= 0.5 else 1
476476
community_raw = follower_pts + ratio_pts
477-
sub["community_influence"] = round(
477+
sub["community_influence"] = round_half_even(
478478
min(community_raw, 2.5) if _has_social_only_dormant_signal(m) else community_raw, 1
479479
)
480480

@@ -490,12 +490,12 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
490490
else:
491491
recency_pts = 0.0
492492
diversity_pts = min(m["activity_type_count"], 4) * 1.125
493-
sub["activity_authenticity"] = round(contrib_pts + recency_pts + diversity_pts, 1)
493+
sub["activity_authenticity"] = round_half_even(contrib_pts + recency_pts + diversity_pts, 1)
494494

495-
base = round(sum(sub.values()), 1)
495+
base = round_half_even(sum(sub.values()), 1)
496496

497497
risk_assessment, risk_notes, flags, penalty = assess_risk(m)
498-
final = clamp_score(round(base - penalty, 2))
498+
final = clamp_score(round_half_even(base - penalty, 2))
499499
t = tier_for(final)
500500

501501
return {

0 commit comments

Comments
 (0)