orders: read every page, never a fixed 200-order window
The collective crossed 200 orders on 2026-11-23 (203). fetch_member_orders() asked for orders(limit: 200) in one request, so the orders beyond the window — the OLDEST ones, where long-standing members' recurring contributions live — were absent from the sweep's read. Three paying members (ntnsndr, elizabeth-barry1, guest-0f6d98ac) therefore read as "no recurring (monthly) contribution on Open Collective" and were sent a payment reminder at 03:02 UTC for contributions that were live and charged on 2 Nov. fetch_oc_monthly_order_charges() had the same fixed window, hiding the oldest orders' charge ladders from the shortfall credit pass. Both now page by offset until OC's totalCount is covered, and a read that falls short of totalCount RAISES instead of returning a short list: a short list is the exact shape that reads as "nobody is paying".
This commit is contained in:
1 parent
f09bec67d8
commit
c60dc2c482
2 files changed
+216
-11
No files matched your search
+46
-11
@@ -8088,20 +8088,25 @@ async def fetch_member_orders() -> dict[str, list[dict]]:
|
|||||||
"""
|
"""
|
||||||
if not OC_PERSONAL_TOKEN:
|
if not OC_PERSONAL_TOKEN:
|
||||||
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch orders")
|
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch orders")
|
||||||
query = (
|
per_page = 100
|
||||||
'{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { '
|
max_pages = 20 # 2,000 orders — a runaway loop is worse than a short read
|
||||||
|
query_tpl = (
|
||||||
|
'{ collective(slug: "%s") { orders(limit: %d, offset: %d) { totalCount nodes { '
|
||||||
"frequency status createdAt lastChargedAt nextChargeDate "
|
"frequency status createdAt lastChargedAt nextChargeDate "
|
||||||
"fromAccount { slug } amount { value currency } totalAmount { value currency } } } } }"
|
"fromAccount { slug } amount { value currency } totalAmount { value currency } } } } }"
|
||||||
% OC_COLLECTIVE_SLUG
|
|
||||||
)
|
)
|
||||||
|
by_slug: dict[str, list[dict]] = {}
|
||||||
|
seen = 0
|
||||||
|
total = None
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
for page in range(max_pages):
|
||||||
r = await client.post(
|
r = await client.post(
|
||||||
OC_GRAPHQL_URL,
|
OC_GRAPHQL_URL,
|
||||||
headers={"Content-Type": "application/json",
|
headers={"Content-Type": "application/json",
|
||||||
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
|
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
|
||||||
"Api-Version": "2022-01-01",
|
"Api-Version": "2022-01-01",
|
||||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
|
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
|
||||||
json={"query": query},
|
json={"query": query_tpl % (OC_COLLECTIVE_SLUG, per_page, page * per_page)},
|
||||||
)
|
)
|
||||||
if r.status_code != 200:
|
if r.status_code != 200:
|
||||||
raise RuntimeError(f"OC order fetch failed: HTTP {r.status_code}")
|
raise RuntimeError(f"OC order fetch failed: HTTP {r.status_code}")
|
||||||
@@ -8109,11 +8114,23 @@ async def fetch_member_orders() -> dict[str, list[dict]]:
|
|||||||
if body.get("errors"):
|
if body.get("errors"):
|
||||||
raise RuntimeError(f"OC order fetch errors: {str(body['errors'])[:200]}")
|
raise RuntimeError(f"OC order fetch errors: {str(body['errors'])[:200]}")
|
||||||
orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {})
|
orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {})
|
||||||
by_slug: dict[str, list[dict]] = {}
|
nodes = orders.get("nodes") or []
|
||||||
for o in orders.get("nodes") or []:
|
total = orders.get("totalCount") or 0
|
||||||
|
for o in nodes:
|
||||||
slug = ((o.get("fromAccount") or {}).get("slug") or "").strip()
|
slug = ((o.get("fromAccount") or {}).get("slug") or "").strip()
|
||||||
if slug:
|
if slug:
|
||||||
by_slug.setdefault(slug, []).append(o)
|
by_slug.setdefault(slug, []).append(o)
|
||||||
|
seen += len(nodes)
|
||||||
|
if len(nodes) < per_page or seen >= total:
|
||||||
|
break
|
||||||
|
# A read that fell short of OC's own total is PARTIAL, however it ended:
|
||||||
|
# a partial order list reads as "this member has no recurring
|
||||||
|
# contribution", which reminds (then deactivates) a paying member —
|
||||||
|
# so fail loudly instead of returning a shorter, wrong answer.
|
||||||
|
if total is not None and seen < total:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"OC order fetch incomplete: read {seen} of {total} orders "
|
||||||
|
f"(page cap {max_pages})")
|
||||||
return by_slug
|
return by_slug
|
||||||
|
|
||||||
|
|
||||||
@@ -8882,27 +8899,45 @@ async def fetch_oc_monthly_order_charges() -> list[dict]:
|
|||||||
"""
|
"""
|
||||||
if not OC_PERSONAL_TOKEN:
|
if not OC_PERSONAL_TOKEN:
|
||||||
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch order charges")
|
raise RuntimeError("OC_PERSONAL_TOKEN not set; cannot fetch order charges")
|
||||||
query = (
|
# Paginate: a fixed limit silently dropped the OLDEST orders once the
|
||||||
'{ collective(slug: "%s") { orders(limit: 200) { totalCount nodes { '
|
# collective passed it, and an order missing from this read is a truncated
|
||||||
|
# cycle the shortfall pass can never see (or, worse, an order it misreads).
|
||||||
|
per_page = 100
|
||||||
|
max_pages = 20
|
||||||
|
query_tpl = (
|
||||||
|
'{ collective(slug: "%s") { orders(limit: %d, offset: %d) { totalCount nodes { '
|
||||||
"id frequency fromAccount { slug } "
|
"id frequency fromAccount { slug } "
|
||||||
"transactions { publicId createdAt type kind isRefund } } } } }"
|
"transactions { publicId createdAt type kind isRefund } } } } }"
|
||||||
% OC_COLLECTIVE_SLUG
|
|
||||||
)
|
)
|
||||||
|
nodes: list[dict] = []
|
||||||
|
seen = 0
|
||||||
|
total = None
|
||||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
for page in range(max_pages):
|
||||||
r = await client.post(
|
r = await client.post(
|
||||||
OC_GRAPHQL_URL,
|
OC_GRAPHQL_URL,
|
||||||
headers={"Content-Type": "application/json",
|
headers={"Content-Type": "application/json",
|
||||||
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
|
"Authorization": f"Bearer {OC_PERSONAL_TOKEN}",
|
||||||
"Api-Version": "2022-01-01",
|
"Api-Version": "2022-01-01",
|
||||||
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
|
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"},
|
||||||
json={"query": query},
|
json={"query": query_tpl % (OC_COLLECTIVE_SLUG, per_page, page * per_page)},
|
||||||
)
|
)
|
||||||
if r.status_code != 200:
|
if r.status_code != 200:
|
||||||
raise RuntimeError(f"OC order-charge fetch failed: HTTP {r.status_code}")
|
raise RuntimeError(f"OC order-charge fetch failed: HTTP {r.status_code}")
|
||||||
body = r.json()
|
body = r.json()
|
||||||
if body.get("errors"):
|
if body.get("errors"):
|
||||||
raise RuntimeError(f"OC order-charge fetch errors: {str(body['errors'])[:200]}")
|
raise RuntimeError(f"OC order-charge fetch errors: {str(body['errors'])[:200]}")
|
||||||
nodes = (((body.get("data") or {}).get("collective") or {}).get("orders") or {}).get("nodes") or []
|
orders = (((body.get("data") or {}).get("collective") or {}).get("orders") or {})
|
||||||
|
page_nodes = orders.get("nodes") or []
|
||||||
|
total = orders.get("totalCount") or 0
|
||||||
|
nodes.extend(page_nodes)
|
||||||
|
seen += len(page_nodes)
|
||||||
|
if len(page_nodes) < per_page or seen >= total:
|
||||||
|
break
|
||||||
|
if total is not None and seen < total:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"OC order-charge fetch incomplete: read {seen} of {total} orders "
|
||||||
|
f"(page cap {max_pages})")
|
||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
for o in nodes:
|
for o in nodes:
|
||||||
if (o.get("frequency") or "").upper() != "MONTHLY":
|
if (o.get("frequency") or "").upper() != "MONTHLY":
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regression test: the OC order reads must PAGE, not stop at a fixed limit.
|
||||||
|
|
||||||
|
WHY THIS EXISTS
|
||||||
|
fetch_member_orders() asked OC for `orders(limit: 200)` in ONE request. The
|
||||||
|
collective passed 200 orders on 2026-11-23 (203), and the orders beyond the
|
||||||
|
window are the OLDEST ones — exactly where a long-standing member's recurring
|
||||||
|
contribution lives. Those members read as "no recurring (monthly)
|
||||||
|
contribution on Open Collective", so the allowance sweep sent them a
|
||||||
|
payment reminder for a contribution that was LIVE and charged days earlier.
|
||||||
|
Three paying members (ntnsndr, elizabeth-barry1, guest-0f6d98ac) got that
|
||||||
|
wrong email at 03:02 UTC on 2026-11-23.
|
||||||
|
|
||||||
|
fetch_oc_monthly_order_charges() had the same fixed window; an order missing
|
||||||
|
from it is a truncated paid cycle the shortfall credit pass cannot see.
|
||||||
|
|
||||||
|
WHAT IS PINNED HERE
|
||||||
|
* every order is read across pages (203 orders -> two pages, oldest included),
|
||||||
|
* a member whose ONLY recurring order is the oldest one is still matched,
|
||||||
|
* an INCOMPLETE read (OC reports more than it served) raises instead of
|
||||||
|
returning a short list, because a short list reads as "nobody is paying",
|
||||||
|
* the charge ladder for the oldest monthly orders is read too.
|
||||||
|
|
||||||
|
Runnable from the repo root: python3 tests/test_order_pagination.py
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import asyncio
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
import app.main as m # noqa: E402
|
||||||
|
|
||||||
|
m.DB_PATH = os.environ["DB_PATH"]
|
||||||
|
m.OC_PERSONAL_TOKEN = "test-token"
|
||||||
|
m.OC_COLLECTIVE_SLUG = "inference-cooperative"
|
||||||
|
|
||||||
|
# The three slugs whose live monthly orders were the OLDEST in production and
|
||||||
|
# therefore fell outside the fixed 200-order window.
|
||||||
|
OLDEST = ["ntnsndr", "elizabeth-barry1", "guest-0f6d98ac"]
|
||||||
|
|
||||||
|
TOTAL_ORDERS = 203
|
||||||
|
SERVED: dict[str, int | None] = {"n": None} # None = serve everything; an int = pretend truncation
|
||||||
|
REQUESTS = []
|
||||||
|
|
||||||
|
|
||||||
|
def make_nodes(n=TOTAL_ORDERS):
|
||||||
|
"""Newest-first list; the OLDEST three are our live monthly members."""
|
||||||
|
nodes = []
|
||||||
|
for i in range(n):
|
||||||
|
oldest_rank = n - 1 - i # 0 for the newest, n-1 for the oldest
|
||||||
|
slug = OLDEST[oldest_rank] if oldest_rank < len(OLDEST) else f"member{oldest_rank}"
|
||||||
|
nodes.append({
|
||||||
|
"id": f"or_{slug}",
|
||||||
|
"frequency": "MONTHLY",
|
||||||
|
"status": "ACTIVE",
|
||||||
|
"createdAt": f"2026-{9 + oldest_rank // 30:02d}-{(oldest_rank % 28) + 1:02d}T10:00:00Z",
|
||||||
|
"lastChargedAt": "2026-11-02T17:06:25.000Z",
|
||||||
|
"nextChargeDate": "2026-12-01T00:00:00.000Z",
|
||||||
|
"fromAccount": {"slug": slug},
|
||||||
|
"amount": {"value": 15, "currency": "USD"},
|
||||||
|
"totalAmount": {"value": 15.75, "currency": "USD"},
|
||||||
|
"transactions": [
|
||||||
|
{"publicId": f"txn_{slug}_a", "createdAt": "2026-10-02T10:00:00Z",
|
||||||
|
"type": "CREDIT", "kind": "CONTRIBUTION", "isRefund": False},
|
||||||
|
{"publicId": f"txn_{slug}_b", "createdAt": "2026-11-02T10:00:00Z",
|
||||||
|
"type": "CREDIT", "kind": "CONTRIBUTION", "isRefund": False},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
|
||||||
|
NODES = make_nodes()
|
||||||
|
|
||||||
|
|
||||||
|
class Resp:
|
||||||
|
def __init__(self, body, status_code=200):
|
||||||
|
self._body = body
|
||||||
|
self.status_code = status_code
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self._body
|
||||||
|
|
||||||
|
|
||||||
|
def _int_arg(query, name):
|
||||||
|
"""Read `name: <int>` out of the GraphQL query string."""
|
||||||
|
for part in query.split("orders(")[1].split(")")[0].split(","):
|
||||||
|
k, _, v = part.strip().partition(":")
|
||||||
|
if k.strip() == name:
|
||||||
|
return int(v)
|
||||||
|
raise AssertionError(f"query carries no {name}: {query}")
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClient:
|
||||||
|
"""Async httpx stand-in: serves OC's orders connection page by page."""
|
||||||
|
|
||||||
|
def __init__(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *exc):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def post(self, url, headers=None, json=None):
|
||||||
|
q = (json or {}).get("query", "")
|
||||||
|
REQUESTS.append(q)
|
||||||
|
limit = _int_arg(q, "limit")
|
||||||
|
offset = _int_arg(q, "offset")
|
||||||
|
served = SERVED["n"] if SERVED["n"] is not None else len(NODES)
|
||||||
|
page = NODES[offset:offset + limit] if offset < served else []
|
||||||
|
return Resp({"data": {"collective": {"orders": {
|
||||||
|
"totalCount": len(NODES), "nodes": page}}}})
|
||||||
|
|
||||||
|
|
||||||
|
m.httpx.AsyncClient = FakeClient
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, ok):
|
||||||
|
results.append((name, bool(ok)))
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
# --- fetch_member_orders: every order read, oldest members matched ---------
|
||||||
|
REQUESTS.clear()
|
||||||
|
by_slug = await m.fetch_member_orders()
|
||||||
|
check(f"orders read across pages (got {len(REQUESTS)} requests)", len(REQUESTS) == 3)
|
||||||
|
check(f"all 203 payers grouped (got {len(by_slug)})", len(by_slug) == TOTAL_ORDERS)
|
||||||
|
for slug in OLDEST:
|
||||||
|
orders = by_slug.get(slug) or []
|
||||||
|
check(f"oldest member {slug} is matched ({len(orders)} order)",
|
||||||
|
len(orders) == 1 and orders[0].get("status") == "ACTIVE")
|
||||||
|
# the fixed-limit bug's exact reading: these three used to be absent
|
||||||
|
check("no member is dropped by a 200-entry window",
|
||||||
|
all(s in by_slug for s in OLDEST))
|
||||||
|
|
||||||
|
# --- a partial read must RAISE, never answer short ------------------------
|
||||||
|
REQUESTS.clear()
|
||||||
|
SERVED["n"] = 200 # OC says 203, serves 200
|
||||||
|
raised = None
|
||||||
|
try:
|
||||||
|
await m.fetch_member_orders()
|
||||||
|
except RuntimeError as e:
|
||||||
|
raised = str(e)
|
||||||
|
SERVED["n"] = None
|
||||||
|
check(f"incomplete read raises (got {raised!r})",
|
||||||
|
raised is not None and "incomplete" in raised)
|
||||||
|
|
||||||
|
# --- fetch_oc_monthly_order_charges: paginated too -----------------------
|
||||||
|
REQUESTS.clear()
|
||||||
|
records = await m.fetch_oc_monthly_order_charges()
|
||||||
|
check(f"charge pass pages (got {len(REQUESTS)} requests)", len(REQUESTS) == 3)
|
||||||
|
check(f"charge pass covers every monthly order (got {len(records)})",
|
||||||
|
len(records) == TOTAL_ORDERS)
|
||||||
|
oldest_ids = {f"or_{s}" for s in OLDEST}
|
||||||
|
check("oldest orders' charge ladders present",
|
||||||
|
oldest_ids <= {r.get("order_id") for r in records})
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
|
|
||||||
|
fails = sum(not ok for _, ok in results)
|
||||||
|
for name, ok in results:
|
||||||
|
print(f" [{'PASS' if ok else 'FAIL'}] {name}")
|
||||||
|
print(f"\n{len(results) - fails}/{len(results)} passed")
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
Reference in new issue
Block a user