Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(gsc): derive site totals from dimensionless aggregate, not query-row sum (#130)

Danielddee627e6660
diff --git a/scripts/gsc_query.py b/scripts/gsc_query.py
index 10120f8..2dcee7b 100644
--- a/scripts/gsc_query.py
+++ b/scripts/gsc_query.py
@@ -55,6 +55,49 @@ def _build_gsc_service():
return None
+def _query_site_totals(
+ service,
+ site_url: str,
+ start_date: str,
+ end_date: str,
+ search_type: str,
+ data_state: str,
+ filters: Optional[list],
+) -> Optional[dict]:
+ """Fetch true site-wide totals via a dimensionless query.
+
+ GSC anonymizes click data for low-volume ("rare") queries, so summing
+ the per-query rows undercounts clicks (often to exactly 0) and
+ impressions. A query with an empty ``dimensions`` array returns a
+ single aggregate row carrying the real site totals (issue #130).
+ Returns ``None`` if the aggregate query fails (caller falls back).
+ """
+ body = {
+ "startDate": start_date,
+ "endDate": end_date,
+ "dimensions": [],
+ "type": search_type,
+ "rowLimit": 1,
+ "dataState": data_state,
+ }
+ if filters:
+ body["dimensionFilterGroups"] = [{"filters": filters}]
+ try:
+ response = service.searchanalytics().query(siteUrl=site_url, body=body).execute()
+ except Exception:
+ return None
+ rows = response.get("rows", [])
+ if not rows:
+ return {"clicks": 0, "impressions": 0, "ctr": 0, "position": 0}
+ agg = rows[0]
+ return {
+ "clicks": agg.get("clicks", 0),
+ "impressions": agg.get("impressions", 0),
+ "ctr": round(agg.get("ctr", 0) * 100, 2),
+ "position": round(agg.get("position", 0), 1),
+ }
+
+
def query_search_analytics(
site_url: str,
start_date: Optional[str] = None,
@@ -189,10 +232,22 @@ def query_search_analytics(
total_impressions += impressions
result["row_count"] = len(all_rows)
- result["totals"]["clicks"] = total_clicks
- result["totals"]["impressions"] = total_impressions
- if total_impressions > 0:
- result["totals"]["ctr"] = round((total_clicks / total_impressions) * 100, 2)
+
+ # Site totals come from a dimensionless aggregate query, NOT from summing
+ # the per-dimension rows. Summing query-dimension rows undercounts clicks
+ # because GSC anonymizes low-volume queries, producing a false "0 clicks"
+ # site total (issue #130). Fall back to the row sum only if the aggregate
+ # query fails.
+ site_totals = _query_site_totals(
+ service, site_url, start_date, end_date, search_type, data_state, filters
+ )
+ if site_totals is not None:
+ result["totals"] = site_totals
+ else:
+ result["totals"]["clicks"] = total_clicks
+ result["totals"]["impressions"] = total_impressions
+ if total_impressions > 0:
+ result["totals"]["ctr"] = round((total_clicks / total_impressions) * 100, 2)
# Quick wins: position 4-10 with high impressions
if "query" in dimensions:
diff --git a/tests/test_gsc_totals_aggregate.py b/tests/test_gsc_totals_aggregate.py
new file mode 100644
index 0000000..3a439d4
--- /dev/null
+++ b/tests/test_gsc_totals_aggregate.py
@@ -0,0 +1,69 @@
+"""Regression for issue #130: GSC site totals must come from a dimensionless
+aggregate query, not from summing per-query rows (which GSC anonymizes,
+producing a false "0 clicks" site total).
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+import gsc_query # noqa: E402
+
+
+class _Exec:
+ def __init__(self, response):
+ self._response = response
+
+ def execute(self):
+ return self._response
+
+
+class _SearchAnalytics:
+ """Query-dimension rows hide clicks (anonymized); the dimensionless
+ aggregate carries the real totals."""
+
+ def query(self, siteUrl=None, body=None):
+ if body.get("dimensions") == []:
+ return _Exec({"rows": [
+ {"clicks": 24, "impressions": 2734, "ctr": 0.0088, "position": 12.3},
+ ]})
+ return _Exec({"rows": [
+ {"keys": ["kw a"], "clicks": 0, "impressions": 500, "ctr": 0, "position": 8},
+ {"keys": ["kw b"], "clicks": 0, "impressions": 428, "ctr": 0, "position": 9},
+ ]})
+
+
+class _Service:
+ def searchanalytics(self):
+ return _SearchAnalytics()
+
+
+def test_totals_use_aggregate_not_query_sum():
+ with mock.patch.object(gsc_query, "_build_gsc_service", return_value=_Service()):
+ result = gsc_query.query_search_analytics("sc-domain:example.com", dimensions=["query"])
+ # Summing the query rows would yield 0 clicks; the aggregate is the truth.
+ assert result["totals"]["clicks"] == 24, result["totals"]
+ assert result["totals"]["impressions"] == 2734, result["totals"]
+ assert result["row_count"] == 2 # rows still come from the dimensioned query
+
+
+def test_totals_fall_back_to_row_sum_when_aggregate_fails():
+ class _FailingSA(_SearchAnalytics):
+ def query(self, siteUrl=None, body=None):
+ if body.get("dimensions") == []:
+ raise RuntimeError("aggregate query failed")
+ return super().query(siteUrl=siteUrl, body=body)
+
+ class _FailingService:
+ def searchanalytics(self):
+ return _FailingSA()
+
+ with mock.patch.object(gsc_query, "_build_gsc_service", return_value=_FailingService()):
+ result = gsc_query.query_search_analytics("sc-domain:example.com", dimensions=["query"])
+ # Aggregate failed -> fall back to the summed rows (impressions still add up).
+ assert result["totals"]["impressions"] == 928, result["totals"]