Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions packages/ghfind-py/ghfind/_risk.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import math
from typing import Any, Dict, List, Mapping, Optional, Tuple

from ._rounding import round_half_even

RISK_VERSION = "v10"
TOTAL_CAP = 25.0
CONTRIBUTION_CAP = 16.0
Expand Down Expand Up @@ -74,9 +76,9 @@ def _coverage(m: Mapping[str, Any]) -> Dict[str, float]:
all_sample = max(0.0, _finite(m.get("recent_pr_sample")))
all_total = max(1.0, min(_finite(m.get("total_pr_count")), 30.0))
return {
"repo": round(_clamp01(fetched / public_repos), 4),
"merged_pr": round(_clamp01(merged_sample / merged_total), 4),
"all_pr": round(_clamp01(all_sample / all_total), 4),
"repo": round_half_even(_clamp01(fetched / public_repos), 4),
"merged_pr": round_half_even(_clamp01(merged_sample / merged_total), 4),
"all_pr": round_half_even(_clamp01(all_sample / all_total), 4),
}


Expand Down Expand Up @@ -111,8 +113,8 @@ def _candidate(
"flag": flag,
"family": family,
"disposition": "note",
"severity": round(_clamp01(severity), 4),
"confidence": round(_clamp01(confidence), 4),
"severity": round_half_even(_clamp01(severity), 4),
"confidence": round_half_even(_clamp01(confidence), 4),
"penalty": 0.0,
"detail": detail,
"evidence": _evidence(m, observed, sample, threshold),
Expand All @@ -135,15 +137,15 @@ def _apply_cap(candidates: List[Dict[str, Any]], family: str, cap: float) -> flo
raw_total = sum(item["raw"] for item in active)
if raw_total <= 0:
return 0.0
target = round(min(cap, raw_total), 2)
target = round_half_even(min(cap, raw_total), 2)
factor = target / raw_total
assigned = 0.0
for index, item in enumerate(active):
penalty = round(max(0.0, target - assigned), 2) if index == len(active) - 1 else round(item["raw"] * factor, 2)
penalty = round_half_even(max(0.0, target - assigned), 2) if index == len(active) - 1 else round_half_even(item["raw"] * factor, 2)
item["signal"]["penalty"] = penalty
if penalty > 0:
item["signal"]["disposition"] = "penalty"
assigned = round(assigned + penalty, 2)
assigned = round_half_even(assigned + penalty, 2)
return assigned


Expand Down Expand Up @@ -195,7 +197,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
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
if merged_sample > 0 and external_trivial > 0 and external_trivial / merged_sample > 0.3:
detail = "外部热门仓库中的低实质 PR 比例偏高,但合并样本不足 20 个,仅作风险提示。" if merged_sample < MIN_CONTRIBUTION_SAMPLE else "外部热门仓库中的低实质 PR 比例达到量化阈值;仅统计他人仓库,不惩罚正常自提 PR。"
_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)
_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)

rejection_measured = m.get("maintainer_closed_unmerged_pr_count") is not None
rejected = max(0.0, _finite(m.get("maintainer_closed_unmerged_pr_count"))) if rejection_measured else 0.0
Expand All @@ -206,7 +208,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
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
if rejection_measured and decided > 0 and rejection_rate >= REJECTION_WILSON_LOWER:
detail = "维护者关闭未合并的 PR 比例偏高,但样本量或 Wilson 95% 下界未达到扣分门槛,仅作风险提示。" if decided < MIN_REJECTION_DECISIONS or rejection_lower < REJECTION_WILSON_LOWER else "维护者关闭未合并的 PR 的 Wilson 95% 下界达到量化阈值。"
_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)
_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)

flood_sample = max(0.0, _finite(m.get("recent_pr_sample")))
share = _clamp01(_finite(m.get("top_repo_pr_share")))
Expand All @@ -230,7 +232,7 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
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
follow: Optional[Dict[str, Any]] = None
if follow_observed:
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})
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})
candidates.append(follow)

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

contribution_penalty = _apply_cap(candidates, "contribution", CONTRIBUTION_CAP)
social_penalty = _apply_cap(candidates, "social", SOCIAL_CAP)
total_penalty = round(min(TOTAL_CAP, contribution_penalty + social_penalty), 2)
total_penalty = round_half_even(min(TOTAL_CAP, contribution_penalty + social_penalty), 2)
signals = [item["signal"] for item in candidates]
notes = []
red_flags = []
Expand All @@ -264,13 +266,13 @@ def assess_risk(m: Mapping[str, Any]) -> Tuple[Dict[str, Any], List[Dict[str, An
note["penalty"] = 0.0
note["disposition"] = "note"
notes.append(note)
risk_score = round(total_penalty / TOTAL_CAP * 100, 2)
risk_score = round_half_even(total_penalty / TOTAL_CAP * 100, 2)
level = "high" if risk_score >= HIGH_MINIMUM else "review" if risk_score >= REVIEW_MINIMUM else "none"
assessment = {
"version": RISK_VERSION,
"risk_score": risk_score,
"level": level,
"confidence": round(_confidence(coverage) * 100, 2),
"confidence": round_half_even(_confidence(coverage) * 100, 2),
"applied_penalty": total_penalty,
"signals": signals,
"coverage": coverage,
Expand Down
25 changes: 25 additions & 0 deletions packages/ghfind-py/ghfind/_rounding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Rounding used by the TypeScript and Go scoring implementations."""

import math


def round_half_even(value: float, digits: int = 0) -> float:
"""Match the reference's scaled half-even rule, including its tolerance."""
factor = 10.0 ** digits
scaled = value * factor
# Python's round(value, digits) preserves large finite values and passes
# through NaN/Infinity even when scaling cannot remain finite.
if not math.isfinite(scaled):
return value
lower = math.floor(scaled)
if abs(scaled - lower - 0.5) < 1e-9:
rounded = lower if lower % 2 == 0 else lower + 1
else:
# Compare the fraction instead of adding 0.5: that addition can
# round an already-integral binary64 value at or above 2**52.
rounded = lower + (1 if scaled - lower >= 0.5 else 0)
# Math.round retains negative zero; the half-even branch above can
# instead produce positive zero, including for an exact negative half.
if rounded == 0 and math.copysign(1.0, scaled) < 0:
return -0.0
return rounded / factor
26 changes: 13 additions & 13 deletions packages/ghfind-py/ghfind/_score.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
The number is the single source of truth; the LLM only writes prose/roast on top
of this output.

Parity notes (why this reproduces the TS output bit-for-bit):
- TS reimplemented Python's ``round()`` (round-half-to-even / banker's) as its own
``round()``. Python's built-in ``round()`` IS banker's, so we use it directly for
every TS ``round(...)`` call.
Parity notes for TypeScript rounding:
- TS and Go scale values before applying half-even with a tolerance around the
midpoint; ``round_half_even`` mirrors that rule for the scoring calculations.
- TS ``Math.round(...)`` is round-half-UP, NOT banker's. We replicate it with
``_math_round`` = ``floor(x + 0.5)`` wherever the TS uses ``Math.round``.
- ``??`` (nullish) defaults only on null/undefined; ``_nz`` mirrors that (defaults
Expand All @@ -22,6 +21,7 @@
from typing import Any, Dict, List, Mapping, Optional

from ._risk import assess_risk
from ._rounding import round_half_even

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

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


def star_engagement_multiplier(ratio: Any) -> float:
Expand Down Expand Up @@ -393,7 +393,7 @@ def original_project_quality(m):
* content_skill_discount(m)
)
project_substance = max(0, min(_nz(m.get("best_original_repo_quality_score"), 0), 1)) * 6
return round(star_pts + project_substance, 1)
return round_half_even(star_pts + project_substance, 1)


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

# 2. Original Project Quality (18)
sub["original_project_quality"] = max(original_project_quality(m), max(0,min(18,m.get("personal_original_project_quality_score",0))))
Expand Down Expand Up @@ -444,7 +444,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
+ high_impact_core_pr_bonus(m) * (1-(1-presentation_discount(m))*.8)
- author_self_closed_external_penalty(m)
)
sub["contribution_quality"] = round(
sub["contribution_quality"] = round_half_even(
saturate_toward(max(0, contribution_quality_raw), contribution_evidence_ceiling(m)),
1,
)
Expand All @@ -457,7 +457,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
from ._presentation import ecosystem_presentation_discount
external_share = min(1,max(0,_nz(m.get("external_merged_pr_count"),0))/max(1,m["merged_pr_count"]))
ecosystem_raw = (prestige + depth) * ecosystem_presentation_discount(m) * (1-(1-content_skill_discount(m))*(1-external_share))
sub["ecosystem_impact"] = round(
sub["ecosystem_impact"] = round_half_even(
ecosystem_raw,
1,
)
Expand All @@ -474,7 +474,7 @@ def score(m: Mapping[str, Any]) -> Dict[str, Any]:
ratio = followers / following
ratio_pts = 3 if ratio >= 2 else 2 if ratio >= 1 else 1.5 if ratio >= 0.5 else 1
community_raw = follower_pts + ratio_pts
sub["community_influence"] = round(
sub["community_influence"] = round_half_even(
min(community_raw, 2.5) if _has_social_only_dormant_signal(m) else community_raw, 1
)

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

base = round(sum(sub.values()), 1)
base = round_half_even(sum(sub.values()), 1)

risk_assessment, risk_notes, flags, penalty = assess_risk(m)
final = clamp_score(round(base - penalty, 2))
final = clamp_score(round_half_even(base - penalty, 2))
t = tier_for(final)

return {
Expand Down
Loading
Loading