You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@community.apache.org by rb...@apache.org on 2026/09/09 16:04:32 UTC
(comdev-metrics) 13/15: Various tweaks:
This is an automated email from the ASF dual-hosted git repository.
rbowen pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/comdev-metrics.git
commit 0d1a9b55318a6667d7948afef0af4990949c1db4
Author: Rich Bowen <rb...@rcbowen.com>
AuthorDate: Mon Jul 13 11:45:56 2026 -0400
Various tweaks:
Links to mailing lists
Health status (declining, at risk, dormant)
Phrasing/legend updates for clarity
---
site/index.html | 74 +++++++++++++++------------
site/project.html | 80 +++++++++++++++++++++++++++++-
src/asfmetrics/collectors/git_activity.py | 79 ++++++++++++++++++++++-------
src/asfmetrics/collectors/mailing_lists.py | 33 ++++++------
src/asfmetrics/health.py | 9 ++--
5 files changed, 205 insertions(+), 70 deletions(-)
diff --git a/site/index.html b/site/index.html
index 3fce65a..8295b64 100644
--- a/site/index.html
+++ b/site/index.html
@@ -167,37 +167,37 @@
<p id="health-window" style="color:#666;font-size:0.9rem;margin-bottom:0.5rem"></p>
<p style="color:#666;font-size:0.85rem;margin-bottom:1.5rem" id="health-methodology"></p>
- <h3 style="color:#c0392b">🔴 Declining <span id="declining-count" style="font-weight:normal;color:#666"></span></h3>
- <p style="color:#666;font-size:0.85rem;margin-bottom:0.5rem">Both mailing list discussion and git commits trending sharply downward.</p>
- <table id="declining-table">
- <thead><tr><th>Project</th><th>Mailing List</th><th>Git Commits</th><th></th></tr></thead>
+ <h3 style="color:#555">⚫ Dormant <span id="dormant-count" style="font-weight:normal;color:#666"></span></h3>
+ <p style="color:#666;font-size:0.85rem;margin-bottom:0.5rem">Near-zero activity across all metrics.</p>
+ <table id="dormant-table">
+ <thead><tr><th>Project</th><th id="dormant-ml-header">Mailing List Msgs</th><th id="dormant-git-header">Git Commits</th></tr></thead>
<tbody></tbody>
</table>
- <h3 style="color:#e67e22;margin-top:2rem">🟡 At Risk <span id="at-risk-count" style="font-weight:normal;color:#666"></span></h3>
- <p style="color:#666;font-size:0.85rem;margin-bottom:0.5rem">One or both metrics declining significantly, with meaningful prior activity.</p>
+ <h3 style="color:#c0392b;margin-top:2rem">🔴 At Risk <span id="at-risk-count" style="font-weight:normal;color:#666"></span></h3>
+ <p style="color:#666;font-size:0.85rem;margin-bottom:0.5rem">Both mailing list discussion and git commits trending sharply downward. Immediate attention needed.</p>
<table id="at-risk-table">
- <thead><tr><th>Project</th><th>Mailing List</th><th>Git Commits</th><th></th></tr></thead>
+ <thead><tr><th>Project</th><th class="health-ml-header">Mailing List (Q1 vs Q2)</th><th class="health-git-header">Git Commits (Q1 vs Q2)</th></tr></thead>
<tbody></tbody>
</table>
- <h3 style="color:#555;margin-top:2rem">⚫ Dormant <span id="dormant-count" style="font-weight:normal;color:#666"></span></h3>
- <p style="color:#666;font-size:0.85rem;margin-bottom:0.5rem">Near-zero activity across all metrics. Candidates for Attic retirement.</p>
- <table id="dormant-table">
- <thead><tr><th>Project</th><th>Mailing List (3 mo)</th><th>Git Commits (12 mo)</th></tr></thead>
+ <h3 style="color:#e67e22;margin-top:2rem">🟡 Declining <span id="declining-count" style="font-weight:normal;color:#666"></span></h3>
+ <p style="color:#666;font-size:0.85rem;margin-bottom:0.5rem">One or both metrics declining significantly, with meaningful prior activity.</p>
+ <table id="declining-table">
+ <thead><tr><th>Project</th><th class="health-ml-header">Mailing List (Q1 vs Q2)</th><th class="health-git-header">Git Commits (Q1 vs Q2)</th></tr></thead>
<tbody></tbody>
</table>
<div style="margin-top:2rem;padding:1rem;background:#f8f9fa;border-radius:6px;font-size:0.85rem;color:#555">
<strong>Methodology:</strong> <span id="health-method-detail"></span><br>
- <strong>Thresholds:</strong> Declining = both axes ≤ <span id="threshold-decline"></span>%.
- At Risk = one axis ≤ <span id="threshold-decline2"></span>% (min <span id="threshold-prior"></span> prior activity).
+ <strong>Thresholds:</strong> At Risk = both axes ≤ <span id="threshold-decline"></span>%.
+ Declining = one axis ≤ <span id="threshold-decline2"></span>% (min <span id="threshold-prior"></span> prior activity).
Dormant = ≤ <span id="threshold-dormant-commits"></span> commits + ≤ <span id="threshold-dormant-msgs"></span> messages in recent quarter.
</div>
</div>
</div>
- <p id="generated-date" style="color:#999;font-size:0.8rem;text-align:right;ma
+ <p id="generated-date" style="color:#999;font-size:0.8rem;text-align:right;margin-top:0.5rem"></p>
</div><!-- #app -->
@@ -214,11 +214,10 @@
async function loadData() {
try {
- const [committeesResp, releasesResp, newCommResp, healthResp] = await Promise.all([
+ const [committeesResp, releasesResp, newCommResp] = await Promise.all([
fetch('data/_cache/committees.json'),
fetch('data/_cache/releases.json'),
fetch('data/_cache/new_committers.json'),
- fetch('data/_cache/project_health.json'),
]);
if (!committeesResp.ok) {
@@ -230,7 +229,6 @@
const committees = await committeesResp.json();
const releases = releasesResp.ok ? await releasesResp.json() : {};
const newCommData = newCommResp && newCommResp.ok ? await newCommResp.json() : {by_project: {}, total: 0};
- const healthData = healthResp && healthResp.ok ? await healthResp.json() : null;
document.getElementById('loading').style.display = 'none';
document.getElementById('app').style.display = 'block';
@@ -409,8 +407,24 @@
}
// --- Project Health tab ---
+ let healthData = null;
+ try {
+ const healthResp = await fetch('data/_cache/project_health.json');
+ if (healthResp.ok) {
+ healthData = await healthResp.json();
+ }
+ } catch (healthErr) { console.warn('project_health.json not available:', healthErr); }
+
if (healthData) {
const win = healthData.window;
+ // Update table headers with actual quarter labels
+ const qLabel = `(${win.prior_label} → ${win.recent_label})`;
+ document.querySelectorAll('.health-ml-header').forEach(el => { el.textContent = `Mailing List ${qLabel}`; });
+ document.querySelectorAll('.health-git-header').forEach(el => { el.textContent = `Git Commits ${qLabel}`; });
+
+ document.getElementById('dormant-ml-header').textContent = `Mailing List Msgs (${win.recent_label})`;
+ document.getElementById('dormant-git-header').textContent = `Git Commits (${win.recent_label})`;
+
document.getElementById('health-title').textContent =
`Project Health — ${win.recent_label} vs ${win.prior_label}`;
document.getElementById('health-window').textContent = win.description;
@@ -428,8 +442,10 @@
`Quarter-over-quarter comparison: ${win.recent_label} (recent) vs ${win.prior_label} (prior). ` +
`Current partial month excluded. Only projects with data files are assessed.`;
- document.getElementById('declining-count').textContent = `(${healthData.declining.length})`;
- document.getElementById('at-risk-count').textContent = `(${healthData.at_risk.length})`;
+ // In JSON: "declining" = both axes down (severe), "at_risk" = one axis down (moderate)
+ // On page: "At Risk" (red) = severe, "Declining" (orange) = moderate
+ document.getElementById('at-risk-count').textContent = `(${healthData.declining.length})`;
+ document.getElementById('declining-count').textContent = `(${healthData.at_risk.length})`;
document.getElementById('dormant-count').textContent = `(${healthData.dormant.length})`;
function trendCell(pct, prior, recent, label) {
@@ -439,33 +455,25 @@
`<span style="color:#888;font-size:0.85rem">(${prior}→${recent} ${label})</span>`;
}
- function fillHealthTable(tableId, entries, showBar) {
+ function fillHealthTable(tableId, entries) {
const tbody = document.querySelector(`#${tableId} tbody`);
entries.forEach(e => {
const row = document.createElement('tr');
const mlCell = trendCell(e.ml_trend_pct, e.ml_prior, e.ml_recent, 'msgs');
const gitCell = trendCell(e.git_trend_pct, e.git_prior, e.git_recent, 'commits');
- let barHtml = '';
- if (showBar) {
- const mlW = e.ml_trend_pct !== null ? Math.min(100, Math.abs(e.ml_trend_pct)) : 0;
- const gitW = e.git_trend_pct !== null ? Math.min(100, Math.abs(e.git_trend_pct)) : 0;
- barHtml = `<td style="width:20%"><div class="bar" style="display:flex">` +
- `<div style="background:#e74c3c;height:100%;width:${mlW}%;border-radius:3px 0 0 3px" title="ML: ${e.ml_trend_pct || 0}%"></div>` +
- `<div style="background:#f39c12;height:100%;width:${gitW}%" title="Git: ${e.git_trend_pct || 0}%"></div>` +
- `</div></td>`;
- }
row.innerHTML = `
<td><a href="project.html?id=${e.project}">${projectNames[e.project] || e.project}</a></td>
<td>${mlCell}</td>
<td>${gitCell}</td>
- ${barHtml}
`;
tbody.appendChild(row);
});
}
- fillHealthTable('declining-table', healthData.declining, true);
- fillHealthTable('at-risk-table', healthData.at_risk, true);
+ // "declining" in JSON = both axes down = "At Risk" on the page (red, severe)
+ // "at_risk" in JSON = one axis down = "Declining" on the page (orange, warning)
+ fillHealthTable('at-risk-table', healthData.declining);
+ fillHealthTable('declining-table', healthData.at_risk);
// Dormant table is simpler
const dormantTbody = document.querySelector('#dormant-table tbody');
@@ -474,7 +482,7 @@
row.innerHTML = `
<td><a href="project.html?id=${e.project}">${projectNames[e.project] || e.project}</a></td>
<td>${e.ml_recent}</td>
- <td>${e.git_total_12mo}</td>
+ <td>${e.git_recent}</td>
`;
dormantTbody.appendChild(row);
});
diff --git a/site/project.html b/site/project.html
index 293608b..a0442fb 100644
--- a/site/project.html
+++ b/site/project.html
@@ -108,6 +108,9 @@
</div>
</div>
+ <div id="health-badge" style="display:none;margin-bottom:1.5rem;padding:0.8rem 1.2rem;border-radius:8px;font-size:0.95rem">
+ </div>
+
<div class="section">
<h2>Mailing List Activity (12 Months)</h2>
<table id="lists-table">
@@ -157,6 +160,15 @@
<p id="project-links"></p>
</div>
+ <div class="section" id="growth-section" style="display:none">
+ <h2>Community Growth (Last 12 Months)</h2>
+ <table id="growth-table">
+ <thead><tr><th>Name</th><th>Date Added</th><th>Type</th></tr></thead>
+ <tbody></tbody>
+ </table>
+ <p id="growth-none" style="display:none;color:#666;font-style:italic">No new committers or PMC members added in the last 12 months.</p>
+ </div>
+
</div><!-- #app -->
<script>
@@ -227,7 +239,7 @@
const row = document.createElement('tr');
row.innerHTML = `
- <td>${list.list_name}@${ml.domain}</td>
+ <td>${list.list_name}@${ml.domain} <a href="https://lists.apache.org/list.html?${list.list_name}@${ml.domain}" target="_blank" title="View archive on lists.apache.org" style="margin-left:0.4rem">✉️</a></td>
<td>${quarterTotal}</td>
<td><div class="sparkline">${sparkHtml}</div></td>
`;
@@ -367,6 +379,72 @@
}
}
+ // --- Health status badge ---
+ try {
+ const healthResp = await fetch('data/_cache/project_health.json');
+ if (healthResp.ok) {
+ const health = await healthResp.json();
+ const badge = document.getElementById('health-badge');
+ const win = health.window;
+
+ const inDeclining = health.declining.find(e => e.project === id);
+ const inAtRisk = health.at_risk.find(e => e.project === id);
+ const inDormant = health.dormant.find(e => e.project === id);
+
+ if (inDormant) {
+ badge.style.display = 'block';
+ badge.style.background = '#f0f0f0';
+ badge.style.borderLeft = '4px solid #555';
+ badge.innerHTML = `<strong>⚫ Dormant</strong> — Near-zero activity across all metrics (${win.recent_label}).`;
+ } else if (inDeclining) {
+ badge.style.display = 'block';
+ badge.style.background = '#fdf2f2';
+ badge.style.borderLeft = '4px solid #c0392b';
+ const mlStr = inDeclining.ml_trend_pct !== null ? `ML: ${inDeclining.ml_trend_pct}%` : '';
+ const gitStr = inDeclining.git_trend_pct !== null ? `Git: ${inDeclining.git_trend_pct}%` : '';
+ badge.innerHTML = `<strong>🔴 At Risk</strong> — Both mailing list and git activity declining sharply (${win.prior_label} → ${win.recent_label}). ${mlStr} ${gitStr}`;
+ } else if (inAtRisk) {
+ badge.style.display = 'block';
+ badge.style.background = '#fef9e7';
+ badge.style.borderLeft = '4px solid #e67e22';
+ const mlStr = inAtRisk.ml_trend_pct !== null ? `ML: ${inAtRisk.ml_trend_pct}%` : '';
+ const gitStr = inAtRisk.git_trend_pct !== null ? `Git: ${inAtRisk.git_trend_pct}%` : '';
+ badge.innerHTML = `<strong>🟡 Declining</strong> — Activity trending downward (${win.prior_label} → ${win.recent_label}). ${mlStr} ${gitStr}`;
+ } else {
+ badge.style.display = 'block';
+ badge.style.background = '#eafaf1';
+ badge.style.borderLeft = '4px solid #27ae60';
+ badge.innerHTML = `<strong>🟢 Healthy</strong> — No significant decline detected (${win.prior_label} → ${win.recent_label}).`;
+ }
+ }
+ } catch(healthErr) { console.warn('Health data not available:', healthErr); }
+
+ // --- Community growth (new committers + PMC members) ---
+ try {
+ const ncResp = await fetch('data/_cache/new_committers.json');
+ if (ncResp.ok) {
+ const nc = await ncResp.json();
+ const projectCommitters = nc.by_project[id] || [];
+
+ // Also check PMC roster for recent additions
+ const growthSection = document.getElementById('growth-section');
+ growthSection.style.display = 'block';
+
+ if (projectCommitters.length === 0) {
+ document.getElementById('growth-none').style.display = 'block';
+ document.querySelector('#growth-table').style.display = 'none';
+ } else {
+ const tbody = document.querySelector('#growth-table tbody');
+ projectCommitters.sort((a, b) => b.date.localeCompare(a.date));
+ projectCommitters.forEach(p => {
+ const row = document.createElement('tr');
+ row.innerHTML = `<td>${p.name}</td><td>${p.date}</td><td>Committer</td>`;
+ tbody.appendChild(row);
+ });
+ }
+ }
+ } catch(ncErr) { console.warn('New committers data not available:', ncErr); }
+
} catch(e) {
document.getElementById('error').style.display = 'block';
document.getElementById('error').textContent = `Error: ${e.message}`;
diff --git a/src/asfmetrics/collectors/git_activity.py b/src/asfmetrics/collectors/git_activity.py
index 95f4313..1338d74 100644
--- a/src/asfmetrics/collectors/git_activity.py
+++ b/src/asfmetrics/collectors/git_activity.py
@@ -180,9 +180,15 @@ def _save_cache(project: str, cache_data: dict, config: dict) -> None:
def _cache_is_current(cache: dict) -> bool:
- """Check if cache was already fetched this month."""
+ """Check if cache was fetched recently enough to skip.
+
+ Returns True only if fetched today (same date). For a weekly cron,
+ this means each run will refresh the current month's data, but
+ running multiple times in one day won't hit the API repeatedly.
+ """
fetched_at = cache.get("_fetched_at", "")
- return fetched_at[:7] == _current_month_str()
+ today = datetime.now().strftime("%Y-%m-%d")
+ return fetched_at == today
def invalidate_git_cache(config: dict) -> None:
@@ -251,8 +257,8 @@ def _fetch_github_commits(
pass
author = (
- c.get("author", {}).get("login")
- or c.get("commit", {}).get("author", {}).get("name", "unknown")
+ (c.get("author") or {}).get("login")
+ or (c.get("commit") or {}).get("author", {}).get("name", "unknown")
)
if commit_date:
@@ -334,6 +340,8 @@ def _aggregate_github_monthly(
org: str,
since: datetime,
token: str | None,
+ project: str = "",
+ progress: str = "",
) -> dict:
"""Fetch GitHub data per-repo into monthly buckets.
@@ -341,7 +349,12 @@ def _aggregate_github_monthly(
"""
per_repo = {}
- for repo in repos:
+ total_repos = len(repos)
+ for repo_idx, repo in enumerate(repos, 1):
+ import sys
+ sys.stdout.write(f"\r\033[K {progress}{project}: [{repo_idx}/{total_repos}] {org}/{repo} — fetching commits...")
+ sys.stdout.flush()
+
monthly_commits = defaultdict(int)
monthly_committers = defaultdict(set)
monthly_prs_opened = defaultdict(int)
@@ -355,6 +368,9 @@ def _aggregate_github_monthly(
monthly_commits[month] += 1
monthly_committers[month].add(c["author"])
+ sys.stdout.write(f"\r\033[K {progress}{project}: [{repo_idx}/{total_repos}] {org}/{repo} — {len(commits)} commits, fetching PRs...")
+ sys.stdout.flush()
+
# PRs
prs = _fetch_github_prs(org, repo, since, token)
for pr in prs:
@@ -386,6 +402,11 @@ def _aggregate_github_monthly(
}
per_repo[repo] = repo_data
+ rl_remaining = _rate_limit["remaining"]
+ rl_info = f" [API: {rl_remaining}]" if rl_remaining is not None else ""
+ sys.stdout.write(f"\r\033[K {progress}{project}: [{repo_idx}/{total_repos}] {org}/{repo} ✓ {len(commits)} commits, {len(prs)} PRs{rl_info}")
+ sys.stdout.flush()
+
return per_repo
@@ -396,6 +417,7 @@ def collect_github_activity(
org: str,
token: str | None,
config: dict,
+ progress: str = "",
) -> dict:
"""Collect Git activity metrics per-repo for a project via GitHub API, with caching.
@@ -409,16 +431,18 @@ def collect_github_activity(
return _build_result_from_cache(project, "github", cache, org=org, repos=repos)
if cache and cache.get("repos_data"):
- # Stale cache — only fetch current month for each repo
- since = _first_of_month(current_month)
- fresh = _aggregate_github_monthly(repos, org, since, token)
+ # Stale cache — re-fetch from the date of last fetch (inclusive)
+ # Overlap is fine: monthly data gets overwritten, not appended
+ fetched_at = cache.get("_fetched_at", "")
+ since = datetime.strptime(fetched_at, "%Y-%m-%d") if fetched_at else _twelve_months_ago()
+ fresh = _aggregate_github_monthly(repos, org, since, token, project=project, progress=progress)
cached_repos = cache.get("repos_data", {})
for repo_name, fresh_months in fresh.items():
if repo_name not in cached_repos:
cached_repos[repo_name] = {}
- if current_month in fresh_months:
- cached_repos[repo_name][current_month] = fresh_months[current_month]
+ for month_key, month_data in fresh_months.items():
+ cached_repos[repo_name][month_key] = month_data
cache["repos_data"] = cached_repos
cache["_fetched_at"] = datetime.now().strftime("%Y-%m-%d")
@@ -427,7 +451,7 @@ def collect_github_activity(
# No cache — full 12-month fetch
since = _twelve_months_ago()
- repos_data = _aggregate_github_monthly(repos, org, since, token)
+ repos_data = _aggregate_github_monthly(repos, org, since, token, project=project, progress=progress)
cache_data = {
"_fetched_at": datetime.now().strftime("%Y-%m-%d"),
@@ -522,6 +546,7 @@ def collect_svn_activity(
project: str,
svn_url: str,
config: dict,
+ progress: str = "",
) -> dict:
"""Collect commit activity from SVN, with caching. Same per-repo structure."""
current_month = _current_month_str()
@@ -531,15 +556,16 @@ def collect_svn_activity(
return _build_result_from_cache(project, "svn", cache, svn_url=svn_url)
if cache and cache.get("repos_data"):
- since = _first_of_month(current_month)
+ fetched_at = cache.get("_fetched_at", "")
+ since = datetime.strptime(fetched_at, "%Y-%m-%d") if fetched_at else _twelve_months_ago()
fresh = _aggregate_svn_monthly(svn_url, since, project)
cached_repos = cache.get("repos_data", {})
for repo_name, fresh_months in fresh.items():
if repo_name not in cached_repos:
cached_repos[repo_name] = {}
- if current_month in fresh_months:
- cached_repos[repo_name][current_month] = fresh_months[current_month]
+ for month_key, month_data in fresh_months.items():
+ cached_repos[repo_name][month_key] = month_data
cache["repos_data"] = cached_repos
cache["_fetched_at"] = datetime.now().strftime("%Y-%m-%d")
@@ -669,7 +695,7 @@ def _empty_result(project: str, vcs: str, url: str) -> dict:
# Main entry point
# ---------------------------------------------------------------------------
-def collect_git_activity(project: str, config: dict) -> dict | None:
+def collect_git_activity(project: str, config: dict, progress: str = "") -> dict | None:
"""Collect VCS activity metrics for a project.
Determines the correct backend (github/svn) from config and
@@ -689,6 +715,25 @@ def collect_git_activity(project: str, config: dict) -> dict | None:
# Determine VCS backend for this project
vcs = overrides.get("vcs", git_config.get("backend", "github"))
+ # Auto-detect SVN-only projects from repositories.json
+ if vcs == "github" and not overrides.get("vcs"):
+ json_dir = Path(config.get("output", {}).get("json_dir", "./site/data/"))
+ repos_cache = json_dir / "_cache" / "repositories.json"
+ if repos_cache.exists():
+ with open(repos_cache) as f:
+ all_repos = json.load(f)
+ # Check if project has SVN but no git repos
+ has_svn = f"{project}-svn" in all_repos
+ has_git = any(
+ k == project or (k.startswith(f"{project}-") and not k.endswith("-svn"))
+ for k in all_repos.keys()
+ )
+ if has_svn and not has_git:
+ vcs = "svn"
+ svn_url = all_repos.get(f"{project}-svn", "")
+ if svn_url.startswith("http"):
+ return collect_svn_activity(project, svn_url.rstrip("/") + "/trunk", config, progress=progress)
+
if vcs == "svn":
# SVN backend
svn_url = overrides.get("svn_path")
@@ -697,7 +742,7 @@ def collect_git_activity(project: str, config: dict) -> dict | None:
if not svn_url:
svn_url = f"{ASF_SVN_BASE}/{project}/trunk"
- return collect_svn_activity(project, svn_url, config)
+ return collect_svn_activity(project, svn_url, config, progress=progress)
elif vcs == "github":
# GitHub backend
@@ -724,7 +769,7 @@ def collect_git_activity(project: str, config: dict) -> dict | None:
if not repos:
repos = [project]
- return collect_github_activity(project, repos, org, token, config)
+ return collect_github_activity(project, repos, org, token, config, progress=progress)
else:
print(f" warning: unknown VCS backend '{vcs}' for {project}")
diff --git a/src/asfmetrics/collectors/mailing_lists.py b/src/asfmetrics/collectors/mailing_lists.py
index 91908ff..975c15a 100644
--- a/src/asfmetrics/collectors/mailing_lists.py
+++ b/src/asfmetrics/collectors/mailing_lists.py
@@ -79,15 +79,14 @@ def _save_cache(project: str, cache_data: dict, config: dict) -> None:
def _cache_is_current(cache: dict) -> bool:
- """Check if cache has already been fetched this month.
+ """Check if cache was fetched today (same date).
- If _fetched_at matches the current month, all data is current
- (past months are immutable, and the current month was fetched today
- or at least this month).
+ Same-day re-runs skip (saves API calls during testing).
+ Next-day or later runs always refresh current month data.
"""
fetched_at = cache.get("_fetched_at", "")
- # Compare YYYY-MM portion
- return fetched_at[:7] == _current_month_str()
+ today = datetime.now().strftime("%Y-%m-%d")
+ return fetched_at == today
def discover_lists(base_url: str = PONYMAIL_API) -> dict:
@@ -158,11 +157,14 @@ def _fetch_current_month_stats(
domain: str,
base_url: str = PONYMAIL_API,
) -> dict | None:
- """Fetch stats for just the current month (1M window).
+ """Fetch stats for the current + previous month (2M window).
- Used for incremental cache updates — only refreshes the current month.
+ Used for incremental cache updates. We use 2M (not 1M) because if
+ the last run was late in the previous month, the previous month's
+ final count may have increased since then. Two months guarantees
+ we pick up the tail end of the previous month.
"""
- return collect_list_stats(list_name, domain, base_url, timespan="1M", quick=True)
+ return collect_list_stats(list_name, domain, base_url, timespan="2M", quick=True)
def collect_mailing_list_stats(project: str, config: dict) -> dict | None:
@@ -218,14 +220,13 @@ def collect_mailing_list_stats(project: str, config: dict) -> dict | None:
stats = _fetch_current_month_stats(list_name, domain, base_url)
if stats:
months = stats.get("active_months", {})
- # Update just the current month in the cached months
+ # Update current + previous month in the cached months
+ # (2M window covers both; previous month may have grown since last fetch)
cached_months = list_data.get("active_months", {})
- if current_month in months:
- cached_months[current_month] = months[current_month]
- elif current_month not in cached_months:
- # API returned no data for current month — set to 0
- # (or leave missing, either is fine)
- pass
+ for month_key, count in months.items():
+ # Overwrite any month returned by the 2M window
+ # (current month + previous month)
+ cached_months[month_key] = count
list_data["active_months"] = cached_months
# Update totals from the full month range
list_data["messages"] = sum(
diff --git a/src/asfmetrics/health.py b/src/asfmetrics/health.py
index 4d3eac1..e5ab2df 100644
--- a/src/asfmetrics/health.py
+++ b/src/asfmetrics/health.py
@@ -181,6 +181,8 @@ def compute_project_health(config: dict) -> dict:
git_declining = git_pct is not None and git_pct <= DECLINE_THRESHOLD
ml_moderate = ml_pct is not None and ml_pct <= MODERATE_DECLINE
git_moderate = git_pct is not None and git_pct <= MODERATE_DECLINE
+ ml_growing = ml_pct is not None and ml_pct >= -DECLINE_THRESHOLD # +30% or more
+ git_growing = git_pct is not None and git_pct >= -DECLINE_THRESHOLD
# Declining: both axes down sharply
if ml_declining and git_declining:
@@ -190,11 +192,12 @@ def compute_project_health(config: dict) -> dict:
elif git_pct is not None and git_pct <= -60 and ml_moderate:
declining.append(entry)
# At Risk: one axis down sharply (with meaningful prior activity)
- elif ml_declining and (ml_prior >= MIN_PRIOR_ACTIVITY or git_prior >= MIN_PRIOR_ACTIVITY):
+ # But NOT if the other axis is growing strongly (compensating)
+ elif ml_declining and not git_growing and (ml_prior >= MIN_PRIOR_ACTIVITY or git_prior >= MIN_PRIOR_ACTIVITY):
at_risk.append(entry)
- elif git_declining and (ml_prior >= MIN_PRIOR_ACTIVITY or git_prior >= MIN_PRIOR_ACTIVITY):
+ elif git_declining and not ml_growing and (ml_prior >= MIN_PRIOR_ACTIVITY or git_prior >= MIN_PRIOR_ACTIVITY):
at_risk.append(entry)
- elif ml_moderate and git_moderate and (ml_prior >= MIN_PRIOR_ACTIVITY or git_prior >= MIN_PRIOR_ACTIVITY):
+ elif ml_moderate and git_moderate and not ml_growing and not git_growing and (ml_prior >= MIN_PRIOR_ACTIVITY or git_prior >= MIN_PRIOR_ACTIVITY):
at_risk.append(entry)
# Sort by severity (combined trend percentage, most negative first)