Author SHA1 Message Date
inference-bot bbd8115058 manifest: pin to 20261202-ca336a3
ci/woodpecker/push/woodpecker Pipeline failed
2026-12-02 15:33:05 +00:00
inference-bot ca336a3115 credits: only charge spend incurred while credits were available (#12 follow-up)
ci/woodpecker/push/woodpecker Pipeline was canceled
close_credit_cycles drew max(0, cycle_spend - allowance) capped by the
pack's current balance, so a pack bought mid-cycle was charged for spend
that predated it. Split the cycle at the first grant: allowance is consumed
first, then credits cover only the spend after they became available.
apply_cycle_draw takes the eligible figure; the ledger reason records it.
Correction rows for the six over-drawn clawback cycles are separate.
2026-12-02 15:32:34 +00:00
inference-admin 122824fd99 manifest: pin to 20261128-1191bcd
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-28 14:04:22 +00:00
inference-admin 1191bcd521 spend: name the unattributed slice of own spend for posterity
own_all_time_spend already includes SpendLogs rows that join to no team alias,
but the remainder was unnamed, so every reader had to notice it by subtraction.
coop_spend_totals() now reports own_unattributed_spend and both payloads
(/admin/overview totals and admin/money-series totals) carry it: the gateway's
own overhead, historically the master-key audio keepalive pings (~$3.21 over
16,894 rows before the 2026-11-28 key split).

History is labelled, never rewritten: LiteLLM_SpendLogs is the system of record
and the portal keeps read-only access, so no team_id is backfilled.
2026-11-28 14:03:47 +00:00
inference-bot aba53eabb5 manifest: pin to 20261127-fb6af42
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-28 02:42:36 +00:00
inference-bot fb6af42bbf allowance: keep reset dates on the join day after LiteLLM resets
ci/woodpecker/push/woodpecker Pipeline was canceled
LiteLLM's reset job treats budget_duration '30d' as 'monthly on the 1st' and
rewrites budget_reset_at to the next month's first day after every reset. The
dues reconcile repins only members whose payment it verified; manual and
org-backed rows are skipped, so their renewal drifts to the calendar month.
pin_member_reset_dates() pins every active non-guest row from its anchor day,
writing only when the stored date differs; it runs in /admin/sweep.

Observed live: 27 members showed 2026-12-01 instead of their join-day date
after the Nov 28 reset; 26 were anchor-day 28.
2026-11-28 02:41:48 +00:00
inference-bot 6124d05ffd manifest: pin to 20261127-d10b36e
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 22:05:49 +00:00
inference-bot d10b36ed34 credits: an adjustment below the drawn amount must not eat the next pack
ci/woodpecker/push/woodpecker Pipeline was canceled
credits_drawn could exceed credit_balance after an admin set/correction (or a
negative adjustment), so a later pack was only partly usable: available =
max(0, purchased - drawn) swallowed the difference. Cap credits_drawn at the
row's balance on every add_credits movement; ledger history is unchanged.
Tests cover reduction-then-repurchase.
2026-11-27 22:05:19 +00:00
inference-bot 066a6fc2cf manifest: pin to 20261127-a70dd6a
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 22:04:22 +00:00
inference-bot a70dd6ab4c guests: only UNSPENT credit carries into membership
ci/woodpecker/push/woodpecker Pipeline was canceled
A guest has no monthly cycle, so nothing ever drew their spend against the $2
pack. Conversion kept the full credit_balance, handing back credits already
used — guest-access.md promises only the unspent credit carries over.

record_guest_conversion_draw() writes the consumed part as a negative ledger
row (reference guest-convert-draw:<email>) and bumps credits_drawn, capped by
the row's credit and idempotent on replay. Tests cover draw, replay, cap, and
the resulting remaining figure.
2026-11-27 22:03:43 +00:00
inference-bot cfb767dd4f manifest: pin to 20261127-18a4447
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:59:21 +00:00
inference-bot 18a4447aa2 usage: handle an uncapped team in /broker/usage
ci/woodpecker/push/woodpecker Pipeline was canceled
An operator account has team max_budget NULL (no cap). broker_get_usage only
assigned balance when max_budget was not None, so the DB path left 'balance'
unbound and the HTTP fallback read the same name before assignment — a 500 for
exactly the accounts the uncapped policy created. Initialise balance from the
member's allowance + credits still available, mark the response uncapped when
the team row has no cap, and keep the dashboard arithmetic defined.
2026-11-27 21:58:34 +00:00
inference-bot dc53b27ad2 manifest: pin to 20261127-3e01f72
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:35:52 +00:00
inference-bot 3e01f727c2 credits: defer a clawback cap that would fall under recorded spend
ci/woodpecker/push/woodpecker Pipeline was canceled
Applying the draw mid-cycle used to push max_budget below the member's
already-recorded spend, so LiteLLM refused every call until their next reset
(weeks for some anchors). The draw is still recorded immediately — books are
correct — but the cap is only pushed once the member's spend has room for it,
which happens right after LiteLLM's reset. The tick retries every 10 minutes,
so the cap lands at the first tick after the boundary; deferred members are
reported in close_credit_cycles().deferred.

tests/test_credit_cycle_close.py covers draw-recorded/cap-deferred and the
cap landing after spend resets, with no second draw.
2026-11-27 21:35:02 +00:00
inference-bot 1070fc5dd0 manifest: pin to 20261127-0296f8d
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:23:58 +00:00
inference-bot 0296f8d066 credits: infer anchor days for org-backed members
ci/woodpecker/push/woodpecker Pipeline was canceled
The allowance reconcile skips rows with org_slug (dues are paid by an OC
Organization, not an individual order), so org members never got an anchor_day
and close_credit_cycles skipped them forever — their packs regenerated monthly,
the same defect as #12.

- fetch_org_join_days(): paginated OC members walk, ORGANIZATION accounts only,
  slug -> membership createdAt.
- reconcile_org_anchors(): for every active org-backed row with anchor_day NULL,
  set anchor = org join day clamped to 1..28 and pin the team reset to its next
  occurrence. Only NULL rows are touched (idempotent); an org with no OC record is
  reported, never guessed, and keeps being reported until resolved.
- Runs in /admin/sweep and immediately in the org-member webhook path.

tests/test_org_anchors.py: anchor math incl. clamp, reset pin, idempotence,
unresolved reporting.
2026-11-27 21:23:24 +00:00
inference-bot 3d326ed428 manifest: pin to 20261127-97f0d6c
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 21:20:30 +00:00
inference-bot 97f0d6c3f1 credits: uncapped operator accounts; no cap for info@
ci/woodpecker/push/woodpecker Pipeline was canceled
Operator/infrastructure accounts are a collective expense, not members: applying
the $15 + credits cap to them cuts the co-op's own tooling off mid-task.

- UNCAPPED_EMAILS (defaults to OPERATOR_EMAILS) is cleared in
  sync_team_budget_from_balance via litellm_clear_team_budget: max_budget = NULL
  on the team row (unlimited), written directly because /team/update drops
  budget_reset_at.
- sync_team_budget_from_balance returns None for an uncapped account; admin
  responses report team_budget: null rather than a computed figure.
2026-11-27 21:19:52 +00:00
inference-bot 237b695087 manifest: pin to 20261127-fe89890
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 20:42:13 +00:00
inference-bot fe898905b4 credits: close each cycle so a pack cannot be spent twice (#12)
ci/woodpecker/push/woodpecker Pipeline failed
LiteLLM zeroes a team's `spend` at budget_reset_at but leaves max_budget
alone, and nothing in the portal ever reduced credit_balance. So every
monthly reset restored every credit pack already spent: a $15 member who
bought $50 and used all $65 got $65 again the next month.

Fix — record the draw when a cycle closes:
- new `members.credits_drawn` (credits consumed in CLOSED cycles);
  credit_balance stays the lifetime purchased total so the "bought all-time"
  display never changes meaning.
- `compute_max_budget` caps at allowance + credits STILL AVAILABLE
  (purchased − drawn). Spend inside the current cycle still does not shrink
  the cap, so a credit add keeps raising it 1:1.
- `apply_cycle_draw` writes a NEGATIVE credit_ledger row per closed cycle,
  deduped on reference `cycle-close:<email>:<cycle>`; the cycle's spend is
  summed from LiteLLM_SpendLogs over the exact anchor-day window.
- `close_credit_cycles` runs every 10 min via the new Cloudron scheduler task
  (credit_cycle_close.sh) and again as a catch-up inside /admin/sweep.
- CREDIT_CLOSE_FROM (default 2026-11-28) stops it charging cycles that
  started before the fix: credits already regranted are forgiven rather than
  clawed back mid-cycle.
- /admin/credits/{email} now reports credits_drawn.

Tests: tests/test_credit_cycle_close.py covers the cap arithmetic, the
issue's worked example, draw idempotence and the available-credit cap.
2026-11-27 20:29:12 +00:00
inference-bot bcdc0416e2 manifest: pin to 20261127-0e53c33
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-27 18:04:29 +00:00
inference-bot 0e53c330e1 tests: FX verdict at the 1.0975 fallback pin
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-27 18:04:00 +00:00
inference-bot 9ab8156da2 fx: baseline the spot check at the written fallback pin, not a stale 1.16
ci/woodpecker/push/woodpecker Pipeline failed
The sweep compared the ECB rate to a hardcoded 1.16 and emailed info@ with
"-5.39%" plus advice to "re-convert" — obsolete since fx_sync.py converts at
boot. The steady breach also froze the alert marker, so a later, real move
could never mail.

- Default baseline 1.0975 (the gateway's FX_FALLBACK_USD pin, ECB 2026-11-26);
  runtime value set via FX_POLICY_EUR_USD.
- Email now says live billing is unaffected by conversion and points at the
  stale artifacts (config fallback, ops pricing tables, fx_state.json).
2026-11-27 17:58:01 +00:00
inference-bot a3bfc56b77 manifest: pin to 20261124-c174cba
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-24 19:50:16 +00:00
inference-bot c174cba5ce Merge pull request 'membership events: durable lapse/reactivation log' (#11) from feat/membership-events into main
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-24 19:49:10 +00:00
inference-bot b3de608170 membership events: durable lapse/reactivation log
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-24 19:41:00 +00:00
inference-admin f1ba9d7313 manifest: pin to 20261123-419b1f4
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-23 14:27:14 +00:00
inference-admin 419b1f4322 matrix sync: skip a member's remaining rooms after a transport error
ci/woodpecker/push/woodpecker Pipeline was canceled
An unreachable remote homeserver hangs every invite POST to that member until
the client timeout (8 rooms x 30s), which outlived the 5-minute service-sync
tick and starved every member queued behind it. Raise a member-scoped
_TransportError instead of returning False, skip that member's remaining rooms
for this pass, and report transport_skipped in the result. Invites stay
idempotent, so the next pass retries.

Test: a timed-out member is attempted once, not once per room.
2026-11-23 14:26:03 +00:00
inference-bot d190aa7762 manifest: pin to 20261123-db0c09e
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-23 03:36:33 +00:00
inference-bot db0c09e85d orders: docstring matches the paginated read (no fixed window) 2026-11-23 03:36:33 +00:00
inference-bot 3ccaf0ec85 manifest: pin to 20261123-c60dc2c
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-23 03:34:55 +00:00
inference-bot c60dc2c482 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".
2026-11-23 03:34:49 +00:00
inference-admin f09bec67d8 Merge pull request 'Loomio sync: a stamp must not outlive the membership' (#9) from loomio-reconcile into main
ci/woodpecker/push/woodpecker Pipeline failed
Reviewed-on: #9
2026-11-22 19:47:22 +00:00
inference-bot ffed06d492 loomio sync: a stamp must not outlive the membership
ci/woodpecker/push/woodpecker Pipeline failed
The invite stamp meant 'handed to Loomio once, EVER', so a member whose
membership was later revoked (a lapse that was reversed) or who deleted
their Loomio account was recorded as invited and never invited again.

- Stamp only the addresses Loomio actually returns in added_emails; an
  address accepted in the payload but not added stays eligible.
- Clear the stamp for an ACTIVE member stamped-but-absent from the live
  roster; the invite itself waits one pass so a single stale page cannot
  become an invite.
- Cap stamp clearing per pass (LOOMIO_RECONCILE_MAX, default 10): more
  stamped-but-absent members means a short roster read, not a mass
  re-invite.
- loomio_opt_out exempts members who deliberately left.
- Username fix falls back to the portal slug when a handle is already
  taken (Loomio handles are instance-global; every OC alias resolves to
  opencollective).
2026-11-22 19:45:20 +00:00
inference-bot 146bfaf45e manifest: pin to 20261121-b761136
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-21 19:43:12 +00:00
inference-bot b761136dd9 unmapped backers: a plain donation is not a member finding
ci/woodpecker/push/woodpecker Pipeline was canceled
A no-tier BACKER is only a member when it predates the tier system
(LEGACY_NO_TIER_BEFORE). Treating every no-tier BACKER as memberish made
the $75 Workers.VC donation mail info@ as a paid contributor with no
account. Mirror fetch_members() exactly; donations stay silent, and only
unattached credit packs keep the hold-and-notify path.
2026-11-21 19:42:36 +00:00
inference-bot ac39740acb manifest: pin to 20261121-a4b6aa5
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-21 18:20:40 +00:00
inference-bot a4b6aa5357 matrix sync: a transport error on one invite must not abort the pass
An httpx.ReadTimeout during an invite POST raised out of sync_matrix_space,
so every member after the timed-out one got nothing and the service-sync log
said only 'Matrix sync failed:' (httpx transport exceptions stringify to '').
One new member sat uninvited for a day that way.

- invite(): catch httpx.HTTPError per member/room, log the type, return False
- pass counts only members whose invite actually returned True
- room-membership snapshot, the retire half and the Cloudron users walk no
  longer abort on a transport error; the unreadable room/member is skipped
- service-sync now logs the exception TYPE (empty str(e) hid the cause)

Regression in tests/test_service_invites.py section 7: a timed-out member does
not stop the member after them, and the next pass retries them.
2026-11-21 18:20:00 +00:00
inference-admin d7c812ba07 manifest: pin to 20261120-34f2eed
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 20:08:53 +00:00
inference-admin 34f2eeddd7 security: reject hostile tokens cleanly and record webhook sources
secrets.compare_digest raises TypeError on str containing non-ASCII, so a
webhook path token or header token with one answered 503/500 instead of
401/403 — a scanner manufactured a false money-critical alert on 2026-11-20.
Compare UTF-8 bytes through _secret_eq and fail closed on empty.

webhook_failures now stores ip and user_agent; the sweep email names each
source and distinguishes a probe from an Open Collective delivery.
2026-11-20 20:08:12 +00:00
inference-admin 347f2cf720 manifest: pin to 20261120-3c36bdf
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 10:02:37 +00:00
inference-admin 3c36bdf2a9 security: cap MXID verification DMs per member per day
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-20 10:01:47 +00:00
inference-admin 3ed4d75898 manifest: pin to 20261119-637a8ae
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 00:19:35 +00:00
inference-admin 637a8aed13 security: require timestamped HMAC on the key feed when configured
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-20 00:18:43 +00:00
inference-admin f24f0c32f4 security: CODEOWNERS for CI config
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 00:15:12 +00:00
inference-admin 66b765d81d manifest: pin to 20261119-504200e
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 00:08:44 +00:00
inference-admin 504200e011 security: queue Matrix invites after MXID verification instead of blocking the request
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 00:06:37 +00:00
inference-admin f39a84ac14 manifest: pin to registry.inference.coop/code/member-portal:20261119-dc7c381
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 00:02:45 +00:00
inference-admin dc7c381bd8 security: verify control of external MXIDs before inviting (one-time Matrix DM code)
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-20 00:01:23 +00:00
inference-admin 96c0866c67 manifest: pin to registry.inference.coop/code/member-portal:20261119-3a2d608
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:45:05 +00:00
inference-admin 3a2d6088f2 security: expose MXID change date to the admin panel
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:44:10 +00:00
inference-admin c57dbdb62e tests: cover switch-group path in guest cancel
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:41:15 +00:00
inference-admin ac2ba4d2c1 manifest: pin to 20261119-a215b5f
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:35:21 +00:00
inference-admin a215b5f9c9 security: bound MXID changes, preserve Cloudron groups, refuse guest invites onto existing accounts, legacy no-tier cutoff, internal-only key feed
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:33:24 +00:00
inference-admin 4554bf3251 manifest: pin to 20261119-89e5ae6
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:26:25 +00:00
inference-admin 89e5ae6273 webhook: refuse an unresolvable order.processed instead of answering provisioned
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-19 23:25:39 +00:00
inference-admin 90b94904e8 manifest: pin to 20261119-c9726f4
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:23:52 +00:00
inference-admin c9726f4029 security: verify OC orders, fail-closed revoke, per-IP rate buckets, escaped guest email
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 23:22:51 +00:00
inference-admin 5a0a3decbe manifest: pin to 20261119-59d228b
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 22:45:32 +00:00
inference-admin 59d228b8d3 retire Open WebUI: drop rag_refresh job and its credentials; keep LibreChat path
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-19 22:44:49 +00:00
inference-admin 816494aee0 manifest: pin to 20261119-5f3519d
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 22:40:09 +00:00
inference-admin 5f3519d0af security: retire the legacy /v1/* key-injection proxy and PORTAL_SECRET
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 22:39:14 +00:00
inference-admin 1ea7cfc773 manifest: pin to 20261119-649392d
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 22:11:51 +00:00
inference-admin 649392d2e8 security: constant-time admin-token compare on four routes; legacy token off by default
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-19 22:09:38 +00:00
inference-admin 1f1d555125 manifest: pin to 20261118-4af22ca
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-18 17:44:49 +00:00
inference-admin 4af22ca4c4 portal: daily EUR/USD spot check against the pricing FX, alert only (no reprice)
ci/woodpecker/push/woodpecker Pipeline was canceled
Reads the ECB reference rate in the sweep, compares to FX_POLICY_EUR_USD (1.16),
and emails info@ only when the drift first crosses FX_ALERT_PCT (2%). Marker in
portal_state keeps a steady breach from mailing daily and resets when inside the band.
2026-11-18 17:44:00 +00:00
inference-admin 6b46dfee90 manifest: pin to 20261117-e4d9d7b
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-17 16:14:11 +00:00
inference-admin e4d9d7bf49 portal: stale-invite sweep skips addresses emailed in the last hour
ci/woodpecker/push/woodpecker Pipeline was canceled
An explicit resend followed by the sweep sent the same guest two identical invites.
2026-11-17 16:13:49 +00:00
inference-admin cddab4d759 manifest: pin to 20261117-0ae9634
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-17 16:13:02 +00:00
inference-admin 0ae9634f70 portal: setup links expire after seven days — say so, and offer a resend
ci/woodpecker/push/woodpecker Pipeline was canceled
Cloudron's account-setup links lapse after a week, so an unaccepted invitation goes
stale through no fault of the member. Both setup emails now state the lifetime and
where to ask for a new link. New admin routes: resend one invite (fresh link, never
to an activated account) and resend every unaccepted guest invite older than N days.
2026-11-17 16:12:40 +00:00
inference-admin e6db73c6bb manifest: pin to 20261117-58b9a52
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-17 16:12:00 +00:00
inference-admin 58b9a52e01 manifest: pin to 20261117-9023496
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-17 09:17:59 +00:00
inference-admin 9023496e94 portal: dues sum stacked subscriptions and record for manual members
ci/woodpecker/push/woodpecker Pipeline was canceled
_current_dues took only the newest live order, so evan-prodromou's $5 + $10 monthly
subscriptions displayed as $5. Sum per unit (monthly separate from yearly), never
mixing them. Also snapshot dues BEFORE the manual skip: manual members take no
membership decision, but the panel's Dues column is a read-model of OC truth and
was unreachable for them.
2026-11-17 09:17:37 +00:00
inference-admin 549a86a48c manifest: pin to 20261117-f7f6946
ci/woodpecker/push/woodpecker Pipeline failed
2026-11-17 09:09:26 +00:00
inference-admin f7f6946207 portal: dues = the co-op's share, not the donor's OC total
ci/woodpecker/push/woodpecker Pipeline was canceled
totalAmount includes the buyer's optional Open Collective tip, so a member who tips
showed a higher dues level than they pay us. Use amount.value — the base
contribution that reaches the co-op — and fetch it alongside totalAmount. The
webhook credit-pack path made this same mistake and already resolves it via the
public order API.
2026-11-17 09:08:58 +00:00
inference-bot a814a5f7f9 manifest: pin to 20261117-a135560
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 09:02:55 +00:00
inference-bot a135560899 portal: persist each member's current OC dues level
reconcile_allowances already matches every member's Open Collective orders;
it now records what those orders say the member currently pays:
dues_amount / dues_frequency / dues_updated_at (added via the lazy ALTER
pattern). Only a LIVE recurring order (MONTHLY/YEARLY, ACTIVE/PROCESSING)
counts — one-time orders are credit purchases, cancelled/errored ones are not
a current level, and anything unreadable is NULL rather than a guessed tier.

/admin/overview carries the three fields so the admin panel can show a real
Dues column instead of a credit figure. The write happens in report mode too:
it records OC's own truth and makes no membership decision.

tests/test_dues_level.py pins the extraction rules.
2026-11-17 09:02:22 +00:00
inference-admin 1216d9a873 manifest: pin to 20261117-9b90f89
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 08:14:29 +00:00
inference-admin 9b90f89135 portal: stray-credit email states the real floor — from $5/month, no suggested level
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-17 08:14:05 +00:00
inference-admin 78bd79a933 manifest: pin to 20261117-d941961
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 08:07:29 +00:00
inference-admin d941961549 portal: stop telling stray-credit buyers the floor is $10
ci/woodpecker/push/woodpecker Pipeline was canceled
mmoya traced the false '$10 floor' to the stray-credit email: it said '($10-20/month,
sliding scale)' when Open Collective's flexible tier starts at $5 (suggested $10).
Copy now says 'from $5/month, suggested $10 — sliding scale'.
2026-11-17 08:07:01 +00:00
inference-admin 422bb1862a manifest: pin to 20261117-ea0f728
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 05:11:44 +00:00
inference-admin ea0f728af2 portal: member_aliases — credit a purchase made from a member's second OC profile
ci/woodpecker/push/woodpecker Pipeline was canceled
A person can hold two Open Collective profiles, one hiding its email. Purchases from
the hidden one have no email to match and no primary slug, so they land in held
credits. member_aliases maps extra slugs to a member email; the sweep's held-credit
pass resolves email -> slug -> alias before holding anything. Admin GET/POST
/admin/aliases manages rows; test covers grant and idempotency.
2026-11-17 05:11:16 +00:00
inference-admin d51fa55a1d manifest: pin to 20261117-ffe62d3
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 05:05:25 +00:00
inference-admin ffe62d3c78 portal: derive source from OC email visibility instead of trusting a stale flag
ci/woodpecker/push/woodpecker Pipeline was canceled
oc-incognito disables email matching by design, so a profile that later shows an
email leaves the member silently unmatched. The sweep now flips those to oc and
records oc_email; profiles still hiding an email are untouched. Test covers both.
2026-11-17 05:04:50 +00:00
inference-admin 35735d67a5 manifest: pin to 20261117-af4135a
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-17 05:04:19 +00:00
inference-admin af4135ac36 manifest: pin to 20261117-85e8e62
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 04:57:18 +00:00
inference-admin 85e8e62e5b portal: membership-status reports the computed allowance, not members.balance (often NULL)
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-17 04:56:58 +00:00
inference-admin 265fae993f manifest: pin to 20261117-27b0ea5
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 04:56:13 +00:00
inference-admin 27b0ea564a portal: answer for a lapsed membership instead of leaving the dashboard blank
ci/woodpecker/push/woodpecker Pipeline was canceled
New read-only /broker/membership-status, authenticated by the broker secret with a
verifier that admits a member row in ANY state (usage and keys still require active).
Returns active/state, the latest allowance_log decision with its evidence, the OC
minimum contribution (MIN_CONTRIBUTION, copy-only — OC stays the authority), credits,
allowance and the contribute URL.

MIN_CONTRIBUTION is deliberately NOT wired into deactivation: a number we half-know
should not cost anyone access.
2026-11-17 04:55:34 +00:00
inference-admin 6041c0cdb2 manifest: pin to 20261117-e9d0fd2
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-17 04:52:08 +00:00
inference-admin e9d0fd259a portal: settle held credits in the sweep, and report the ones nobody can be credited for
ci/woodpecker/push/woodpecker Pipeline was canceled
A credit pack bought while the buyer's membership was inactive is held — correctly,
we must never mint credits for a non-member. The gap was what happened next: the hold
sat until a human noticed (mmoya's $10 waited from 01:45 until they wrote in).

Every sweep now grants any hold that resolves to an ACTIVE member (by email first, then
slug), reusing grant_held_credits() so held:<id> keeps it idempotent; holds with no
active member older than HELD_ALERT_HOURS are emailed to info@. Tests cover grant/hold/
no-double-apply.
2026-11-17 04:51:40 +00:00
inference-admin 34547075cf manifest: pin to 20261113-bed7f03
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:46:23 +00:00
inference-admin bed7f03063 rate limits: one bucket per ROUTE, not one per proxy address
ci/woodpecker/push/woodpecker Pipeline was canceled
Every request arrives through Cloudrons
2026-11-13 22:45:48 +00:00
inference-admin 6f6261eb1f manifest: pin to 20261113-0a6939f
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:33:35 +00:00
inference-admin 0a6939fe07 retire the Open WebUI integration
ci/woodpecker/push/woodpecker Pipeline was canceled
The app is stopped (`com.openwebui.cloudronapp`, installed|stopped), so every call
to it failed with "Temporary failure in name resolution" — a stopped container has
no DNS entry. Four of the last four provisions logged exactly that; no new member
ever reached the group.

Its "members group" was never a Cloudron group: the id pointed at a group inside
Open WebUI's own database, which is why it appears nowhere in Cloudron's UI.

Removed: owui_add_to_members_group, both call sites (provision_member and guest
convert), the OWUI_* constants, and the signed-JWT identity path in inject_key.
That last one is the part that matters beyond tidiness: it accepted a
shared-secret-signed token as proof of identity for an integration nobody runs.
inject_key keeps its one live path (LibreChat: X-User-Email + X-Portal-Secret,
still verified).

First attempt at this cut too much — a greedy splice off the guest-convert call
took listmonk_sync and the held-credit grant with it, and test_guest_lifecycle.py
caught it before anything shipped. Redone with exact anchors.
2026-11-13 22:33:10 +00:00
inference-admin 5c494cb261 manifest: pin to 20261113-b1022eb
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:28:15 +00:00
inference-admin b1022eb02a oc-incognito: take the slug from the member's own row
ci/woodpecker/push/woodpecker Pipeline was canceled
Setting the source was not enough, and verification is what caught it: mmoya still
produced no allowance decision at all.

The reconciler gets a member's OC slug from the member INDEX — which is keyed by
email, and DROPS anyone whose profile hides its email. So `oc_slug` came back
empty, the member fell into "not in the live Open Collective member list — cannot
verify payment", and was counted as skipped. An oc-incognito member would have
been "not manual" and still not reconciled: a nicer label over the same hole.

For source oc-incognito the slug now comes from the member's own row, which is
the same key fetch_member_orders() groups orders by — the whole reason matching
can work for these people. The test pins the fallback, not just the source.
2026-11-13 22:27:55 +00:00
inference-admin 66a770ae10 manifest: pin to 20261113-64d1ea5
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:25:07 +00:00
inference-admin 64d1ea5093 members: an explicit SOURCE, so 'oc-incognito' stops being 'manual'
ci/woodpecker/push/woodpecker Pipeline was canceled
mmoya@mmoya.org sat in MANUAL_MEMBERS because OC hides the address on their
profile (incognito-5ad60182, email null since 2023), so email matching can never
find them. But "manual" means hand-provisioned, and the sweep SKIPS manual
members entirely: a paying subscriber had no lapse logic, no dues tracking and no
order attribution. Two different facts were sharing one word.

members.source now carries which one it is:
  oc            — OC-backed, matched by email (the default; NULL means this)
  oc-incognito  — OC-backed, profile hides the email, matched by the stored OC
                  SLUG — which the reconciliation already uses, since
                  fetch_member_orders() groups orders by the payer's slug and
                  members.slug holds exactly that for these people
  manual        — hand-provisioned; no contribution expected, nothing reconciles,
                  nobody lapses

So an oc-incognito member needs no exemption from reconciliation — they need to
stop being skipped, and the existing slug path does the rest.

Every decision that keyed on the raw MANUAL_MEMBERS list now keys on the source:
the reconciliation skip, the sweep's deactivation guard, and the shortfall-credit
exemption. An explicit source beats the list, so a member can be moved without
editing the env — and the env list can shrink toward deprecation. An
unrecognised or unreadable source falls back to 'oc', the direction that keeps
reconciling someone rather than quietly exempting them.

anchor_day_for_member also resolves by slug now: an incognito member is absent
from the member index (it drops anyone without an email), and falling back to
"today" would silently move their renewal day.

tests/test_oc_incognito.py pins all of it, including that the column is optional
(NULL = not stated) so this ships without a data migration.
2026-11-13 22:24:46 +00:00
inference-admin a98db6e36e manifest: pin to 20261113-2cde368
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:14:59 +00:00
inference-admin 2cde368c1e resolve payer: authenticate the lookup — without the token OC hides the email
ci/woodpecker/push/woodpecker Pipeline was canceled
Second live-only bug in the same helper. Sent unauthenticated, OC answers the
public view of an account: name comes back, email does not. A hand query with the
Personal-Token header returned conor.canaday@gmail.com for the very slug the
helper reported as email=None — so the fix would have resolved nobody, silently,
while looking like it worked.

The test now pins the header (the stub records what it was called with), because
the failure mode here is an absence, and an absence is exactly what a stub
forgets to check.
2026-11-13 22:14:36 +00:00
inference-admin 0458e8e5a5 manifest: pin to 20261113-9c10e62
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:13:50 +00:00
inference-admin 9c10e627fc resolve payer: read the response's JSON (the stub hid this)
ci/woodpecker/push/woodpecker Pipeline was canceled
_oc_graphql_post returns the RESPONSE — it is a retrying wrapper around
client.post — so fetch_account_by_slug has to call .json() on it. My unit test
stubbed it as a dict, so the test passed and the first live call in the container
died with "Response object has no attribute get".

The test now stubs the real shape (a response wrapper with .json()). Folding it
in here rather than hiding it: a stub that does not match the real return shape
certifies nothing.
2026-11-13 22:13:22 +00:00
inference-admin cbf5a6870b manifest: pin to 20261113-5a73806
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 22:12:24 +00:00
inference-admin 5a7380686c webhook: a first-time contributor's order must not vanish in silence
ci/woodpecker/push/woodpecker Pipeline was canceled
On 2026-11-13 21:59:43 Open Collective delivered order.processed for a live
$5/month membership (Conor W, conor.canaday@gmail.com, order
or_eU8gRkrPCvFsaYHrgiCfz). The portal answered 200 and did nothing.

The membership branch resolves the payer by SLUG against the collective's
members list:

    members = await fetch_members()
    member = next((m for m in members if m["slug"] == slug), None)

and a first-time contributor's account is not in that list yet — OC reports the
payer as guest-…/incognito-…. So `member` was None, the branch fell through, and
because the delivery had SUCCEEDED there was no error to record either: no
account, no welcome email, no credit, no log line. The sweep's unmapped-backers
check found it hours later, which is the wrong place to find it.

Now an unknown payer is resolved from the order's account slug
(`Individual.email`, which OC exposes for an ordinary guest checkout) and handed
to the same provisioning path a known member gets. When even that yields no
email — an incognito profile, hidden on purpose — the webhook logs at ERROR that
nobody was provisioned or credited, instead of shrugging.

The defect worth naming is the SHAPE: an `if` with no `else` on a money path,
where doing nothing leaves no trace. tests/test_resolve_payer.py pins the
resolution cases (guest with email, incognito, unknown account, read failure, no
token) and the fact that the branch can no longer fall through quietly.
2026-11-13 22:12:02 +00:00
inference-admin 27929987b2 manifest: pin to 20261113-241ac80
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 21:53:53 +00:00
inference-admin 241ac800c6 panel state: a reminder is history, not a state — renewals clear grace, grace expires
ci/woodpecker/push/woodpecker Pipeline was canceled
mark@ofosos.org showed as in grace while his contribution was live. The sweep's
own trail says it plainly: reminded 2026-11-04 for the cycle that looked unpaid,
grace elapsed 2026-11-11, and `renewed` logged at 19:02 on 2026-11-13 (last
charge 2026-11-11, next reset 2026-11-26). The panel said grace anyway, because
member_membership_state() asked only "is there a row in payment_reminders?".

That table is a HISTORY — kept so the sweep does not re-remind inside a cycle. It
is not a state, and treating it as one broke two things: a reminder never
expired (grace is PAYMENT_GRACE_DAYS long), and a renewal never cleared it.

Now the LATEST reconciliation decision decides:
  renewed / would_renew            -> active (they are paying)
  reminder inside the window       -> in_grace
  reminder past the window         -> awaiting_contribution, saying grace elapsed
  would_deactivate / deactivated   -> awaiting_contribution
Ordered by decided_at, not id: the same member had id 2296 dated 2026-11-11 next
to id 2286 dated 2026-11-13, so "latest by id" reads the wrong decision.

Reads still fail safe: an unreadable DB reports active, never a payment problem.

tests/test_membership_state.py pins all of it, including the ordering trap.
2026-11-13 21:53:27 +00:00
inference-admin b1f5a30272 manifest: pin to 20261113-2a77b0c
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 21:44:46 +00:00
inference-admin 2a77b0c988 spend: ONE all-time figure, computed once, for every surface that shows it
ci/woodpecker/push/woodpecker Pipeline was canceled
The panel's card said $941.37 and the member dashboard's said $900.51 for the
same claim. The panel used its own per-team query; the dashboard summed the
chart series IN THE BROWSER, which disagrees with the server whenever a row is
null, capped or stale.

coop_spend_totals() is now the definition: one GROUP BY over SpendLogs joined to
the team table, so
  spend_all_time      = every row (members, operators, agent teams, sandboxes) —
                        the same universe litellm_spend_by_day() sums, so the
                        cards and the money chart agree by construction
  own_all_time_spend  = the part that is the co-op's own (non-member teams, plus
                        rows with no team)
and member_all_time_spend = the rest. Exposed through /admin/overview (the
panel's boot payload), the money payload, and /broker/metrics (the dashboard's).
_coop_spend_totals_safe() returns {} rather than a zero: a failed computation
must never read as "the co-op has spent nothing".

tests/test_coop_spend_totals.py pins the arithmetic (total == member + own ==
every row) and the no-fake-zero rule.
2026-11-13 21:44:13 +00:00
inference-admin e15a01c338 manifest: pin to member-portal:20261113-9af0604
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 21:02:57 +00:00
inference-admin 9af0604f47 portal: /broker/money-series, so members chart the co-op's money beside its other charts
ci/woodpecker/push/woodpecker Pipeline was successful
The member dashboard could not show the money chart because the broker exposed no
money series — the same payload /admin/money-series serves the panel is aggregate
and carries no member identities (cumulative revenue, cumulative token spend, the
OC balance), so it goes through the broker for the same reason /broker/metrics
does. One chart definition, drawn identically for members and stewards.
2026-11-13 21:01:38 +00:00
inference-admin 0d5ffede05 README: the spend check compares day by day over the shared window
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:48:02 +00:00
inference-admin b30e2c8080 manifest: pin to 20261113-c92d897
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:47:23 +00:00
inference-admin c92d8979eb spend check: compare like for like (same window, same kind of number)
ci/woodpecker/push/woodpecker Pipeline was canceled
The second live run FAILED again, correctly and informatively: portal $935.52
all-time vs LiteLLM $827.89 — and the $107.63 'drift' was the WINDOW. LiteLLM's
per-day view reaches back a fixed number of days (31 on 2026-11-13); our table
holds 69. Over the days both sides cover the two agree to $0.07, with no day
differing by more than $0.022 (the API rounds to cents).

So the check now compares DAY BY DAY over the shared window, which localises drift
instead of hiding it in a sum, with a per-day tolerance ($0.10) plus a window-total
tolerance ($5). It reads /global/spend/teams rather than /global/spend/keys: the
per-key figure follows each key's own budget cycle, so summing it is not an all-time
number at all (and /global/spend/report, the all-time one, is Enterprise-gated).

Degenerate reads are judged BEFORE the window overlap, because in the failure this
check exists for the portal's aggregate comes back EMPTY — there would be no shared
days to compare, and the overlap logic would report 'cannot compare' instead of the
stale-credential signature. All failure reporting goes through one helper that mails
info@ once per episode and advances the marker only after a notice is sent.

23 checks; all 20 suites green.
2026-11-13 20:46:50 +00:00
inference-admin c13880cfab manifest: pin to 20261113-c0ef046
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:44:16 +00:00
inference-admin c0ef046b0d spend check: read the field LiteLLM actually sends (total_spend), and fail loudly either way
ci/woodpecker/push/woodpecker Pipeline was canceled
The first live run FAILED with api $0.00 over 306 keys against the portal's $935.35.
The disagreement was real, the verdict was right, and the cause was mine: LiteLLM's
/global/spend/keys returns each key's all-time spend as `total_spend`, not `spend`.
A checker that trusts its own parse then reports "the portal is wrong" — the exact
mirror of the failure this check exists to catch, which is why the guard now names
both possibilities when the independent side reads zero against real portal spend.

Parser accepts either field name; a regression test exercises the real function
against a stubbed httpx (the module attribute is stubbed for the other checks, so
the real one is captured at import). 24 checks; all 20 suites green.
2026-11-13 20:43:41 +00:00
inference-admin 1c1fced5ba manifest: pin to 20261113-e2eaa7a
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:42:11 +00:00
inference-admin dac8f2c9ea README: the spend-consistency step
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-13 20:41:58 +00:00
inference-admin e2eaa7ae40 spend consistency: the check moves into the portal's sweep
ci/woodpecker/push/woodpecker Pipeline was canceled
The failure this exists for (2026-11-05): the portal's own all-time-spend aggregate
failed SOFT when its copy of the gateway's LiteLLM DB credential went stale — the
query returned nothing, every surface showed $0, and nothing looked wrong, because
the portal WAS the thing that was wrong. The guard ran as a daily script on the
bot's host.

It now runs in the portal, and keeps two genuinely independent reads: the portal's
SpendLogs aggregate over its own DB credential, and LiteLLM's own HTTP API
(/global/spend/keys) over the master key — a different transport AND a different
credential, which is the point, since the DB copy is what goes stale.

It adds the signature guard the host script could only infer from outside: an
EMPTY//usr/bin/bash portal aggregate while LiteLLM reports real spend is a FAILURE, named as
the stale-credential case; an API side that returns no keys is a failure too, not
agreement. A read that cannot be made is skipped — never a clean bill. Silent when
they agree; info@ once per failing episode, marker cleared on recovery.
POST /admin/spend-check runs it on demand. 23 checks; all 20 suites green.
2026-11-13 20:41:27 +00:00
inference-admin bb0a02dcd9 manifest: pin to 20261113-bf1e5f0
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:36:39 +00:00
inference-admin 06e7ae0ea5 README: the unmapped-backer step and the notice policy
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:35:42 +00:00
inference-admin bf1e5f013b unmapped backers: stop the phantom finding (the members query had no createdAt)
ci/woodpecker/push/woodpecker Pipeline was canceled
The first production run reported a null-account node as an uncredited payer. The
cause was in my port, not the data: the members query selected id-less,
date-less nodes, so every null-account node fell into the date "" bucket, matched
no same-day order, and was reported as unattributable — while the host-side script
(correctly) said clean.

Two fixes: select id + createdAt in fetch_all_member_nodes, and never emit a
null-account finding when the node carries no date — there is nothing to attribute
it against, and guessing is what produced the phantom. 27 checks in the suite.
2026-11-13 20:35:28 +00:00
inference-admin 13b6131652 notices: tell a human about what is NEW, and only when a notice actually went out
ci/woodpecker/push/woodpecker Pipeline was successful
Three fixes to the 'email only when there is a problem' rule, found by testing it:

1. The marker recorded the CURRENT set, so a set that SHRANK looked changed — one
   purchase granted dropped out, the remaining hold looked new, and it was mailed
   about twice. What a human has been TOLD is now a growing SET of keys
   (order:grant / order:hold, slug:class for backers): only keys not in it are
   mailed, and the union is stored.
2. A notify=False run advanced the marker, so a verification look CONSUMED the
   only alert a finding gets. The marker now advances only when the notice was
   actually sent (a failed send retries next sweep), and a clean pass clears it so
   a recurrence is news again.
3. The credit reconcile had the same shape of bug.

Tests updated to pin the new semantics: a smaller set re-mails nobody, a silent
look does not swallow the alert, a clean run clears the marker and a recurrence
speaks. 26 + 40 checks in those suites; all 19 suites green.
2026-11-13 20:34:24 +00:00
inference-admin f258a22aa3 manifest: pin to 20261113-eaaabf3
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:31:22 +00:00
inference-admin eaaabf3763 unmapped backers: the paid-but-unprovisioned net moves into the portal
ci/woodpecker/push/woodpecker Pipeline was canceled
A contributor who pays and never gets an account is invisible to the sweep —
fetch_members() drops every member node with no email, and an OC Organization
never exposes one — so they wait until they ask (the mmoya case). The net for them
was a daily script on the bot's host driving `cloudron exec` from outside. The
portal holds both sides of that comparison, so it now owns it.

reconcile_unmapped_backers() runs in the sweep and reports three classes, because
each needs a different human action: an org account (link it), a VISIBLE email
(the sweep should have provisioned this — check the token/sweep), and a hidden
email (fetch it out-of-band). A node with no account object is attributed through
same-day current orders, and stays silent when every same-day payer is mapped.

MAIL POLICY (ntnsndr, 2026-11-13): only when there is a problem — and only when
the finding SET changes, fingerprinted in portal_state (slug+class only, never an
email), so a stuck finding does not mail three times a day while a fresh one
always speaks. A clean run clears the marker. A failed read returns skipped,
never a clean bill.

POST /admin/unmapped-check (X-Admin-Token, ?notify=0 to stay quiet). The
credit-pack reconcile now mails on the same rule. 25 checks; all 19 suites green.
2026-11-13 20:30:46 +00:00
inference-admin d117da3dc6 README: the sweep's webhook-failure report, and why the scraper is gone
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:25:51 +00:00
inference-admin 9f7934121f manifest: pin to 20261113-2e40387
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-13 20:25:18 +00:00
inference-admin 2e40387245 webhook failures: the portal records and reports its own, not a scraper on my host
ci/woodpecker/push/woodpecker Pipeline was successful
The alert for a failed Open Collective delivery lived in portal_webhook_watch.py on
the operator's machine, polling this app's log through the Cloudron API. That put a
money-critical signal outside the system, and on a log buffer with only hours of
memory — during the 2026-11-13 investigation whole hours (06:00-13:00, 15:00) were
simply absent, so 'no failed delivery in the log' could not be distinguished from
'no delivery at all'.

The portal handles every delivery, so the portal now knows: a new webhook_failures
table records every non-2xx (including the 401 that means the URL and WEBHOOK_TOKEN
disagree, whose event type is read from a body cached before the token check), and
webhook_failure_report() in the sweep emails info@ ONCE per new batch via a marker
in the new portal_state table, so a wrong token does not mail every sweep while the
rows stay queryable. The delivery path is unchanged: bookkeeping failures are
logged, never raised, and the response stays 401/503.

19 checks in test_webhook_resilience.py; all 18 suites green.
2026-11-13 20:23:33 +00:00
inference-admin 6c82d7d689 manifest: pin to 20261113-c174fa2
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:21:22 +00:00
inference-admin c174fa2ffe reconcile: link a row to its member by slug OR email
ci/woodpecker/push/woodpecker Pipeline was successful
Both routes are needed. A manual grant often carries no reference at all, so the
row's EMAIL is the only link to its member — and the slug and email local part
routinely differ ('henry-smith' vs 'h.smith@x.org'). The membership test was
slug-first and, when the slug matched neither the reference nor the email, dropped
the row outright: a hand-credited purchase therefore reads as a gap (ntnsndr's
2026-09-28 packs, where the ledger carries +20.00, +5.75 and a -10.75 correction
with no references). _row_belongs_to() accepts either route, in both the
accounted-for test and the nearby-rows context. 38 checks; all 18 suites green.
2026-11-13 20:20:40 +00:00
inference-admin 711371f9d7 manifest: pin to 20261113-f2b6153
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:19:17 +00:00
inference-admin f2b6153aa6 reconcile: show a candidate's nearby ledger rows, so a manual grant isn't read as a gap
ci/woodpecker/push/woodpecker Pipeline was canceled
Widening the window to OC's whole order history found three $5 packs from
2026-09-28 reported as uncredited — ntnsndr's launch-day purchases, which WERE
credited by hand that morning: +20.00, +5.75, then a -10.75 correction ('true
contributions were 3 x $5.00'), netting exactly $15, with no per-order reference
on any row.

credit_pack_accounted() is right not to infer 'accounted for' from a nearby
amount — that would hide genuine gaps — but a reviewer could not tell the two
cases apart from the candidate alone. Each candidate now carries its nearby
ledger/held rows (7-day window, capped at 5) and the report-mode log line prints
them, so a manual grant explains itself. Nothing about the decision changes.

36 checks; all 18 suites green.
2026-11-13 20:18:44 +00:00
inference-admin d69c518b47 manifest: pin to 20261113-5868ca8
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:16:34 +00:00
inference-admin 5868ca82e8 reconcile paid credit packs against the ledger, report-first (issue #7)
ci/woodpecker/push/woodpecker Pipeline was canceled
Credits have one path in: the OC order.processed webhook. On 2026-11-13 two paid
packs got nothing through it — a $50 whose delivery 500'd on httpx's 5s default,
and a $10 with no delivery in the retained log at all — and nothing on a
schedule noticed. This adds a pass that reads OC's own order list and compares it
with our books over a day-based window (not "whatever the log still holds": the
$10 gap was 11h old and the log had lost the whole morning).

Report-first: CREDIT_RECONCILE defaults to 'report' (log findings, change
nothing) and grants only when set to 'on'. Grants go through add_credits() with
credit_pack_reference(), the same per-order key the webhook writes, so a late
delivery and this pass are idempotent against each other in both directions. A
buyer with no active membership is reported, never credited — those keep the
hold-and-email path.

credit_pack_accounted() encodes what our own rows actually look like: a v2 id, a
hyphenated legacy id, an empty-suffix legacy reference, and held_credits rows. A
bare oc:<slug>:<order.id> match read 21 credited purchases as missing during
development, so the fallback demands a second signal (member + tip-free amount +
date) before calling an order credited.

POST /admin/credit-pack-reconcile (X-Admin-Token) runs it on demand, dry unless
?apply=1 and the policy is on. 33 new checks; all 18 suites green.
2026-11-13 20:16:24 +00:00
inference-admin 32e744d9ee README: document the webhook error net, the OC timeouts, and the missing reconciliation
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 20:05:23 +00:00
inference-admin 9c53e5e727 manifest: pin to 20261113-f45e4ef
ci/woodpecker/push/woodpecker Pipeline was canceled
2026-11-13 20:04:53 +00:00
inference-admin f45e4ef305 webhook: stop a transient OC read failure from costing a member credits
On 2026-11-13 an `order.processed` delivery for a $50 credit pack returned 500.
fetch_members() -> fetch_all_member_nodes() used a bare httpx.AsyncClient(), so OC
was given httpx's DEFAULT 5-second timeout; the read timed out, httpx.ReadTimeout
escaped the handler as an unhandled ASGI exception, and the purchase was never
credited. The member paid and got nothing, and the log held a stack trace rather
than anything naming the member or the order.

Three changes, each aimed at a different failure:

* fetch_all_member_nodes: an EXPLICIT 30s timeout, and one retry per page on a
  transport error (`_oc_graphql_post`). Still RAISES when it cannot get the full
  list — the sweep's fail-safes depend on that.
* opencollective_webhook: the work moves to _process_opencollective_webhook and a
  thin wrapper answers 503 (retryable) with an ERROR line naming the exception if
  anything unexpected escapes. A 401 stays a 401; that status is the signal that
  the webhook URL and WEBHOOK_TOKEN disagree, and swallowing it would hide a
  misconfigured webhook.
* tests/test_webhook_resilience.py proves it: 401 preserved, 503 (not 500) on a
  simulated ReadTimeout, credits granted exactly once per OC order, an identical
  re-delivery answering already_credited with no money moved, and the retry/raise
  behaviour of the transport helper.
2026-11-13 20:04:09 +00:00
inference-admin 5705d02792 manifest: pin to 20261113-0e825e6
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 17:38:35 +00:00
inference-admin 0e825e6d61 service invites: per-room Matrix gate, resumable rate limits, Loomio record heal, 5-min sync tick
A new member could end up with a Loomio account and a Matrix account and see
NOTHING: no forum group, no Space. Three defects:

* sync_matrix_space() gated each member on the SPACE's membership, so an
  account already joined/invited to the Space was skipped for EVERY room. A
  member whose invite pass was interrupted (or who predates a room added to
  MATRIX_INVITE_ROOMS later) never received that room — and a restricted child
  room is invisible until you are invited to it. The gate is now per room, from
  a single up-front membership snapshot; a room whose membership cannot be read
  is left alone rather than invited into blindly.
* a 429 slept for retry_after_ms (minutes) INSIDE the pass, so a scheduled run
  could outlive its own tick. A rate limit now ENDS the pass; the next run
  resumes (every invite is idempotent).
* a member sitting in the Loomio group with no loomio_invited_at stamp reads as
  'never invited' — the dedupe guard was only as good as the rows it had. The
  sync now heals the record from the live roster.

And the activation window itself: provisioning skips an unactivated account by
design, and activation happens later with nobody watching, so the 3x/day sweep
was the pickup. New /admin/service-sync + a 5-minute scheduler task fires the
same idempotent syncs while any member still awaits an invite (one SELECT when
none do), and deliberately is NOT /admin/sweep — it never touches Open
Collective, allowance logic or member mail.

tests/test_service_invites.py proves the per-room gate, resumable rate limits,
the unreadable-room skip, the record heal and the endpoint's idle/run paths.
2026-11-13 17:37:57 +00:00
inference-bot de0f5c13c4 manifest: pin to 20261113-3c64b15
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 16:12:45 +00:00
inference-bot 3c64b150db broker: per-member daily usage series in /broker/usage (daily: day/spend/requests)
ci/woodpecker/push/woodpecker Pipeline was successful
The member dashboard's usage chart reads per-day spend + requests for the
signed-in member, bounded by the existing days param (0 = all time, the
unchanged default). Same source and day convention as the co-op daily series
(to_char(startTime)); interior zero days are explicit so chart spacing is
true; requests excludes failed attempts; spend sums every row. Additive and
backward compatible: every existing field untouched. Tested in
tests/test_broker_usage_daily.py (route table, SQL shape, fallback twin,
fail-soft degradation).
2026-11-13 16:11:16 +00:00
inference-bot afffd52dec manifest: pin to 20261113-cad5897
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-13 04:04:45 +00:00
inference-bot cad5897e9a metrics: self-heal missing OC balance days from the OC ledger
The 2026-11-12 hole was NOT a missed sample: the 03:15 run recorded
oc_balance_usd=1357.39, and the evening repair backfill's full-row
upsert of the then-current day — whose dict carries no balance key —
nulled it on conflict. Nothing ever revisited a day's balance, so the
hole was permanent.

Two fixes:
- upsert() can no longer erase a balance it did not measure: the
  conflict clause COALESCEs, so a NULL (a failed OC read) keeps the
  previously recorded value.
- the nightly snapshot heals any recent day (within a week, after the
  series' first recorded balance) whose balance is missing: the value is
  reconstructed from Open Collective's transaction ledger
  (balance(cutoff) = current - net flow after the 03:15 sample moment,
  ledger window clamped to the balance read), matching the daily sample
  semantics exactly. It is written balance-column-only, so membership
  and usage series are untouched. Days before 2026-11-08 stay NULL by
  design. Fail-soft: an OC failure prints and retries next night.

The reconstruction was verified to the cent against OC's own ledger:
full-ledger signed sum == stats.balance (1470.44 on 2026-11-13), and
1470.44 - 113.05 (net flow 2026-11-12 03:15 -> 2026-11-13 03:15:58)
== 1357.39, exactly the sample the 03:15 run had recorded.
2026-11-13 04:04:43 +00:00
inference-bot 8405fd9157 manifest: pin to 20261112-cf3dbb7
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-12 18:41:20 +00:00
inference-bot cf3dbb7489 metrics: complete YESTERDAY's row at 03:15 — every day was frozen at its first ~3 hours
ci/woodpecker/push/woodpecker Pipeline was successful
snapshot() fetched the full spend window (since = yesterday) but kept only
spend.get(TODAY): the day's first hours, written at 03:15 and never revisited.
Every metrics_daily row after the last backfill under-counted its day by the
hours after 03:15 (Nov 7 recorded $2.19/691 requests against a true
$29.06/3384). The completed day's aggregates were computed and thrown away.

Now each run completes the day that just ENDED — full-day spend, requests,
tokens and impact, written to the usage columns only (upsert_usage: membership
columns are point-in-time measurements and are never rewritten) — and then
records today's live partial as before.

backfill() gains --since YYYY-MM-DD: a targeted usage-only repair that cannot
touch the published membership curve.

Regression test: tests/test_metrics_completion.py (day completion, membership
preservation, since-mode repair boundaries, full-backfill parity).
2026-11-12 18:40:31 +00:00
inference-bot 022e193cc2 manifest: pin to 20261111-58214be0
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-11 05:16:23 +00:00
inference-bot 58214be0db Guest state: the overview payload carries the definitive display state
Single derivation point (tested once, here): 'invited' while the Cloudron
invite is unaccepted, else the guests-ledger status (the record of record),
membership state only as a no-ledger-row fallback. The panel and dashboard
become pure consumers of `state` — their local invited/active derivation
goes away in their own repos next. Live-behaviour note: today's four live
guests render byte-identically; the change only shows for ended guests
(ledger 'expired' instead of the bare inactive flag), which is what the
panel already displayed via its own guest_status preference.
2026-11-11 05:16:13 +00:00
inference-bot 62a59477c6 ci: Woodpecker pipeline runs the 12 test suites on push (gates merges)
ci/woodpecker/push/woodpecker Pipeline was successful
2026-11-11 03:42:00 +00:00
inference-bot 9494ed6d0c manifest: pin to 20261108-2954fe60 2026-11-08 20:54:35 +00:00
inference-bot 2954fe609f Guest invite: serialize member invites — parallel direct calls can't slip two guests
The one-per-30-days rule is a READ of the guests ledger, provisioning
takes seconds of external calls, and the ledger row that closes the
window is written LAST — so two PARALLEL direct calls (curl, bypassing
the dashboard JS) could both pass guest_request_guard before either row
exists and slip two guests past the rule. The member invite path now
runs guard+provision under _GUEST_INVITE_LOCK (single-process uvicorn),
making check-and-send atomic: the second caller re-runs the guard after
the first caller's ledger row exists and is refused 429.

tests/test_guest_concurrency.py proves both halves on the fixture DB:
unguarded, two parallel invites both provision (the test has teeth);
with the lock, exactly one provisions, one is refused 429, one ledger
row, one account, one email; sequential semantics unchanged.
2026-11-08 20:53:54 +00:00
Inferencebot 1d102a4754 manifest: pin to 20261108-88ca8bf 2026-11-08 20:42:00 +00:00
Inferencebot 88ca8bfe18 Guest state: provisioned-but-not-set-up reads 'invited', never 'active'
A guest invitation provisions immediately, but the Cloudron account is not
ACCEPTED until the guest clicks the setup link (inviteAccepted=false, no
username) — until then they cannot log in, so no surface may read them as
active. guest_invite_pending() derives it from the same Cloudron signal the
overview's activated flag uses; unseen-record (users fetch failed) is never
pending, so the state falls back instead of asserting what the data does
not show.

/admin/overview: guest rows report state='invited' with an 'awaiting
setup' reason (invite date named when the ledger has it); /broker/guests
trail entries carry state='invited' the same way, status stays the ledger
record of record. Display/state semantics only — access rules, the $2 cap
and the expiry box are unchanged.

Tests: new test_guest_invited_state.py (derivation, overview flip,
fetch-failure fallback, member rows untouched, trail state);
test_guest_requests.py gains the trail invited/accepted assertions and a
constructible-but-loud fake client so the stubbed users fetch runs.
2026-11-08 20:40:23 +00:00
inference-bot f592e5b7b5 manifest: pin to 20261108-285aa66 2026-11-08 20:21:53 +00:00
inference-bot 285aa66525 Guest invites provision immediately: remove the member approval gate
Operator decision 2026-11-08: the remaining protections (active member,
1 guest per inviter per rolling 30 days, one guest per recipient ever,
no existing portal row, MANUAL_MEMBERS refusal, the $2 cap and the
GUEST_DAYS box) are sufficient without the approval step.

* POST /broker/guests provisions through provision_guest_member at once —
  no pending state; no guest_requests row is ever written.
* GUEST_AUTO_APPROVE flag removed (the live env never carried it).
* guest_request_guard keeps the member-path rules and drops the
  trial-era pending-request checks; the 30-day window is counted from
  the guests ledger.
* GET /admin/guest-requests + approve/reject removed; GET /admin/guest-ledger
  serves the panel's duplicate-send guard.
* The member trail keeps legacy rejected requests as history only.

Built on the sibling $2-cap commit 6be8e2d.
2026-11-08 20:20:30 +00:00
inference-bot f1a86d9d76 manifest: pin to 20261108-6be8e2d 2026-11-08 20:12:53 +00:00
inference-bot 6be8e2d632 Guest cap $5 -> $2: GUEST_BUDGET default, emails, docs, tests 2026-11-08 20:12:47 +00:00
Inferencebot 0f12c63f5e manifest: pin to 20261108-6f5e479 2026-11-08 05:14:11 +00:00
Inferencebot 6f5e479900 Guest invitation email: drop the renewable-energy claim, state sliding-scale pricing
Operator edits:
- The co-op is described only as a member-governed AI cooperative; the
  renewable-energy claim is removed (not all providers are renewable).
- Membership pitch now states the pricing exactly: pay on a sliding
  scale, $15/month allowance plus optional credit packs, plus a say in
  how it's run.
2026-11-08 05:13:52 +00:00
inference-bot 3493227880 manifest: pin to 20261108-ed50031 2026-11-08 03:12:38 +00:00
inference-bot ed50031663 Admin guest invites: admin inviter, no member cap, no name guessing
The admin panel's /admin/provision-guest now takes ONE field (the guest's
email): no name is collected and none is derived from the email — the
guest chooses their own display name and username during Cloudron account
setup, and the invitation email greets neutrally when no name is known.
The guests ledger records the co-op's ADMIN account (ADMIN_INVITER_EMAIL,
default info@inference.coop) as the inviter. Admin invites provision
immediately (the operator IS the approver) and are not bound by the
member's one-per-30-days cap; recipient-side guards (one guest per
recipient ever, no existing portal row) still run. The member paths
(broker invite, request approval) keep every protection and likewise pass
no derived name.
2026-11-08 02:55:10 +00:00
inference-bot 7a63b3a728 README: document the member self-serve guest flow and the trial gate 2026-11-08 02:53:00 +00:00
inference-bot 6220812e08 manifest: pin to 20261108-0293d66 2026-11-08 02:45:40 +00:00
inference-bot 0293d66c1e Member self-serve guest invitations with a trial approval gate
POST /broker/guests (member broker identity — guests cannot reach it) creates
a guest REQUEST; GET /broker/guests returns the member's invitation allowance
(rolling one-per-30-days, counting pending + approved requests) and their own
guest trail. guest_request_guard enforces every existing protection plus the
member-side ones: recipient never an existing member, a prior guest, a pending
request, or a MANUAL_MEMBERS address; the inviter's window counts requests too.

Trial gate (GUEST_AUTO_APPROVE, default off): requests land PENDING in the new
guest_requests table; the operator approves or rejects them via
GET/POST /admin/guest-requests (X-Admin-Token). Approval fires the full
provision_guest_member pipeline (Cloudron user, $5 credit, GUEST_DAYS box,
invitation email naming the inviter, newsletter, ledger row); a guard refusal
at approve-time is recorded on the request and surfaced. The member sees
pending/not-approved status in their own trail — the recipient is contacted
only on approval. With the flag on, a member's request provisions
immediately, no code change needed.

38-check fixture suite (tests/test_guest_requests.py) proves the gate, every
refusal path, the approve/reject actions and auto-approve with the network
replaced by a raising guard.
2026-11-08 02:42:56 +00:00
inference-bot 93184b6011 Fix the gift→guest rename migration for legacy databases
Two defects found by booting the renamed app against a fixture of the
pre-rename database (the live portal's exact state):

1. members.gift_expires_at: the RENAME above uses the stale
   snapshot, so the plain
   below fired right after a successful rename and crashed boot with
   'duplicate column name' — the portal would have failed its deploy
   health check on the live database. Make the two branches exclusive.

2. The ledger's own expiry column: ALTER TABLE guests RENAME moved the
   table but kept its legacy gift_expires_at column, which the provision
   INSERT (writing guest_expires_at) would fail on at first use. Rename
   the column with the table.

Also moves the credit-ledger dedupe references ('gift:<email>' /
'gift-return:<email>') to their guest prefixes at boot — returns first,
since 'gift-return:…' also matches 'gift:%' — so a re-grant after the
rename cannot double-credit.

Verified: migration harness 10/10 on a legacy-state fixture (renames,
value conversion, ref migration, idempotent second boot, readback
helpers); full portal suite 9/9 files green.
2026-11-08 02:42:53 +00:00
inference-bot 27f9cc06b2 Rename gift to guest throughout: routes, ledger table, account_type values, env names, emails, tests
Pure rename, no behaviour change, matching the renamed panel and dashboard
builds. Includes one-time idempotent migrations for existing databases
(gifts->guests table, gift_expires_at->guest_expires_at column,
account_type 'gift'->'guest' values, gift_lapse_notices->guest_lapse_notices)
and four transitional alias routes (admin/provision-gift, admin/gift-convert,
broker/gift-status, broker/cancel-gift) so pre-rename dashboard/panel builds
keep working until they are redeployed.
2026-11-08 02:41:05 +00:00
inference-bot 8af8e39c0b README: document the gift self-cancel flow and GUESTS_ENDED_GROUP_ID 2026-11-08 02:34:13 +00:00
inference-bot 526d98be17 manifest: pin to 20261108-40fb75a 2026-11-08 02:28:46 +00:00
inference-bot 40fb75a34b gift cancel: self-service cancellation with credit return and full audit trail
POST /broker/cancel-gift (dashboard broker identity, gift accounts only,
idempotent) + GET /broker/gift-status for the ended-state view. Semantics
match the gift lapse: row deactivated, account kept for a clean resume,
gateway budget zeroed, newsletter off — plus the return a lapse does not
do: unspent credit back to the co-op as a NEGATIVE credit_ledger row whose
reason names the cancellation and the original gift reference, deduped on
its own reference. Gifts ledger records inviter → recipient → 'cancelled
by recipient'. The user leaves the guests group for GUESTS_ENDED_GROUP_ID
(dashboard-only visibility for the ended state); the reaching-limits
notice is pre-marked so a self-cancelled guest is never told their
credits were spent. Tests: tests/test_gift_cancel.py (19 fixture checks,
network-guarded).
2026-11-08 02:28:45 +00:00
inference-bot 9c441dc0aa manifest: pin to the tag the builder produced (20261108-022314-976fc18c7) 2026-11-08 02:23:35 +00:00
inference-bot e704123f22 manifest: pin to 20261108-0b0bdaa 2026-11-08 02:23:04 +00:00
inference-bot 0b0bdaab6f gift emails: invitation at gift time + once-only reaching-limits notice
- gift_welcome_email becomes gift_invitation_email: the ONE email a gift
  sends (the invitation and the guest welcome merged, not two mails at
  once). Subject 'You've been invited to the Inference Cooperative'; names
  the inviter (member slug), the $5 credits, the setup link, the
  Become-a-member button on BECOME_MEMBER_URL. Uses the shared
  PINE_LOGO_SVG instead of an inline copy.
- reaching-limits email (gift_limits_email, 'Your guest access has ended —
  become a member to continue') wired into the sweep's gift deactivation:
  sent once per guest, gated by a gift_lapse_notices sent-state row (same
  pattern as mark_shortfall_notice_sent). Says the access ended, the
  account and data are kept, and membership ($15/mo via Open Collective)
  restores a full monthly allowance + community spaces.
- catch-up pass in reconcile_gift_lifecycles: guests deactivated before the
  email shipped (or a failed send) get exactly one notice on a later sweep;
  converted guests are excluded by account_type.
- sweep summary now reports gift_lapse_notices.
- test_gift_lifecycle: invitation-subject assertion; send_email stub
  returns True (the bool is the gate's contract); new once-only + catch-up
  + healthy-untouched checks. 43/43.
2026-11-08 02:22:59 +00:00
inference-bot 0bc3cd65e7 manifest: pin to 20261108-c6eb2b4 2026-11-08 02:09:35 +00:00
inference-bot c6eb2b44e8 overview: guests are their own list, excluded from member counts
/admin/overview now returns gift (guest) accounts in a separate guests[]
list instead of inside members[], and excludes them from totals.members,
totals.active and the member spend totals. Guests get their own totals
breakout (guests, guests_active, guest_spend, guest_all_time_spend) so
their spend stays visible without ever reading as member activity — the
same reasoning as the operator (admins) and agent categories.

Builds on the gift feature's account_type marker: a guest is any row with
account_type='gift'. The panel reads guests[] and ignores gift rows in
its member count either way.
2026-11-08 02:09:28 +00:00
inference-bot 103766eb74 manifest: pin to 20261108-6d9074e 2026-11-08 02:06:06 +00:00
inference-bot 6d9074eefe gift accounts: $5 guest passes with time box, inviter ledger, auto member conversion
Operator feature: a member gives a friend access with $5 of credits, no OC
membership. Cloudron user lands in the guests group (chat + dashboard only),
LiteLLM team capped at GIFT_BUDGET with NO monthly reset, portal row marked
account_type='gift' with gift_expires_at set, gift welcome email, newsletter
subscription, and a gifts ledger recording inviter -> recipient (one gift per
inviter per 30 days, one per recipient ever).

Sweep safety: reconcile_memberships never deactivates a gift for lacking an
OC contribution; reconcile_gift_lifecycles lapses gifts by their own rules
(credits spent out, or the GIFT_DAYS time box) with member-deactivation
semantics. Guests are excluded from Loomio/Matrix invite lists, the reinvite
path, budget notices, the allowance reconciliation and the metrics member
counts.

Conversion: a gift whose OC identity appears under its own email converts
automatically (webhook + sweep + /admin/provision all funnel through
provision_member): group guests->members, cap lifted to allowance + carried
credits, anchor day kept, congrats email, full member onboarding.
/admin/gift-convert links a membership paid under a different OC email
(members.oc_email, matched by the sweep and webhook).

Fixture test: tests/test_gift_lifecycle.py (37 checks, network replaced by
a raising guard).
2026-11-08 02:05:37 +00:00
inference-bot 73d8c61aa7 manifest: pin to 20261108-2d2d191 2026-11-08 01:55:29 +00:00
inference-bot 2d2d191e11 money-series: drop the caveat field from the payload
The operator removed all caveats from the finance chart; the balance-history
note is gone from the API payload too so it cannot reappear anywhere.
balance_history_start, the series, totals, sources and errors are unchanged.
2026-11-08 01:55:23 +00:00
inference-bot f44c4bb6bd manifest: pin to 20261108-dcce9fc 2026-11-08 01:50:18 +00:00
inference-bot dcce9fcb35 money series: /admin/money-series (revenue/spend/OC balance) + daily OC balance snapshot
- /admin/money-series (X-Admin-Token, 30/min): three series for the admin
  panel's Money chart, hourly in-memory cache with stale-on-error fallback.
  revenue = OC contribution transactions (CREDIT/CONTRIBUTION/non-refund,
  monthly + one-time, org-backed included), cumulative from 2026-09-06;
  spend = one GROUP BY day pass over the full LiteLLM SpendLogs (no team
  filter, same definition as metrics_snapshot.spend_by_day); balance = OC
  current balance + daily snapshots.
- OC exposes only the CURRENT balance — no historical series exists — so
  metrics_snapshot.py now writes oc_balance_usd into metrics_daily daily
  (from 2026-11-08 onward; balance history cannot be backfilled). The
  endpoint seeds an existing row's balance with the live value without
  touching the snapshot's other columns.
- Aggregate totals only: no member emails or names selected or returned.
2026-11-08 01:50:17 +00:00
inference-bot 3cc2fad1dd manifest: pin to 20261106-ed66d73 2026-11-06 19:51:34 +00:00
inference-bot ed66d73327 activation hook: fire Loomio+Matrix syncs at first broker login
New members were skipped by the syncs until their Cloudron account was
activated (deliberately - never invite a half-created account), but nothing
fired the syncs at the moment they DID activate: the 3x/day sweep was the
only pickup, so a newly-activated member could wait hours for forum/space
access (limdingwen waited ~5h on 2026-11-06).

Hook the broker identity path (_verify_broker_secret): after an active
member resolves, if loomio_invited_at is still null, confirm their Cloudron
account is activated (inviteAccepted, fail-CLOSED - an unreadable user list
never fires) and run the same idempotent syncs the sweep runs, as a
background task off the response. Established members pay one indexed
SELECT; concurrent first-logins collapse into one run via an inflight flag;
each service is independently best-effort so a Loomio outage cannot block
the Matrix invite or the response.

Tests: tests/test_first_login_sync.py (18 checks, fixture db + stubbed
network). Also fix test_allowance_shortfall, whose expected exclusion
reference still asserted the pre-a88ca86 placeholder.

Sweep, provisioning and deactivation paths are untouched.
2026-11-06 19:51:12 +00:00
inference-bot a88ca860d4 fix: restore the real OC tx reference in SHORTFALL_REMEDIATED (repo must match the deployed image)
The deployed portal image (20261105-ca3b8db) was built from a working tree
carrying the real transaction id; commit 22c0167 over-redacted it to a
placeholder that matches nothing, so the next build would lose the exclusion
that prevents double-crediting the manually-remediated 2026-11-04 shortfall
charge. Sync HEAD to the deployed bytes (md5-identical to the running
container). The tx id alone is the H2-approved form: it identifies the OC
transaction, carries no member email.
2026-11-05 18:55:15 +00:00
inference-bot 8720d623ea manifest: pin to 20261105-00f60f1 2026-11-05 16:26:16 +00:00
inference-bot 00f60f1374 ops: bound allowance_log growth; correct stale README claims (audit L4+L5)
allowance_log: the sweep and every report-mode run used to append a row
per member per run (~500/day measured). The insert is now an upsert per
(member, cycle, decision) — a re-derived decision updates the row's
evidence and timestamp; a decision CHANGE still gets its own row. No
index or migration; the latest-decision readers are unaffected; history
is not rewritten.

README: scheduler runs 3x/day (0 3,11,19 UTC), not nightly-3am; the
sweep's auth is the ADMIN_TOKEN X-Admin-Token header, not WEBHOOK_TOKEN;
the retired free/member/supporter tier budgets replaced by the actual
single MEMBER_BUDGET model; the unread OPENCOLLECTIVE_WEBHOOK_SECRET env
row removed.
2026-11-05 16:26:16 +00:00
inference-bot 1127b41ba3 manifest: pin to 20261105-ce1bc7b 2026-11-05 16:21:51 +00:00
inference-bot ce1bc7bee6 security: log every key-feed fetch (audit M2)
/admin/librechat/keys deliberately serves every member's chat key on one
sync token (the LibreChat sandbox seeds from it; a per-member fetch would
require changing the sandbox's identity model — decision recorded in
ops-docs maintenance/librechat-key-feed.md). Every fetch now logs a
count-only WARNING (no key material; the email redactor strips addresses)
with caller + user-agent, and the daily digest watches the rate against
the sandbox's ~10-min poll cadence.
2026-11-05 16:21:51 +00:00
inference-bot 8a9222033d manifest: pin to 20261105-d63f702 2026-11-05 16:17:21 +00:00
inference-bot d63f702ec3 privacy: redact member emails from portal logs (audit M1)
The _RedactWebhookPath filter now also strips email-shaped strings from
every log record — messages, %-format args (recursing into tuple/list/
dict args), and any exception text already attached to the record — the
same retention discipline the webhook token got in ops/security#2.
_send_email recipients, listmonk failures, Loomio invite lists and
provisioning/credit lines carry member addresses into container logs,
which persist on the host and ride the backups. MXIDs, counts, slugs and
amounts stay readable; the daily digest's own sanitisation is unchanged.
Filter keeps its never-break-logging guarantee (all redaction inside
try/except; non-string args untouched).

Live pre-state measured: 99 email-bearing lines in the current app log.
2026-11-05 16:17:21 +00:00
inference-bot 2b501b75be manifest: pin to 20261105-b9561a4 2026-11-05 16:06:52 +00:00
inference-bot b9561a49d2 correctness: paginate Cloudron user fetches; atomic held-credit grant (audit M5+M6)
M6: a single-page ?per_page=100 fetch silently truncates past 100 users —
the box is at 99. New shared walkers (async + sync) page through
/api/v1/users like the Matrix paths, capped at 50 pages. All six single-
page call sites now walk: duplicate-email check (provisioning 409s),
reinvite loop, Loomio activation filter, admin overview, member-email
resolution, local MXID resolution. Failure behavior per site is preserved
(page-1 failure fails loudly; later-page failure keeps what was read).

M5: provisioning-time held-credit grant moved into grant_held_credits():
per hold, the status flip, balance move and ledger row commit in ONE
transaction (the old code committed the flip before add_credits, so an
exception between them left hold=granted and the member uncredited).
Mirrors admin_held_grant, keyed on held:<hold_id> so re-runs are no-ops;
mixed-case emails normalized. Tests in tests/test_portal_hardening.py.
2026-11-05 16:06:52 +00:00
inference-bot 0f32c3a868 manifest: pin to 20261105-22c0167 2026-11-05 15:59:07 +00:00
inference-bot 22c0167978 privacy: de-PII the shortfall exclusion and policy comment (audit H2)
SHORTFALL_REMEDIATED is keyed on the OC charge reference alone (the same
idempotence key the shortfall path uses); the member's identity and the
timeline of the 2026-11-04 manual allowance reset move to the operations
docs and stay in the ledger. The policy comment that named a member's
join/charge dates is generalized. No behavioral change: the exclusion
matches the same charge it always matched.
2026-11-05 15:59:07 +00:00
inference-bot f0d67e7efa manifest: pin to 20261105-e6ab177 2026-11-05 15:54:34 +00:00
inference-bot e6ab177a05 credits: make the credit-pack webhook grant idempotent (audit H1)
- reference built per-order from the webhook's order.idV2 (the id the
  amount lookup resolves) instead of the absent data.id that produced
  the legacy empty-suffix 'oc:<slug>:' format; legacy ledger rows are
  neither re-keyed nor rejected (a new-format reference can never match
  one)
- credit_reference_exists() gates add_credits; a re-delivered order
  returns 'already_credited' with the standing balance
- hold path: one hold per purchase via a pre-check plus a UNIQUE index
  on held_credits.oc_reference (index creation logs CRITICAL and
  continues if the live table ever carried duplicates — audited: none)
- get_order_amount sends the webhook-supplied order id as a GraphQL
  variable instead of interpolating it into the query (audit L9)
- regression test: replay credits exactly once; legacy rows never
  block a first grant; unique-index semantics incl. NULLs
2026-11-05 15:54:29 +00:00
inference-bot 48128ab97b manifest: pin to 20261105-6337bcf 2026-11-05 03:48:17 +00:00
inference-bot 6337bcfc24 portal: don't double the oc: prefix in the held-credit grant reason 2026-11-05 03:48:01 +00:00
inference-bot 11a74d955e manifest: pin to 20261105-e103e67 2026-11-05 03:47:21 +00:00
inference-bot e103e6779b portal: add admin endpoint to grant a held credit pack to a member
Held credit packs (purchases by non-members) could previously only be
refunded or auto-granted when the SAME email/slug later became a member.
A purchase made on another account's behalf therefore had no admin path
and forced a hand-edit of money state.

Add POST /admin/held-credits/{hold_id}/grant with body {email}: applies
the hold to a specified member account in one transaction (balance +
ledger + hold -> granted), idempotent on reference held:<hold_id>.
2026-11-05 03:45:14 +00:00
inference-bot ed1e361b14 manifest: pin to 20261104-db64dac 2026-11-04 20:01:28 +00:00
inference-bot db64dac235 allowances: credit the shortfall when OC's billing day truncates a paid cycle
Open Collective aligns recurring charges onto the collective's common billing
day, so a mid-month joiner is charged again before a full month is up: they pay
for a full month and receive less than one. Credit the missing ALLOWANCE (the
flat MEMBER_BUDGET pro-rated for the days lost, unrounded) as non-expiring
credits.

- derived from the collective's real per-order charge history, on every sweep;
  any consecutive pair on the same order < a full month apart is truncated
- idempotent on the OC charge reference (dedupe on the charge, not the member)
- skips and logs any cycle whose dates cannot be determined
- ledger reason names the cycle; the notice is staged and defaults OFF
- [redacted member reference]'s remediated charge is excluded by ref

Tests: tests/test_allowance_shortfall.py (pure derivation).
2026-11-04 20:01:10 +00:00
inference-bot c468b61d3e manifest: pin to 20261104-f7bbec8 2026-11-04 19:26:04 +00:00
inference-bot f7bbec8a0a loomio: enable by default; idempotent add (never re-invite) + targeted remove
The guard direction from 2026-11-04 is corrected: the co-op DOES use Loomio and
wants every new member added. Removing members/notifications is not the goal —
not duplicating them is. The feature is switched back ON and the sync is made
idempotent instead.

Enablement
  * LOOMIO_SYNC_ENABLED now defaults to ENABLED (kill switch: set =0 to pause).
    Restoring LOOMIO_API_KEY and deploying is all that is needed again.

Non-duplicating ADD (the real fix), two layers:
  * (a) live pre-check against Loomio group membership (b3 index, ordered and
    paginated stably). An address already in the group is skipped SILENTLY —
    it is never placed in an invite payload, so no API call about it can fire
    a notification or email.
  * (b) members.loomio_invited_at: an address we have handed over before is
    never sent again, even if it is not (yet) visible in the live roster.
  * FAIL CLOSED if the live roster cannot be read.
  * remove_absent is never sent.

Removal reconciliation preserved (deactivation must still propagate):
  * A member in the group who is no longer active is removed via a TARGETED
    b3 DELETE by membership id — it names only the member being removed, so it
    cannot re-invite or notify anyone staying. Operator allowlist
    (LOOMIO_ALWAYS_KEEP) is never removed. 404 (already gone) counts as
    success, so a re-run neither errors nor churns.
  * The keep-set is computed from the UNFILTERED active list: an active member
    whose Cloudron account is not yet activated is not removed (only their
    invite is deferred).

Tests: tests/test_loomio_guard.py (26/26) — add/dedupe, silent skip, record
guard, fail-closed, remove-once, allowlist-never-removed, targeted removal
(no present member in any payload), double-run no-op for both phases, 404
tolerance, kill switch.
2026-11-04 19:25:45 +00:00
inference-bot 17329c5d6f manifest: pin to 20261104-120a246 2026-11-04 19:09:33 +00:00
inference-bot 120a24678d loomio: never invite an existing member (off by default + positive exclusion)
Incident 2026-11-04: a live run of sync_loomio_memberships() emailed a Loomio
invite notification to essentially the WHOLE membership (notification 744:
~83 in-app recipients, ~79 emails 'sent' 18:53-18:56 UTC). The sync handed
Loomio the full active-member list every run with no record of who had been
invited, relying on Loomio's add-if-absent semantics — which produced a
whole-group notification.

Guards now make a repeat impossible:
  * LOOMIO_SYNC_ENABLED (off by default) — restoring LOOMIO_API_KEY alone no
    longer re-arms the integration.
  * members.loomio_invited_at — positive exclusion: an address is sent only if
    it is neither in Loomio's current member list NOR ever handed over, and
    each is recorded once. (The new column starts NULL for the ~89 members
    already in Loomio, so the current-member check is what closes that gap.)
  * FAIL CLOSED — no invite if Loomio's member list cannot be read.
  * remove_absent is dropped: no evict-then-re-add (re-invite) path.

Tests: tests/test_loomio_guard.py (10/10).
2026-11-04 19:09:33 +00:00
inference-bot 947e4d3cf2 manifest: pin to 20261104-8c85c91 2026-11-04 18:47:18 +00:00
inference-bot 8c85c912e8 allowances: add a would_deactivate PREVIEW (deactivation stays gated off)
Report mode (and a send run while ALLOWANCE_DEACTIVATE is off) now reports a
member whose reminder is past the grace window as would_deactivate, with the
reminder date, grace length and deadline in the evidence. The real action is
unchanged and still needs BOTH ALLOWANCE_POLICY=on AND ALLOWANCE_DEACTIVATE=on.

The lapse decision is extracted into a pure function (allowance_lapse_decision)
so it is unit-testable against a synthetic reminder time:
tests/test_allowance_lapse.py (would_deactivate past grace; in_grace inside).
2026-11-04 18:46:54 +00:00
inference-bot ee7ed77697 manifest: pin to 20261104-f1945aa 2026-11-04 18:31:06 +00:00
inference-bot f1945aaf53 admin overview: expose derived membership state (active / in_grace / awaiting_contribution / inactive)
The admin panel needs to show a member's membership state without inventing
policy of its own. Compute it in the portal (the source of truth) from what the
allowance reconciliation already knows — the payment_reminders send record and
the latest allowance_log decision — and carry it on each /admin/overview row as
state + state_reason. Read-only; no side effects.
2026-11-04 18:30:42 +00:00
inference-bot 97da432bd4 manifest: pin to 20261104-a8200fd 2026-11-04 17:31:33 +00:00
inference-bot a8200fdf54 allowances: correct the dormant-yearly note (collective order list is complete; a member's account.orders spans collectives) 2026-11-04 17:31:11 +00:00
inference-bot 36b7c2f77e manifest: pin to 20261104-a984a44 2026-11-04 17:30:09 +00:00
inference-bot a984a443e1 allowances: recognise YEARLY contributions so a yearly payer isn't read as unpaid
_payment_verdict treated MONTHLY as the only recurring frequency, so a live
ACTIVE YEARLY contribution — one charge, current for twelve cycles — fell
through to "no recurring (monthly) contribution" and would have been reminded
and (with deactivation on) deactivated for eleven of those months.

Make the verdict frequency-aware: only a MONTHLY or YEARLY order can cover an
allowance cycle; an ACTIVE YEARLY covers while its window (last charge + 1yr,
or nextChargeDate) includes now; PROCESSING stays paid-pending; a ONE-TIME
payment is credit, never an allowance period and never a mask. A failed
monthly charge still takes the remind path.

Dormant on today's data: inference-cooperative has 0 yearly orders (104 orders:
88 MONTHLY, 16 ONETIME), verified per member ACCOUNT because a member's own
yearly order does not appear in the collective-level order list. This changes
no current member's decision — the report is identical before and after.

Adds tests/test_payment_verdict.py (yearly branch + monthly/processing/onetime/
error/cancelled cases), runnable in the app container.
2026-11-04 17:29:47 +00:00
inference-bot 86e77a0ad4 manifest: pin to 20261104-ced8c4f 2026-11-04 05:19:58 +00:00
inference-bot ced8c4f082 email: set an explicit Message-ID on outbound mail so a send is traceable 2026-11-04 05:19:43 +00:00
inference-bot 75959e6045 manifest: pin to 20261104-5237e63 2026-11-04 05:18:54 +00:00
inference-bot 5237e6352b allowances: add mode=test to /admin/allowance to verify a reminder really sends 2026-11-04 05:18:39 +00:00
inference-bot f68e4fb652 manifest: pin to 20261104-a8bdb70 2026-11-04 05:18:09 +00:00
inference-bot a8bdb70e08 allowances: fix decision-label mapping (would_renew not would_renewed) 2026-11-04 05:17:54 +00:00
inference-bot 326fec9214 manifest: pin to 20261104-d878c32 2026-11-04 05:17:26 +00:00
inference-bot d878c32d68 allowances: restore fetch_member_orders/_payment_verdict/payment_reminder_email dropped in the slug fix 2026-11-04 05:17:12 +00:00
inference-bot ea4660690d manifest: pin to 20261104-f8b3eaa 2026-11-04 05:16:46 +00:00
inference-bot f8b3eaacd6 allowances: resolve OC slug from the member's email, not the stored column
The first report run matched orders on members.slug, which holds a stale
guest-… slug from first provisioning for 18 members — every one of them read
as unpaid while actually being current payers. Resolve the live slug from the
member's email via the OC member list, refresh the stored slug, and treat
members absent from the OC member list as unverifiable (skip, never punish).
2026-11-04 05:16:32 +00:00
inference-bot 985b55f6d9 manifest: pin to 20261104-ccce643 2026-11-04 05:15:41 +00:00
inference-bot ccce643b39 allowances: payment-driven renewal anchored to the member's join day
Replaces the payment-date re-anchoring that let Open Collective's common
billing day move a member's renewal and skip a cycle ([redacted member reference]:
[redacted timeline].

- Reconcile against OC orders directly on the sweep's schedule: a live
  recurring contribution (ACTIVE/PROCESSING) renews; otherwise one reminder
  email, then deactivation only after PAYMENT_GRACE_DAYS.
- Anchor each member's reset to their join day (members.anchor_day), not the
  payment date; the webhook now only confirms the cycle.
- Decision log (allowance_log) records renewed/reminded/deactivated with the
  payment evidence.
- Report-only by default (ALLOWANCE_POLICY=report); deactivation gated
  separately by ALLOWANCE_DEACTIVATE=off.
- POST /admin/allowance?mode=report|send.
2026-11-04 05:15:24 +00:00
inference-bot 5da1981823 manifest: pin to 20261104-a89c464 2026-11-04 01:05:43 +00:00
inference-bot a89c464834 sync: retire identities from all invite rooms, not just Space+General
The retirement half of sync_matrix_space() iterated [MATRIX_SPACE_ID] + the
General room while the invite half used member_invite_rooms() (MATRIX_INVITE_ROOMS,
7 rooms including Skillshare). A retired local identity was therefore left in
Design, Community, Infrastructure, Updates and Skillshare — a privacy problem in
member-only rooms. Iterate member_invite_rooms() in both halves so they cannot
drift again. Retirement logic (kick joined / revoke invite-state) is unchanged.
2026-11-04 01:05:41 +00:00
inference-bot d5b4a2e03a manifest: pin to 20261103-c53112f
The registry builder is working again (the build pushed cleanly), so
restore the dockerImage pin the portal dropped in f45ca19. Tag carries
the Requests-count fix in app/main.py (commit c53112f).
2026-11-03 23:40:33 +00:00
inference-bot c53112fbaf model usage: Requests counts only successful calls
The Requests column summed every spend-log row (COUNT(*)), so a model's
call count included refused/failed attempts — e.g. Metis showed 26 calls
when only 16 succeeded (the other 10 were 401s on /v1/systemone).

Count only rows whose status is not 'failure', and report the refused
count separately as 'refused' (per model and in totals) so a failure
cannot inflate use without disappearing from view. spend and tokens stay
summed over all rows: a call that failed after consuming tokens still
cost money.

Fixes the panel and dashboard model tables, which both read this
aggregation (panel via /admin/model-usage, dashboard via
/broker/model-leaderboard).
2026-11-03 23:39:01 +00:00
inference-bot 8bcb7ff049 sync: invite members to configured MATRIX_INVITE_ROOMS (Skillshare)
sync_matrix_space() now invites every active member to the rooms in
member_invite_rooms(): MATRIX_INVITE_ROOMS when set, else the co-op Space +
General room; legacy MATRIX_EXTRA_ROOMS is still appended. The set is explicit
configuration, never "every child of the Space", so operator-only rooms are not
pushed at members. Skillshare (!NSPfCdVP7TWTtFoAz1TxVOcqnoDIpMoJDiPb_XS79ys)
was missing from the invite set, so no member who joined after it was created
was ever told about it; including it here makes the nightly sweep self-heal.
2026-11-02 19:51:11 +00:00
inference-bot ea648aab95 README: document operator_spend_usd in the metrics snapshot 2026-11-02 15:51:27 +00:00
inference-bot f45ca199cf manifest: build on-server (drop the registry image pin)
The remote registry builder is currently unusable from this Cloudron host:
its in-build `docker login registry.inference.coop` resolves the registry to
127.0.0.1:443 and is refused, so no new image can be pushed to the registry
(the box's own docker CAN reach the registry — a pull of a missing tag returns
a clean 404 — so this is the builder's container network, not the registry).
The panel and dashboard are already unpinned and build on-server via
`cloudron update` from the repo dir; the portal joins them so its code can ship
the operator-spend breakout the dashboard reads. Restore the pin when the
builder is fixed.
2026-11-02 15:49:11 +00:00
inference-bot 8fc670b240 manifest: pin to 20261102-5f8bed3 2026-11-02 15:42:38 +00:00
inference-bot 5f8bed33e6 metrics: break out the co-op's own (operator) spend in the daily series
metrics_daily.spend_usd is the co-op-wide total and deliberately spans every
team, operators included — the numbers were already right. What was missing
was a way to tell how much of that total is the co-op's OWN usage, so a
member-facing chart could not be misread as member-only activity.

Adds metrics_daily.operator_spend_usd: the per-day portion of spend_usd that
belongs to the accounts in OPERATOR_EMAILS (teams aliased member:<email>, like
anyone else). NULL = not measured (never a confident 0), mirroring spend_usd.

- metrics_snapshot.py: operator_spend_by_day() + write it on snapshot/backfill
- app/main.py: expose it in metrics_series (so /broker/metrics and
  /admin/metrics/series carry it), and add operator_spend /
  operator_all_time_spend to /admin/overview totals as the explicit breakout
  of total_spend / total_all_time_spend.

spend_usd and every existing column are untouched.
2026-11-02 15:42:30 +00:00
InferenceBot ddeefdebe0 manifest: pin to 20261101-6a7eaf0 2026-11-01 18:00:30 +00:00
InferenceBot 6a7eaf0ff8 broker: per-key spend (chat separate) in /broker/usage
Members need to see how much each API key has spent. LiteLLM's per-key
'spend' counter is cycle-only (resets at budget_reset_at), so derive it
from the LiteLLM_SpendLogs table instead: sum spend grouped by api_key,
matching rows to member_api_keys.hash by name and labelling unmatched
rows 'chat' (the portal-held chat key is never in member_api_keys).

broker_get_usage now returns key_spend: [{name, is_chat, spend, tokens,
requests}], API keys by spend desc with the chat row last.
2026-11-01 18:00:25 +00:00
inference-bot b065b7301f manifest: correct the registry path in the pin
I had rewritten co-op/member-portal to code/member-portal while bumping the tag. The repository path in a live pin is the registry location the image is stored and fetched from; changing it points Cloudron at a repo that does not hold this app. Only the tag should move.
2026-11-01 17:17:13 +00:00
inference-bot abdc56e84c manifest: pin to 20261101-e1ec25f
Tag names the commit it was computed from, after committing the agent all-time-spend change.
2026-11-01 17:17:00 +00:00
inference-bot e1ec25f1e4 admin overview: give agent teams an all-time spend, not just the cycle counter
The team spend counter is cycle-only and resets at budget_reset_at, which for the agent teams means the 1st of the month. The panel's agents table read that field directly, so on 1 November the co-op's own bot accounts appeared to have had their spend zeroed out. Members already had an all-time figure for exactly this reason; agent teams did not, because the all-time query filtered to member:% only. Widen it to agent:% and expose all_time_spend on agent rows.
2026-11-01 17:16:33 +00:00
inference-bot 5beffaf7d5 manifest: pin to 20261031-6f6957c 2026-10-31 16:58:03 +00:00
inference-bot 6f6957c779 portal: budget notice copy — drop the reassurance, button says 'Buy credit packs'
Removes 'nothing else about your account changes' from both the body and the footer; it goes without saying. Button label becomes 'Buy credit packs', and the sentence above it says the same thing so the two do not disagree.
2026-10-31 16:57:40 +00:00
inference-bot d2b6f1551f manifest: pin to 20261031-b998d8d 2026-10-31 16:53:50 +00:00
inference-bot b998d8d535 portal: budget notices gain mode=test (email one sample, no ledger row)
Lets the letter be read in a mail client before the sender is armed. Uses the member's real numbers when the address matches one, writes nothing to budget_notices so the once-per-crossing latch is not consumed, and works while BUDGET_NOTICES is off.
2026-10-31 16:53:22 +00:00
inference-bot c21421a89b manifest: pin to 20261031-7d2507a 2026-10-31 16:50:01 +00:00
inference-bot 7d2507a927 portal: 90% threshold for budget notices; sweep 3x a day
Trigger becomes proportional (90% of the balance used) instead of a $2 floor, so a member on $15 and one on $35 are treated the same. The once-per-crossing latch keys on the same fraction. membership_sweep moves from '0 3 * * *' to '0 3,11,19 * * *' so the notice arrives within hours of crossing rather than up to a day later. BUDGET_NOTICES remains off.
2026-10-31 16:49:22 +00:00
inference-bot 26be6156ae manifest: pin to 20261031-d5fbb2e (previous commit dropped the date prefix and 404ed the pull) 2026-10-31 16:44:23 +00:00
inference-bot bb864055e6 manifest: pin to d5fbb2e (computed before the commit again — the code commit is 49e79aa) 2026-10-31 16:35:48 +00:00
inference-bot d5fbb2ed84 portal: budget notice -> generic low-balance wording, $2 floor, username, once per crossing
Wording no longer names an allowance or a credit pack: it says balance, so it is true whether the member is short on allowance, on purchased credit, or both. Trigger is an absolute $2 floor on remaining budget rather than a percentage, so it means the same at any budget size. Recipient greeting uses members.slug (the username) instead of the email local part, which produced 'Hi n,'. The once-only latch now clears when the balance rises back above the floor, so it fires once per crossing rather than once per budget cycle. BUDGET_NOTICES stays off.
2026-10-31 16:35:35 +00:00
inference-bot 49e79aadcc manifest: pin to 20261031-87e7c5b (the earlier pin named the pre-commit hash) 2026-10-31 16:25:51 +00:00
inference-bot 87e7c5b30e portal: budget notices by email, off by default
Warns a member at 80% of their monthly cap and again when it is exhausted, using the welcome email's template shell. Spend and budget come from LiteLLM's Postgres, the same source the dashboard shows. One notice per level per budget cycle. BUDGET_NOTICES=off|dryrun|on gates sending; POST /admin/budget-notices previews at any time and refuses to send unless the flag is on. Rides the existing sweep cron, wrapped so it cannot break reconciliation.
2026-10-31 16:25:36 +00:00
inference-bot 76d59b3fb6 manifest: pin dockerImage to 20261030-6475a51 2026-10-30 19:22:05 +00:00
portal-dev 6475a51067 metrics: expose + persist measured-vs-estimated provenance (#4, #6)
Thread the per-factor source through impact_for() instead of discarding it.
Numeric output (energy_wh, co2e_g) is byte-identical — this is a reporting
change, not a recalculation.

#6 persistence: additive columns tokens_measured, tokens_estimated and
factor_revision (a stable hash of the factor table) on metrics_daily, added via
the existing guarded ALTER TABLE idiom in both app/main.py and
metrics_snapshot.py. Existing rows keep NULL.

#4 API: metrics_series() selects the new columns and derives a per-row
provenance indicator (measured | mixed | estimated | none) from the split; both
/admin/metrics/series and /broker/metrics return it. NULL/unknown splits report
'none', never a confident 'measured'.

docs/energy-metrics.md documents the indicator, the new columns, and the
forward-only-vs-backfill behaviour.
2026-10-30 19:12:20 +00:00
inference-bot e5c6b6060e manifest: pin dockerImage to 20261029-9f198fc 2026-10-29 21:20:19 +00:00
inference-bot 9f198fcf4c overview: exclude sandbox teams from the agents list, and name agents for display
sandbox:librechat-test is a throwaway test account rather than an agent of the co-op,
so it drops out of the panel. Its spend then appears nowhere — accepted knowingly.

Agents also carry a display `name` (the alias minus its "agent:" prefix), so the panel
does not have to strip prefixes itself.
2026-10-29 21:19:21 +00:00
inference-bot a0040f52e0 manifest: pin dockerImage to 20261029-592cf83 2026-10-29 20:57:38 +00:00
inference-bot 592cf83656 metrics + overview: stop counting utility accounts as members, and surface agent usage
The panel has always excluded operator/utility emails from member counts
(OPERATOR_EMAILS), but the metrics counted every row in the members table, so the
panel said 75 while every metric surface said 76. The one affected row is
info@inference.coop — the reading mailbox, not a person.

- metrics_snapshot.py now applies the same OPERATOR_EMAILS definition (same variable
  name, same default) so the two cannot drift apart again. No backfill: history stays
  as published and the daily job writes the corrected value going forward.
- admin_overview now also returns an `agents` list, built from the LiteLLM teams it
  already fetches (anything not member:*), so bot and sandbox spend is visible rather
  than structurally invisible. Kept out of member counts and member aggregates, like
  the operator category.
2026-10-29 20:57:10 +00:00
inference-bot b11552fa49 docs: write down how the energy/CO2 metrics actually work (#3)
The calculation lived only in code comments. Adds docs/energy-metrics.md and wires it
into the README, per the issue's proposed scope. No calculation changes.

Contents: the input (completion_tokens, output tokens only, grouped on model_group)
and why output-only understates total compute; the factor table with its three
provenance tiers (measured / same-family / estimated) and the fact that the tiers are
never exposed; the formulas; NULL-not-zero and the reason (the first backfill claimed
every day used no energy); the implied-grid-intensity tripwire and the 1000x carbon
error it exists to catch; the 03:15 schedule and that --backfill REWRITES history.

States plainly what is measured and what is not: GreenPT is measured, glm-5.3 is
assumed from its flash sibling, and all Tinfoil and Regolo traffic currently falls to
the proxy estimate — with the consequence that the 250 gCO2e/kWh proxy OVERSTATES
Regolo, which runs on renewable energy.

README: "Two jobs" -> "Three", the metrics_snapshot task documented, and a short
Energy & carbon metrics subsection linking the new doc. Also corrects "listing both
tasks" in the post-change verification step.
2026-10-29 20:15:10 +00:00
inference-bot 42cf43a125 manifest: pin dockerImage to 20261029-42bdfa2 2026-10-29 04:19:33 +00:00
inference-bot 42bdfa25d3 portal: record that the admin-token cutover is complete (comment only)
The comment above ADMIN_TOKEN still said "set ADMIN_TOKEN_LEGACY=0 and rotate
both". Stale — and the direct reason a report claimed a rotation was
outstanding: ADMIN_TOKEN was minted new and WEBHOOK_TOKEN rotated on 2026-10-27,
and the legacy path was closed on 2026-10-28.

Comment only, no behaviour change. Rebranched onto the current main: an earlier
attempt had pinned an image built from a tree that predated the key-encryption
work, which would have reverted it.
2026-10-29 04:19:17 +00:00
inference-bot d5a7a72416 docs: PORTAL_KEK env var (key encryption at rest) 2026-10-28 17:15:07 -06:00
inference-bot ceeaf277e2 manifest: pin dockerImage to 20261028-a5410ac (inlined key crypto) 2026-10-28 17:11:40 -06:00
inference-bot a5410ac237 Inline key-encryption module into main.py
The build service's context dropped new files added under app/
(keycrypto.py never reached the image while main.py did), causing a
crash loop. Inline the module so the deploy cannot miss it. Behavior
unchanged: AES-256-GCM at rest, KEK from PORTAL_KEK, enc1: format,
legacy plaintext passthrough, fail-closed migration.
2026-10-28 17:11:12 -06:00
inference-bot 4a48529cbb manifest: pin dockerImage to 20261028-3ee385d-nc (rebuilt no-cache, keycrypto present) 2026-10-28 17:01:36 -06:00
inference-bot 8ee1c8cea5 manifest: pin dockerImage to 20261028-3ee385d (key encryption at rest) 2026-10-28 16:50:20 -06:00
inference-bot 3ee385de12 Encrypt member chat keys at rest (AES-256-GCM)
Member feedback: keys stored in plaintext in the portal DB are a
key-compromise incident waiting to happen. Members.key_token (the chat
key) is now encrypted with AES-256-GCM using a KEK from the PORTAL_KEK
env var. Plaintext exists only in memory when a key is served (dashboard,
LibreChat key feed, LiteLLM management). Startup migration encrypts
existing rows idempotently; fail-closed when the KEK is absent.
Member-managed API keys were already reveal-once (hash-only at rest).
2026-10-28 16:48:58 -06:00
inference-bot ac3d79a1df manifest: pin dockerImage to 20261028-a0d15e3 (sweep legacy-token cleanup) 2026-10-28 13:54:04 +00:00
inference-bot a0d15e30d8 sweep: drop the legacy WEBHOOK_TOKEN fallback (cutover is complete)
ADMIN_TOKEN_LEGACY is "0" and verified: ADMIN_TOKEN returns 200 on /admin/*,
WEBHOOK_TOKEN returns 403. The fallback in sweep.sh would therefore turn
"ADMIN_TOKEN unset" into a confusing mid-run 403 rather than the clear abort
that already exists three lines below it. Same removal in the digest script.

Not a behaviour change in normal operation — ADMIN_TOKEN is set (len 64) and
already preferred — but it removes a foot-gun that could mask a broken
configuration, and leaves the code honest about which credential is live.
2026-10-28 13:53:25 +00:00
inference-bot e773c5097f manifest: pin dockerImage to 20261028-0ae1404 (carbon unit fix) 2026-10-28 04:35:05 +00:00
inference-bot 0ae1404ab5 metrics: fix carbon unit conversion (Wh -> kWh is /1e3, not /1e6)
The carbon column was 1000x too low: 2.9 gCO2e for 55 days and 14.35 kWh,
where 14.35 kWh at the factor table's own intensities must be ~2.9 kg. Energy
was right, so nothing looked broken unless you did the arithmetic — 938 Wh in a
day cannot be 0.2 g of CO2.

Adds a tripwire in impact_for(): if the implied grid intensity falls outside
5-500 gCO2e/kWh, it prints a warning rather than quietly returning numbers. The
factors themselves span 24-250, so a blend outside that band means a unit or
factor error, not a cleaner grid.
2026-10-28 04:34:50 +00:00
inference-bot 997d047323 manifest: pin dockerImage to 20261028-8e9906d (impact column fixes) 2026-10-28 04:34:06 +00:00
inference-bot 8e9906d844 metrics: fix the impact columns — group by model_group, never write a zero
Two bugs from the first deploy, both caught by reading the numbers back:

1. Tokens were summed per raw `model`, which carries the UPSTREAM name
   (openai/deepseek-v4.1-flash), while the factor table is keyed on our
   provider aliases (greenpt/deepseek-v4.1-flash). Every model therefore
   matched nothing. Now grouped on model_group, the same convention
   aggregate_model_usage uses, with model as the fallback for old rows.

2. Every day was written as energy_wh = 0.0 / co2e_g = 0.0 — a false claim that
   the co-op used no energy, and precisely the fail-open this module is written
   to avoid. A day with no measured tokens now yields NULL for all three impact
   columns, and impact_for() refuses to compute from an empty total.

The backfill is idempotent, so re-running it overwrote the zero rows.
2026-10-28 04:33:50 +00:00
inference-bot 89593cfa74 manifest: pin dockerImage to 20261028-af610fe (energy and carbon metrics) 2026-10-28 04:32:20 +00:00
inference-bot af610fe25f metrics: energy and carbon per day, from measured GreenPT factors
Implements the approach Nathan settled on in co-op/support#26: per-token
estimates based on what GreenPT publishes, rather than waiting on the upstream
LiteLLM `impact` passthrough.

- New daily columns: out_tokens, energy_wh, co2e_g.
- Tokens come from OUR OWN spend logs (completion_tokens per model per day), so
  member-visible impact does not depend on any client persisting an `impact`
  object. GreenPT's metric counts OUTPUT tokens only — that is the unit — so
  input tokens are excluded deliberately.
- Factors live in one table with a source per row. The greenpt/* rows are
  MEASURED: fitted from live calls to their API across prompt sizes
  (energy = overhead + marginal x output tokens, R2 >= 0.999; carbon from the
  grid intensity their own emissions imply — ug/mWh and g/kWh are the same
  ratio). Everything else falls back to a documented order-of-magnitude proxy,
  so a day's total is never silently missing models.
- Migration: CREATE IF NOT EXISTS never adds columns, so both the script and
  the app ALTER TABLE on connect.

Refining a factor is a data edit in IMPACT_FACTORS, not a code change.
2026-10-28 04:32:05 +00:00
inference-bot 5a9b0d2b0d manifest: pin dockerImage to 20261028-27d30a1 (broker metrics route fix) 2026-10-28 04:17:18 +00:00
inference-bot 27d30a1af2 portal: fix the broker metrics route (decorator landed on the wrong handler)
My earlier patch inserted the new handler between the existing
/broker/model-leaderboard decorator and its function, leaving two routes
pointing at model-leaderboard and none at /broker/metrics, which 404'd. The
dashboard's co-op leaderboard was being served the wrong payload.

Caught by the post-deploy check (the 404 on a route whose code was present in
the container), not by the build. Adds a pre-build route-table assertion —
every path must be followed by its intended handler — so this shape of mistake
fails before a build rather than after a deploy.
2026-10-28 04:17:03 +00:00
inference-bot acd01afc99 manifest: pin dockerImage to 20261028-4ffadd2 (broker metrics route) 2026-10-28 04:15:19 +00:00
inference-bot 4ffadd223c metrics: share the series with members through the broker
Members asked to see how the co-op is doing, not just their own usage. The
series was admin-only; now the same query serves both surfaces.

- metrics_series(days) holds the query once; /admin/metrics/series and the new
  /broker/metrics both call it (no second copy to drift).
- /broker/metrics is broker-authenticated and returns AGGREGATE, NON-PERSONAL
  figures only: co-op size, requests served, spend. Same class as
  /broker/model-leaderboard, and the same rule — no per-member figure passes
  through the broker.
2026-10-28 04:15:03 +00:00
inference-bot 6ab0554d00 manifest: pin dockerImage to 20261028-1cf78c4 (membership history fix) 2026-10-28 03:56:20 +00:00
inference-bot 1cf78c4e56 metrics: membership history from list-join dates, not welcome_sent_at
The backfill's first real curve was wrong: built on welcome_sent_at it showed
34 members on 19 October, when the co-op had ~65. Most members were provisioned
before the portal sent welcome emails, so that field lags by dozens of people —
and a chart built on it would have misrepresented the co-op's growth.

Membership now comes from Listmonk's per-subscription subscription_created_at
on the members list, which the portal's nightly reconcile keeps mirroring
active members. That reproduces the real curve (13 members mid-September → 71
today). Past days are the cumulative joins of today's members — an honest floor,
documented as such, since members who left are absent.
2026-10-28 03:56:06 +00:00
inference-bot c5d5fa2fac manifest: pin dockerImage to 20261028-27c32fc (listmonk count fix) 2026-10-28 03:55:03 +00:00
inference-bot 27c32fc75f metrics: count LIST membership status, not the subscriber's own status
The first live run recorded newsletter_subs = 0 — a wrong zero, the exact
fail-open this module documents against. Cause: Listmonk's subscriber record
carries status enabled/blocked, while the LIST membership carries
subscription_status confirmed/unconfirmed. Filtering on the subscriber's own
status matched nothing and returned a silent 0.

Now counts memberships whose subscription_status is confirmed (verified: 71,
matching the list), and returns NULL when the endpoint yields no rows at all —
"not measured" rather than "nobody is subscribed". The daily job is the
regression test: it must record 71, not 0.
2026-10-28 03:54:42 +00:00
inference-bot 80de75672c manifest: pin dockerImage to 20261028-70ae435 (daily metrics snapshot) 2026-10-28 03:53:39 +00:00
inference-bot 70ae435867 metrics: daily snapshot of members and usage, backfillable, plus a read route
The co-op had no longitudinal data: every number was an ad-hoc query, so
nothing compounded and no single source owned "how many members do we have,
and when did that change". That cost us a wrong figure in the newsletter ("six
new members" — actually 21; the six were forum joins).

New: metrics_snapshot.py writes one row per day into the portal's SQLite store
(the same members.db), and GET /admin/metrics/series returns them oldest-first
for the panel and dashboard to chart later.

  - Cumulative columns (members_active, members_total, members_new,
    newsletter_subs, matrix_space_members) are counts AS OF that day;
    spend_usd/requests are THAT day's traffic.
  - FAIL CLOSED PER METRIC: an unreadable source yields NULL, never a zero — a
    zero reads as "nobody" and would bake a lie into a chart. Failures print to
    stdout, and a scheduler task's stdout lands in the app log.
  - Listmonk's cached subscriber_count is NOT trusted (it reads 142 for a list
    holding 71): the count comes from paging the subscribers endpoint.
  - Member growth comes from welcome_sent_at, the provisioning timestamp —
    the closest thing the portal stores to a join date. Manual/founder members
    have no welcome email, so backfilled days are a documented LOWER BOUND;
    today's row carries the exact count.
  - Runs as an in-app scheduler task (addons.scheduler, 03:15 UTC) rather than
    an agent cron: member-facing plumbing should not depend on the agent VM.
  - Backfill is idempotent; member growth is reconstructible back to
    September and spend/requests back to the gateway's first request.

Charts land later, on the surfaces, once the shape of the series is reviewed.
2026-10-28 03:52:49 +00:00
inference-bot 403a773f53 manifest: pin dockerImage to 20261027-452a27a (member-set guard + access-log redaction) 2026-10-27 05:04:44 +00:00
inference-bot 452a27a778 portal: guard against an implausible member list; redact the webhook token from logs
Two fixes, both filed rather than deferred.

1. member-portal#2 — the sweep deactivates every member whose email is missing
   from the Open Collective member list, and the existing fail-safe only covers a
   fetch that RAISES. A fetch that SUCCEEDS while returning nothing or far less
   than usual is unguarded, and is what a narrowed token scope, an expired
   credential with partial access, or a renamed Membership tier produces (the
   fetch filters on the tier's name). That path deactivates the membership
   instead of failing. fetch_members() now checks the result against the local
   active count before any caller can act on it: empty, or at or below half of
   local, raises — so the sweep's fail-safe takes over and members stay active.
   Skipped when we have no active members of our own (fresh install).

   Correction to the issue as filed: listmonk_reconcile reads the local members
   table, not this fetch, so the newsletter path was never exposed to it. The
   sweep is the only destructive consumer.

2. ops/security#2 — OC's generic webhooks cannot send headers, so the webhook
   secret must travel in the URL path, and uvicorn wrote it into the access log
   on every delivery. A logging filter on uvicorn.access and on the root handler
   replaces the token with <redacted>. The token cannot be kept out of the URL;
   it can be kept out of the retention.

Both pieces are unit-tested in isolation before shipping: the guard's decision
function over eight cases, and the filter against a real access-log record, an
unrelated path (no over-redaction), and a missing dependency (must not break
logging).
2026-10-27 05:04:05 +00:00
inference-bot c2369034ee manifest: pin dockerImage to 20261027-5720a63 (security fixes: admin token split, credit-pack order verification, revoke on lapse) 2026-10-27 03:34:29 +00:00
inference-bot 5720a63958 security: separate admin token, verify credit-pack orders, revoke access on lapse
Member disclosure, three findings (fixes 1-3 of 5):

1. WEBHOOK_TOKEN was both the Open Collective webhook URL token and the
   X-Admin-Token for every /admin/* route, so anything that learned the webhook
   URL (OC admins, OC logs, this app's access logs) gained portal admin. The URL
   token is forced by OC's generic webhooks, which cannot set headers — the reuse
   is not. Introduce ADMIN_TOKEN, header-only. ADMIN_TOKEN_LEGACY=1 (default)
   still accepts WEBHOOK_TOKEN and logs a warning, so the admin panel and the
   scheduler keep working; set ADMIN_TOKEN everywhere, then flip it to 0 and
   rotate. sweep.sh and the digest script now send ADMIN_TOKEN.

2. The credit-pack path fell back to the webhook payload's own amount when OC
   could not resolve the order, so a forged POST naming its own totalAmount
   minted credits for any slug. The payload is now a hint only: an unresolvable
   order is refused, logged loudly, and emailed to the operator for manual
   reconciliation. Transient OC failures hold instead of granting blind.

3. Lapsing did not revoke access: both deactivation sites (lapse webhook, nightly
   sweep) discarded the key token deactivate_member() returns. Member keys carry
   no max_budget of their own, so they inherit the team's — zero the team budget
   on deactivation, which blocks every key under it. Key deletion is deliberately
   NOT used: provisioning reuses the stored sk- token on reactivation, and
   get_or_create_team does not update an existing team's budget, so the two
   renewal paths now re-sync the budget explicitly. Failures are loud (log +
   alert email); deactivation still completes.
2026-10-27 03:31:40 +00:00
Ubuntu e55d8a3f1e newsletter: operator accounts are not stale subscribers
info@inference.coop is on the Members list but has no members row, so the
reconcile classified the co-op's own inbox as a stale subscriber and would have
unsubscribed it.

The data model already distinguishes this: OPERATOR_EMAILS (default
info@inference.coop,bot@inference.coop) are infrastructure accounts — the SSO
owner and the bot — which the panel surfaces under "admins" and excludes from
member counts. They live outside the members table by design. The Loomio
reconciliation applies the same rule to the same accounts via LOOMIO_ALWAYS_KEEP
("must always remain in the group").

So operators become the third class here: neither members nor stale. Their
subscription is left exactly as it is (never unsubscribed, and the reconcile
never subscribes, so an operator who unsubscribes stays unsubscribed). The
response reports how many were left, and the log line carries counts only.
2026-10-26 16:54:53 +00:00
Ubuntu 250ca6e8f0 manifest: pin dockerImage to 20261026-9495daa (the image now running) 2026-10-26 16:45:22 +00:00
Ubuntu 9495daa701 newsletter: the unsubscribe PUT needs the email field — it was a silent 400
The end-to-end probe against the live listmonk caught this: PUT
/api/subscribers/{id} with {"lists": []} returns 400 {"message":"Invalid
email."}, leaving the subscriber on the list. It needs {"email": ..., "lists":
[]}. The failed request was only a log warning, so the reconcile's main job —
taking lapsed members off the Members list — has never worked; only the DELETE
branch did anything, which is the branch this series just removed.

Now both classes unsubscribe successfully and keep their record.
2026-10-26 16:42:10 +00:00
Ubuntu 7bb676eb68 newsletter: unsubscribe stale subscribers instead of deleting them; sweep: apply the documented fail-safe
Two findings from the retrospective review of 394cccfb..e24c272e (#34).

listmonk_reconcile() deleted subscribers with no members row outright. That
destroyed the subscriber's consent/unsubscribe history, and a stray test account
is indistinguishable from a real person who subscribed outside the portal. Both
classes now leave the list the same way — PUT {"lists": []} — and the record is
kept as a suppression marker; nothing is purged automatically. The summary log
line reports counts by reason instead of subscriber addresses. Subscriber
pagination also gains a short-page fallback so a missing `total` cannot truncate
the reconcile at page 1.

reconcile_memberships() called fetch_members() unguarded, so the documented
fail-safe — skip reconciliation rather than deactivate everyone missing from a
partial list — was unreachable: since fetch_members() now raises, the sweep
returned a 500 instead of {"status": "skipped"}. It now catches the failure and
returns reason "member_fetch_failed". The two webhook call sites are left
unguarded on purpose: a payment webhook should fail loudly so OC retries it, and
it self-heals.

Refs #34
2026-10-26 16:38:52 +00:00
Ubuntu ac0bdb6518 manifest: pin dockerImage to the deployed tag
The repo didn't record which image is live, so it couldn't answer "what is
deployed here?" — the tag lived only on the Cloudron app. Pin it to the image
deployed 2026-10-26 so the repo mirrors production, as our other repos do.

Consequence, same as librechat-custom: when the CLI runs from this directory this
manifest now wins over `cloudron update --image <tag>`, so a future release pins
the new tag here and commits it as part of the deploy.
2026-10-26 16:27:53 +00:00
Ubuntu 492019088e loomio: only rename auto-generated handles, never one a human chose
Testing the previous commit against the live Loomio user list showed it would
also have renamed a member whose handle was chosen by hand (a working name
would have become the sanitized OIDC uid) — the uid is domain-shaped, so the
sanitizer produced a different, wrong target. The function is scoped to
Loomio's own auto-generated handles: the email local part with
non-alphanumerics stripped plus a random suffix. Gate on that shape.

Verified against the live user list (70 users) before building: exactly one
handle changes — the member whose username fix 422'd on every sweep — no
computed target violates Loomio's rule, and the hand-chosen handle is left
alone.
2026-10-26 16:19:42 +00:00
inference-bot 178a4aa360 loomio: sanitize usernames instead of falling back to another invalid one
The username fix rejected a dot-containing OAuth uid and then substituted the
email local part, which carries the same dots — so Loomio answered 422
("Usernames must contain lower case letters, numbers, underscores, and internal
hyphens only") on every sweep, for the one member whose Cloudron username has a
dot. Normalize instead: disallowed characters become underscores, and leading
and trailing hyphens/underscores are stripped. Also log the Loomio user id
rather than the member's email.
2026-10-26 16:07:23 +00:00
inference-bot e24c272e2e org-link fix: INSERT bound 4 values to 3 placeholders (500 on every link); slug = org slug 2026-10-21 21:16:59 -06:00
inference-bot d8d80d9594 newsletter reconcile: Members list mirrors ACTIVE members
Root cause of test accounts receiving the newsletter: LISTMONK_API_USER was
set EMPTY in the portal env - env-present beats the code default, so every
listmonk_sync authenticated with an empty user and 403'd silently. Fixed both
the env (set to portal-sync) and the code (empty env falls back to default).

New: listmonk_reconcile() - the Members list must mirror ACTIVE members.
Stale subscribers are removed: members marked inactive are taken off the list
(record kept as suppression marker); addresses that are not members at all
(test/deleted accounts) are deleted outright. Wired as step 4 of the nightly
membership sweep + POST /admin/newsletter/reconcile for on-demand runs.
2026-10-21 16:32:36 -06:00
inference-bot e4da4da2c6 pagination fix: OC MemberCollection has NO cursor pageInfo — use offset+totalCount pagination (verified against the live API); the cursor query 400'd, taking the sweep and org endpoints down 2026-10-20 23:30:32 -06:00
inference-bot 42c664c076 OC member queries: cursor pagination via fetch_all_member_nodes() — members(limit:100) silently hid everyone past member #100 (same class as the Cloudron 25-per-page trap). Helper RAISES on any page failure so callers' fail-safes apply (never a partial list — the sweep would deactivate everyone missing from one); fetch_members returns [] on failure (sweep skips), fetch_org_backers propagates (sweep keeps linked accounts active), webhook payer lookup and /admin/org-link wrapped. 2026-10-20 23:26:18 -06:00
inference-bot fed4a7005e audit fixes: two latent NameErrors in the org code — webhook org branch referenced undefined org_name (crashed on an unlinked org's first payment), org-links GET referenced undefined name (crashed when a linked org's dues show inactive) 2026-10-20 23:21:51 -06:00
inference-bot d87cbf9650 admin overview: expose matrix_mxid (dashboard-set external handle) per member 2026-10-20 23:01:24 -06:00
inference-bot dcffbb1b98 org-links GET: remaining name-column reference 2026-10-20 22:57:40 -06:00
inference-bot 394cccfbcb org links: members table has no name column — drop it from org SQL/unpackings (names come from OC/Cloudron) 2026-10-20 22:55:55 -06:00
inference-bot 72614f8f19 Organizational memberships: OC org contributors (type ORGANIZATION) never expose an email, so all three automated paths missed them (webhook email lookup, nightly sweep, /join). Add: members.org_slug link column + fetch_org_backers() (org BACKER/Membership nodes); sweep keeps linked accounts active while the org's dues are active and deactivates on lapse (fail-safe keeps active if the org fetch errors); webhook re-activates linked accounts on org dues and emails the operator for unlinked orgs; POST /admin/org-link (link + full provision incl. Cloudron signup link) and GET /admin/org-links (live dues status); admin overview gains an 'org' field. 2026-10-20 22:45:37 -06:00
inference-bot 5425efee1f overview: normalize float-residue spend (e.g. -5.55e-17 after cycle reset) to 0 so the panel never renders -0.00 2026-10-19 11:42:58 -06:00
inference-bot fd13bc6ea2 broker/matrix-mxid GET: local_mxid_for_email was async-def but never awaited — response contained a coroutine and FastAPI 500'd ('coroutine object is not iterable'), so the dashboard silently showed no registered Matrix ID. Make it a plain sync def (blocking urllib). 2026-10-19 10:47:49 -06:00
inference-bot 97ebe69553 portal: /admin/librechat/keys — dedicated-token feed of member chat keys for the sandbox's key auto-load 2026-10-18 23:15:38 -06:00
51 changed files with 17871 additions and 715 deletions

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
# Woodpecker CI pipeline for the member portal — THIN on purpose.
#
# Runs the portal's EXISTING test suites (tests/test_*.py, one self-contained
# script per regression, each with its own "WHY THIS EXISTS" docstring). No
# test logic lives here; any change to what is tested belongs in tests/.
#
# Gating: `push` fires the suite on every push (including branch pushes), so a
# red run blocks the merge via Gitea branch protection (status check
# `ci/woodpecker/push/main`). `manual` is kept so a run can be triggered by
# hand from the Woodpecker UI or API.
#
# Backend note (why there are no container images here):
# The co-op's Woodpecker agent is a Cloudron app with no Docker socket, so it
# runs the `local` backend — each step executes as a shell command INSIDE the
# agent container and the step's `image:` field selects the SHELL, not a
# container image. Every tool a step needs must be baked into the agent image
# (co-op/woodpecker-agent): python3 + pip, node, bash, git, git-lfs.
#
# Dependency note (why not `-r requirements.txt`):
# The agent image's Python is 3.14, where the app image's PINNED stack has no
# published wheels (pydantic 2.9.2 / psycopg2-binary 2.9.9). The tests import
# app.main, which at import time needs only the bounded ranges below; the
# heavier runtime deps (uvicorn, psycopg2) are lazy-imported and unneeded by
# the suites. Ranges, not floating, so a future major cannot silently change
# what CI proves — a major bump shows up as a red run here first.
when:
- event: push
- event: manual
steps:
- name: tests
image: bash
commands:
# venv on the writable volume — the container rootfs is read-only and
# pip refuses to write /root/.local.
- python3 -m venv .venv
- .venv/bin/pip -q install 'fastapi>=0.115,<1' 'httpx>=0.27,<1' 'PyJWT>=2.9,<3' 'slowapi>=0.1.9,<1' 'cryptography>=44,<46'
# Run EVERY suite even when one fails, then fail the step — a single
# command chain would hide all failures after the first.
- |
fails=0
for f in tests/test_*.py; do
echo "== $f"
.venv/bin/python "$f" || fails=$((fails+1))
done
if [ "$fails" -ne 0 ]; then
echo "FAILED: $fails test file(s) red"
exit 1
fi
echo "all portal test suites green"
+3
View File
@@ -0,0 +1,3 @@
# CI config is privileged: a change here can alter what runs in the shared
# Woodpecker agent container. Require an Owners review before merge.
^\.woodpecker\.yml$ @co-op/owners
+18 -9
View File
@@ -14,17 +14,26 @@
},
"sendmail": {},
"scheduler": {
"membership_sweep": {
"schedule": "0 3 * * *",
"command": "/app/code/sweep.sh"
},
"rag_refresh": {
"schedule": "30 3 * * *",
"command": "/app/code/rag_refresh.py"
}
"membership_sweep": {
"schedule": "0 3,11,19 * * *",
"command": "/app/code/sweep.sh"
},
"service_sync": {
"schedule": "*/5 * * * *",
"command": "/app/code/service_sync.sh"
},
"metrics_snapshot": {
"schedule": "15 3 * * *",
"command": "/app/code/metrics_snapshot.py"
},
"credit_cycle_close": {
"schedule": "*/10 * * * *",
"command": "/app/code/credit_cycle_close.sh"
}
}
},
"manifestVersion": 2,
"website": "https://inference.coop",
"contactEmail": "info@inference.coop"
"contactEmail": "info@inference.coop",
"dockerImage": "registry.inference.coop/code/member-portal:20261202-ca336a3"
}
+5 -3
View File
@@ -9,8 +9,10 @@ RUN pip install --no-cache-dir -r requirements.txt
# Copy app
COPY app/ ./app/
COPY sweep.sh /app/code/sweep.sh
COPY rag_refresh.py /app/code/rag_refresh.py
RUN chmod +x /app/code/sweep.sh /app/code/rag_refresh.py
COPY service_sync.sh /app/code/service_sync.sh
COPY credit_cycle_close.sh /app/code/credit_cycle_close.sh
COPY metrics_snapshot.py /app/code/metrics_snapshot.py
RUN chmod +x /app/code/sweep.sh /app/code/service_sync.sh /app/code/credit_cycle_close.sh /app/code/metrics_snapshot.py
# Run as root (the base image default). Cloudron's sandboxing (read-only
# rootfs, AppArmor, dropped capabilities) still applies to root inside the
@@ -20,4 +22,4 @@ RUN mkdir -p /app/data
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--forwarded-allow-ips=172.18.0.1"]
+302 -27
View File
@@ -30,7 +30,18 @@ LibreChat ──→ Member Portal ──→ LiteLLM ──→ backend
## The three responsibilities
1. **Webhook handler** (`POST /webhook/opencollective`) — listens for Open
Collective membership events and activates/deactivates members.
Collective membership events and activates/deactivates members. The same
endpoint carries credit-pack purchases, so a failure here can cost a member
money: it answers **503** (retryable) with an ERROR line naming the exception
when anything unexpected escapes, and **401** when the URL token is wrong —
that status means the webhook URL and `WEBHOOK_TOKEN` disagree, so it is
never swallowed by the error net. Any OC read it makes has an explicit
timeout and one retry (`_oc_graphql_post`); until 2026-11-13
`fetch_all_member_nodes` used httpx's 5-second default and a slow page became
an unhandled 500 on a paid purchase. The durable backstop — reconciling PAID
credit packs against `credit_ledger` on a schedule — is not built yet; see
the app repo's issue *"Backstop: reconcile PAID credit packs against the
ledger"*.
2. **Key injector** (`/v1/*`) — reads the member's email from the
`X-User-Email` header, looks up their LiteLLM key, and forwards the
request to the gateway with that key.
@@ -45,32 +56,109 @@ LibreChat ──→ Member Portal ──→ LiteLLM ──→ backend
| `MEMBERS_GROUP_ID` | Cloudron group ID for members (grants chat access) |
| `LITELLM_BASE` | LiteLLM gateway URL |
| `LITELLM_MASTER_KEY` | LiteLLM master key |
| `OPENCOLLECTIVE_WEBHOOK_SECRET` | Optional webhook signature secret |
| `PORTAL_KEK` | **Required.** Base64-encoded 32-byte key-encryption key. Member chat keys (`members.key_token`) are stored AES-256-GCM-encrypted at rest (`enc1:` prefix) and decrypted in memory only when served (dashboard, LibreChat key feed, LiteLLM management). Generate with `python3 -c "import base64,os;print(base64.b64encode(os.urandom(32)).decode())"`. If unset, the portal runs but refuses to encrypt new keys, keeps legacy plaintext, and logs CRITICAL. Rotating it requires re-encrypting every row (decrypt with the old key, encrypt with the new). |
| `ADMIN_TOKEN` | The portal's admin token (`X-Admin-Token` header) for the `/admin/*` endpoints the panel calls. Never the webhook URL token — that one cannot unlock `/admin/*` by design. |
| `ALLOWANCE_POLICY` | `report` (default) \| `on`. `report` computes every allowance decision and changes nothing; `on` performs renewals and sends the one reminder. Deactivation is gated separately by `ALLOWANCE_DEACTIVATE`. |
| `ALLOWANCE_DEACTIVATE` | `off` (default) \| `on`. When `on`, a member who was reminded and is still unpaid after the grace window is moved to the inactive group. **Defaults off so renewals/reminders can run before anyone loses access.** |
| `PAYMENT_GRACE_DAYS` | Days after the single reminder before an unpaid member is deactivated (default `7`). |
| `GUEST_BUDGET` | Guest-account credit in USD (default `2.0`). |
| `GUEST_DAYS` | Guest-account time box in days from provisioning (default `60`). The sweep deactivates an expired guest even with credits left. |
| `GUEST_PER_INVITER_DAYS` | Rolling window for the one-guest-per-inviter limit (default `30`). |
| `GUESTS_GROUP_ID` | Cloudron group ID for guest accounts. The chat and dashboard apps' access restrictions list BOTH the members and guests groups, so a guest reaches exactly those two apps. |
| `GUESTS_ENDED_GROUP_ID` | Cloudron group a SELF-CANCELLED guest's user lands in: out of guests (chat access ends) but still admitted by the dashboard app, so the ended state and Become-a-member stay visible. Unset → the shared inactive group (dashboard access ends too). |
## Tier budgets
## Guest accounts
Governance decision (set in Loomio). Defaults:
A member can give a friend access to the co-op with $2 of credits — no Open
Collective membership required. `POST /admin/provision-guest` (X-Admin-Token)
with `{"email", "name", "inviter": "<the guest access member's email>"}` runs the
guest pipeline: Cloudron user in the **guests** group, a LiteLLM team capped at
`GUEST_BUDGET` with **no monthly reset** (the cap is the guest's whole life), the
portal row marked `account_type='guest'` with the $2 held as non-expiring
credit, `guest_expires_at` set to now + `GUEST_DAYS`, the guest welcome email
(setup link, what they can use, Become-a-member, newsletter note), and a
**guests ledger** row (`guests` table: inviter → recipient, expiry, status) for
the abuse audit. Guards: one guest per inviter per `GUEST_PER_INVITER_DAYS`; one
guest per recipient ever; the inviter must be an active member; an existing
portal row under the recipient address is refused. Guests are subscribed to
the newsletter and invited to NOTHING else (no Loomio, no Matrix).
- `free` — $2/month of tokens
- `member` — $15/month
- `supporter` — $30/month
**Member self-serve invitations (provision immediately).** `POST /broker/guests`
(the member-dashboard broker identity — a guest identity fails it) lets a MEMBER
invite a guest from their dashboard: `{"email", "name"}`. The same guards run
BEFORE anything is created (`guest_request_guard`: everything above, plus the
recipient is never a `MANUAL_MEMBERS` address), and a valid invitation
**provisions immediately** — the approval gate was removed on 2026-11-08 as
operator policy; the remaining protections (active member, one guest per
inviter per rolling 30 days, one guest per recipient ever, the $2 cap and the
`GUEST_DAYS` box) were judged sufficient. `provision_guest_member` re-runs
every guard, so a moved-state refusal still refuses. The member sees their
invitation trail — each guest with its status and expiry — via
`GET /broker/guests`.
## LibreChat wiring
**Sweep safety.** `reconcile_memberships()` never deactivates a guest for
lacking an OC contribution. A guest lapses only by its own rules, handled by
`reconcile_guest_lifecycles()` inside the sweep: credits spent out (LiteLLM's
cap enforces the limit; the sweep retires the row) or the `GUEST_DAYS` time box.
Deactivation is the same semantics as a member's — guests group → inactive,
budget zeroed, row `active=0`, newsletter unsubscribed — and the account is
KEPT so a returning payer resumes cleanly.
Point LibreChat's custom endpoint at this portal (not directly at LiteLLM),
and add the identity header:
**Self-service cancellation (recipient-initiated).** `POST /broker/cancel-guest`
(dashboard broker identity) ends a guest account at the recipient's own
request: deactivation with the same kept-account semantics, the newsletter
unsubscribed, and — the part a lapse does not do — any UNSPENT credit
returned to the co-op as a negative `credit_ledger` row whose reason names
the cancellation and the original guest reference (`guest-return:<email>` is
the dedupe reference, so a repeat cancel can never double-return). The
guests-ledger row records the full trail: inviter → recipient → 'cancelled
by recipient'. The Cloudron user leaves the guests group for
`GUESTS_ENDED_GROUP_ID` — chat and API access end, while the dashboard app
(which lists that group in its access restriction) still admits them, so
`GET /broker/guest-status` can show the ended state: access ended, data
kept, Become-a-member still one contribution away. A paying member calling
either route gets a 403 — cancelling a membership means ending the Open
Collective contribution, and this endpoint is deliberately guest-only.
**Guest → member conversion (automatic).** When a guest's OC identity appears as
a live BACKER/ADMIN with the account's own email — via the webhook or the
nightly sweep — `provision_member()` routes the call to
`convert_guest_to_member()`: the Cloudron user moves guests → members, the
LiteLLM cap lifts to the member allowance + credits (unspent guest credit is
carried — it already lives in `credit_balance`), the row becomes a normal
member with the standard `MEMBER_BUDGET`, the anchor day (the guest's start
date) is kept and the reset pinned to it, the congratulations email goes out,
and the normal member onboarding runs (newsletter, Loomio + Matrix syncs,
docs-RAG group, held-credit grants). When the contribution arrives under a
DIFFERENT OC email it cannot auto-match: the operator links it with
`POST /admin/guest-convert` `{"email": "<guest account>", "oc_email": "<the OC
email the contribution is under>"}` — the row records `members.oc_email`, and
the sweep and webhook treat that address as an additional matcher from then on.
## Budget model
Governance decision (set in Loomio): a single sliding-scale Membership tier
($5–$20/month flexible) with a FLAT allowance for every member —
`MEMBER_BUDGET` (default `15`), reset on each membership payment and extendable
with non-expiring purchased credit packs. The per-tier budgets the portal once
shipped (free/member/supporter) are retired — there are no per-tier portal
settings; the single env knob is `MEMBER_BUDGET`.
## Chat wiring
LibreChat talks to the **gateway directly** with each member's own key; the
portal is not in the chat request path. (The old `/v1/*` key-injection proxy —
`X-Portal-Secret` + `X-User-Email` — was retired 2026-11-19. It let anyone with
that shared secret spend as any member, and nothing used it.)
```yaml
# librechat-custom/librechat.yaml (excerpt)
endpoints:
custom:
- name: "Inference Cooperative"
apiKey: "${LITELLM_KEY}"
baseURL: "https://portal.inference.coop/v1"
headers:
X-User-Email: "{{LIBRECHAT_USER_EMAIL}}"
models:
default: ["deepseek-v4-flash", "gpt-oss-120b"]
fetch: true
apiKey: "${INFERENCE_COOP_API_KEY}"
baseURL: "https://gateway.inference.coop/v1"
```
## Status
@@ -92,19 +180,206 @@ points. Remaining work before production:
## Scheduled tasks (scheduler addon)
Two jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
Four jobs run inside the container via `CloudronManifest.json` → `addons.scheduler`:
- **membership_sweep** (nightly 3am) — `sweep.sh` calls the portal's own
`/admin/sweep` (auth: `X-Admin-Token` = `WEBHOOK_TOKEN`) to reconcile members
- **membership_sweep** (`0 3,11,19 * * *` UTC — three times a day) — `sweep.sh`
calls the portal's own `/admin/sweep` (auth: the `X-Admin-Token` header with
the portal's `ADMIN_TOKEN` — never `WEBHOOK_TOKEN`, which is the webhook's
URL token and returns 403 on `/admin/*`) to reconcile members
against the live Open Collective list: provisions missed signups, deactivates
lapsed members, syncs Loomio + Matrix. Idempotent; a missed webhook
self-heals within 24 hours.
- **rag_refresh** (nightly 3:30am) — `rag_refresh.py` pulls this repo's
sibling docs from the Gitea raw API (public, no credentials), uploads changed
files to Open WebUI (`OWUI_API_KEY`), attaches them to the shared knowledge
collection (`DOCS_KNOWLEDGE_ID`), reindexes, and re-grants the members group.
State persists in `/app/data/rag_refresh_state.json`.
self-heals within a day. The same sweep also runs the payment-driven
allowance reconciliation (below) and the credit-pack reconciliation.
**Credit-pack reconciliation** (`CREDIT_RECONCILE`, default `report`) — credits
are granted on exactly one path, the OC `order.processed` webhook, and that
path can fail AFTER the money has moved: on 2026-11-13 a $50 pack's delivery
500'd on httpx's invisible 5-second default, and a $10 pack had no delivery in
the retained log at all. Neither left a ledger row and nothing noticed. This
pass reads OC's OWN order list (`fetch_collective_orders`, needs the `orders`
scope on `OC_PERSONAL_TOKEN`, granted 2026-11-13) and compares it with our
books over `CREDIT_RECONCILE_DAYS` (default 30 — days, not "whatever our log
still holds": the $10 gap was 11 hours old and the log had already lost the
whole morning). In `report` mode it logs findings and changes NOTHING; grants
happen only when `CREDIT_RECONCILE=on`. Every grant uses
`credit_pack_reference()` — the same per-order key the webhook writes — so a
late delivery and this pass cannot both credit one purchase. A buyer who is not
an active member is reported, never credited: those keep the hold-and-email
path. On demand: `POST /admin/credit-pack-reconcile` (`X-Admin-Token`), a dry
run unless `?apply=1` and the policy is `on`.
Matching caution: our own references are NOT uniform, so a bare
`oc:<slug>:<order.id>` test reports credited purchases as missing (it read 21
of them that way, all false). `credit_pack_accounted()` matches the exact
reference when one exists and otherwise requires a second signal — same member,
same tip-free amount, within days — and counts a `held_credits` row as
accounted for. Each candidate also carries its `nearby_book_rows` (the member's
own ledger/held rows within a week) because a manual grant can be real and carry
no reference at all: the 2026-09-28 launch-day packs were credited as `+20.00`
then corrected by `-10.75`, netting exactly 3 × $5.00 with no reference on any
row. A reviewer sees that, instead of a phantom victim.
**Webhook-failure report** — the portal records every delivery it does not
accept in `webhook_failures` (`record_webhook_failure()`, called from the
webhook wrapper, including the 401 that means the webhook URL and
`WEBHOOK_TOKEN` disagree) and the sweep emails `info@` **once per new batch**
via a marker in `portal_state`, so a wrong token does not mail every sweep while
the rows stay queryable. Each row carries the source IP and user-agent, and the
email names the source: Open Collective posts from its own hosts, so a refusal
from an unrelated address is a probe, not a purchase. This replaces the
log-scraping watcher that used to run
on the operator's machine: the portal handles every delivery, so the portal is
what must notice and report a failure. (It also removes the dependency on a log
buffer with only hours of memory — when the 2026-11-13 $10 purchase was
investigated, whole hours were missing from it.) Log-scraping jobs cannot be
the primary alert for a signal whose window they cannot see.
**Unmapped-backer check** — a contributor who pays but has no portal row never
gets an account, because `fetch_members()` drops every member node with no
email and an OC Organization never exposes one (the mmoya case, found weeks late
by the member asking). `reconcile_unmapped_backers()` reads the RAW member nodes
— including the ones the sweep must skip — and compares them with `members.db`,
reporting three classes because each needs a different action: an ORG account
(link it with `/admin/org-link`), a VISIBLE email (the sweep should have
provisioned it — check the token), and a HIDDEN email (fetch it out-of-band,
then `/admin/provision`). A node with no account object is attributed through
same-day current orders, and is never reported without a date to attribute it
against. On demand: `POST /admin/unmapped-check`.
**Spend-consistency check** — on 2026-11-05 the portal's all-time-spend aggregate
failed *soft*: its copy of the gateway's LiteLLM DB credential had gone stale, the
query returned nothing, and every surface showed $0 while looking clean — the
portal was the thing that was wrong. `check_spend_consistency()` compares two
genuinely independent reads — the portal's SpendLogs aggregate over its own DB
credential, and LiteLLM's own HTTP API (`/global/spend/teams`) over the master key
— **day by day over the window both sides cover**, which localises drift instead of
hiding it in a sum. Two traps are encoded here: LiteLLM's per-day view reaches back
only a fixed number of days (31) while our table holds everything, so a
sum-vs-all-time test reports the missing window as drift ($107.63 of it on
2026-11-13, against a real agreement of $0.07); and `/global/spend/keys` follows
each key's own budget cycle, so it is not an all-time figure either
(`/global/spend/report` would be, but is Enterprise-gated). An EMPTY/$0 portal
aggregate while LiteLLM reports real spend is a FAILURE named as the
stale-credential signature — judged *before* the window overlap, since in that
failure there are no shared days to compare. Silent when they agree; a read that
cannot be made is `skipped`, never clean. On demand: `POST /admin/spend-check`.
**Notice policy (all of the above):** email `info@` only when there is a
problem, and only about what is NEW. What a human has been told is a growing SET
of keys in `portal_state` (`order:grant` / `order:hold`, `slug:class`) — a set
that shrinks (a purchase granted, a finding fixed) mails nobody again, a failed
send retries on the next sweep instead of going quiet, a `notify=False` run is a
look and never consumes the alert, and a clean pass clears the marker so a
recurrence is news again.
**Service-invite triggers:** the sweep is the backstop, not the primary path.
Two faster triggers exist, because a member who has just set up their account
should not wait hours for forum + Space access:
1. **First-login activation hook** — when a member first presents themselves
on the broker identity path (the dashboard's first login), the portal
checks — only if their Loomio invite is still outstanding
(`loomio_invited_at` is null) — that their Cloudron account is now
activated (`inviteAccepted`), and if so fires the same idempotent Loomio +
Matrix syncs as a background task. Established members cost one SELECT; the
response never waits on Loomio or Matrix; failures are logged and
non-fatal; unactivated accounts are never invited (the check fails closed).
2. **service_sync** (below) — the scheduled tick that covers members who never
open the dashboard.
- **service_sync** (every 5 minutes) — `service_sync.sh` calls the portal's own
`/admin/service-sync` (same `X-Admin-Token` auth as the sweep). WHY: a new
member is provisioned with an UNACTIVATED Cloudron account, and the syncs
deliberately skip an unactivated account (never invite a half-created one) —
so nobody on our side is watching at the moment the member actually activates.
This job fires the same idempotent Loomio + Matrix syncs the sweep runs, but
ONLY while some member is still awaiting their invites (one indexed SELECT
when nobody is, so it costs nothing in the steady state), and it deliberately
is NOT `/admin/sweep`: it never touches Open Collective, allowance logic or
member mail. An in-process guard drops an overlapping run.
Net effect: a member who has just set up their account waits minutes at most.
- **metrics_snapshot** (daily 3:15am UTC) — `metrics_snapshot.py` records one row per
day into the `metrics_daily` table: members, newsletter subscribers, Matrix
membership, spend, request counts, energy/CO₂, and the Open Collective
balance. Each run **completes yesterday's row** with its full-day
spend/requests/tokens/impact aggregates, then records today's row live (its
usage columns carry the hours so far and are completed by the next run's
completion pass). A source that cannot be read
yields NULL for that metric rather than a zero. `spend_usd` is the co-op-wide
total and deliberately spans every team, the co-op's own operator accounts
included; `operator_spend_usd` is the breakout of that portion, served through
`/broker/metrics` so the member dashboard can show the co-op's own share
alongside the total. `oc_balance_usd` is a daily snapshot of the collective's
OC balance (the OC API has no historical series, so balance history accrues
from these snapshots only — 2026-11-08 onward). `--backfill` rebuilds history
idempotently (balance history cannot be backfilled: past balances were never
recorded); `--backfill --since YYYY-MM-DD` repairs recent days' usage columns
only, leaving the membership curve as the nightly snapshots measured it.
Methodology: [Energy and carbon metrics](docs/energy-metrics.md).
Verify after any manifest change: the deploy log must show
`setupAddons: ... scheduler ...` listing both tasks, and each script must
`setupAddons: ... scheduler ...` listing all four tasks, and each script must
succeed when run manually inside the container.
### Allowance renewal (payment-driven, join-day anchored)
Each member has a monthly allowance (`MEMBER_BUDGET`, currently $15). The
allowance renews on the day of the month the member *joined*, never on the day
Open Collective happened to charge them — OC aligns every member's charge onto
the collective's common billing day, so anchoring to the payment date let an
early charge move the boundary and skip a cycle entirely. The join day is stored
per member (`members.anchor_day`) and the reset is pinned there.
Whether the allowance renews is decided by asking Open Collective directly, on
the sweep's own schedule (not inferred from webhook delivery): a member with a
live recurring contribution (order status `ACTIVE` or `PROCESSING` — a payment
in flight is not a missed payment) renews; a member with no live recurring
contribution gets **one** reminder email, and is deactivated only after
`PAYMENT_GRACE_DAYS`. One-time payments are not an allowance cycle — they top up
the non-expiring credit balance and are untouched here. There are no annual
contributors (verified 2026-11-04: 104 orders, 87 MONTHLY, 17 ONETIME, zero
annual), so only the monthly case is implemented.
Every decision (renewed / reminded / deactivated, plus the payment date or its
absence) is written to `allowance_log` and answerable from that record. Run
`POST /admin/allowance?mode=report` (X-Admin-Token) for a no-op report that
changes nothing; `mode=send` performs renewals and sends the reminder and
requires `ALLOWANCE_POLICY=on`. Deactivation additionally requires
`ALLOWANCE_DEACTIVATE=on`.
### Allowance shortfall (a paid cycle OC truncated)
Open Collective aligns every recurring charge onto the collective's common
billing day, so a member who joins mid-month is charged again well before a full
month has elapsed — they pay for a full month and receive less than one. The
co-op's remedy: credit the missing **allowance** (the flat `MEMBER_BUDGET`
pro-rated for the days lost, `FULL_PAID_MONTH_DAYS = 30`, unrounded) as
non-expiring credits — the same balance that extends the allowance and is spent
only after it. It is never a share of what they paid.
The set is derived FROM DATA, on every sweep (`POST /admin/sweep` calls
`reconcile_allowance_shortfalls`, as does `POST /admin/shortfall-credits`):
each MONTHLY order's real charge history is read from Open Collective, and any
consecutive pair on the SAME order less than a full month apart is a truncated
cycle. Two subscriptions a member happens to hold are judged separately; a gap
whose dates cannot be determined is skipped and logged. Each credit is keyed to
the specific OC charge that caused it (`credit_ledger.reference` = the charge
`publicId`), so a re-run credits nothing twice — dedupe is on the charge, not
the member — and the ledger `reason` names the cycle so a member's question is
answerable from it.
Member notices ride the same pass, but default OFF
(`ALLOWANCE_SHORTFALL_EMAILS=off`); set it to `on` to send the staged notice,
at most once per charge (`shortfall_notices`). `mode=report` on
`/admin/shortfall-credits` previews the affected set and changes nothing.
### Energy & carbon metrics
The daily snapshot also computes energy (Wh) and carbon (gCO₂e) from output tokens,
using per-model factors whose provenance varies: measured for GreenPT, assumed equal
for one sibling model, and an explicit order-of-magnitude estimate for providers that
disclose nothing. Only output tokens count, and a day with no measured tokens is
recorded as NULL rather than zero.
[Energy and carbon metrics](docs/energy-metrics.md) documents the factor table, the
formulas, the tripwire that catches unit errors, the schedule, and — most importantly —
which parts are measurements and which are estimates. What members are told is in
`co-op/docs/energy.md`.
+9265 -554
View File
File diff suppressed because it is too large. Load diff
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Credit cycle close — run by the Cloudron scheduler addon every 10 minutes.
#
# Calls the portal's own /admin/credit-cycle-close endpoint (localhost), which
# walks each active member's completed allowance cycles and draws the credits
# those cycles spent (issue #12: a monthly reset used to restore every credit
# pack, because nothing ever recorded what usage consumed).
#
# Idempotent: each closed cycle is keyed by the ledger reference
# `cycle-close:<email>:<cycle>`, so an overlapping tick or a restart never
# charges a cycle twice. Cheap: one SELECT when nobody has credits.
#
# The ADMIN_TOKEN env var is shared with the main app (scheduler runs in the
# same launch environment), so we use it to authenticate. Admin auth is a
# header, never a URL token.
set -e
if [ -z "$ADMIN_TOKEN" ]; then
echo "credit-cycle-close: ADMIN_TOKEN is not set; aborting" >&2
exit 1
fi
python3 - "$ADMIN_TOKEN" <<'PY'
import sys, urllib.request, urllib.error
token = sys.argv[1]
url = "http://127.0.0.1:8000/admin/credit-cycle-close"
req = urllib.request.Request(url, method="POST", data=b"", headers={
"Content-Type": "application/json",
"X-Admin-Token": token,
})
try:
with urllib.request.urlopen(req, timeout=300) as resp:
print("credit-cycle-close:", resp.read().decode())
except urllib.error.HTTPError as e:
print(f"credit-cycle-close: HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"credit-cycle-close: request failed: {e}", file=sys.stderr)
sys.exit(1)
PY
+197
View File
@@ -0,0 +1,197 @@
# Energy and carbon metrics
How the portal's daily `energy_wh` and `co2e_g` figures are produced, what is
measured versus estimated, and how to change them. Written because the calculation
previously lived only in code comments (see `code/member-portal#3`).
For what members are told, see `co-op/docs/energy.md`. This document is the
developer-facing counterpart and is deliberately blunter about the limits.
## Where the numbers come from
**Input: output tokens only, per day, per model.**
- Source: LiteLLM's spend logs (`LiteLLM_SpendLogs`), column `completion_tokens`.
- Grouped on **`model_group`** — our alias, e.g. `greenpt/deepseek-v4.1-flash` —
**not** `model`, which carries the upstream name (`openai/deepseek-v4.1-flash`).
Grouping on the wrong column matches no factor and yields zeros for every day. That
mistake shipped once during development and is the reason this is called out.
**Only output tokens count**, matching the unit GreenPT publishes (mWh per 100 output
tokens). This is a deliberate choice to line up with the provider's own metric, not an
oversight — and it means these figures **understate total compute**, because input
tokens consume energy too. Treat the numbers as comparable and directionally true
rather than as a total energy accounting.
## The factor table
Factors live in `metrics_snapshot.py` (`IMPACT_FACTORS`, `IMPACT_PROXY`). Matching is
`str.startswith()`, so **the longest prefix must come first** — order matters.
| model prefix | Wh / 1k output tokens | gCO2e / kWh | provenance |
|---|---|---|---|
| `greenpt/deepseek-v4.1-flash` | 0.3641 | 193.0 | MEASURED |
| `greenpt/glm-5.3-flash` | 1.0782 | 193.0 | MEASURED |
| `greenpt/glm-5.3` | 1.0782 | 193.0 | SAME_FAMILY |
| `greenpt/green-r` | 0.5535 | 23.6 | MEASURED |
| *anything else* | 0.5000 | 250.0 | ESTIMATED |
### The three provenance tiers
- **MEASURED** — fitted from live calls to GreenPT's API, which returns an `impact`
object on every request (energy in watt-milliseconds, emissions in µgCO2e). Energy
was regressed on output tokens across prompt sizes (R² ≥ 0.999); grid intensity is
what their own emissions figures imply. Fitted 2026-10-28.
- **SAME_FAMILY** — measured for `glm-5.3-flash` and assumed to hold for `glm-5.3`.
An assumption of similarity, not a measurement.
- **ESTIMATED** — the proxy row: an order-of-magnitude figure near the middle of the
measured range, with an EU grid average. It is applied to every provider that does
not disclose impact, **deliberately**, so that a day's total is never quietly
missing models. It is not a number we know.
**No tier is exposed on its own**, but every row now carries a *provenance* read
derived from the measured/estimated token split — see "Provenance in the API"
below. A consumer can tell how much of a day's figure rested on a measurement.
## Provenance in the API
Every row returned by `/admin/metrics/series` and `/broker/metrics` carries the
measured-vs-estimated split, so a consumer can tell how much of a day's figure
rested on a real measurement. Four fields:
| field | meaning |
|---|---|
| `tokens_measured` | output tokens that day attributed to a factor whose `source` is **MEASURED** — a direct provider measurement. |
| `tokens_estimated` | the rest: **SAME_FAMILY** (borrowed from a sibling) and the flat **proxy**. A borrowed or proxied factor is an assumption, so it is **not** counted as measured. |
| `factor_revision` | a short, stable hash of the factor table (`IMPACT_FACTORS` + `IMPACT_PROXY`) in effect when the row was computed. |
| `provenance` | the derived read, below. |
`tokens_measured + tokens_estimated = out_tokens` for any day with tokens. A day
with no output tokens has NULL in both (fail-closed, same rule as energy/carbon).
`provenance` is one of:
- **`measured`** — every token rested on a measured factor.
- **`estimated`** — every token rested on a non-measured factor (borrowed or proxy).
- **`mixed`** — both are present; the day's total is a blend.
- **`none`** — no provenance. This is **either** a day with no output tokens **or**
a row written before these columns existed (older rows keep NULL). It is
deliberately **not** `measured`: an unknown split must never read as a confident
measurement. This is the whole point of the indicator — failure reads as unknown.
`factor_revision` is a deterministic hash, **not a timestamp**: two runs against the
same table produce the same string. It changes if any factor value or source label
changes, or if the matching order changes (order is meaningful — longest prefix
first). It is "what the numbers were computed with", not "what was known then".
### Forward-only, then backfill
The columns are added by an **additive** migration — a guarded
`ALTER TABLE metrics_daily ADD COLUMN …`, the same idiom used when the impact
columns first arrived. On an existing database this is safe: it never errors,
existing rows survive untouched, and they simply keep NULL in the new columns.
Nothing is guessed for history on migration; those rows read as `provenance: "none"`.
To give past rows a real split, run `metrics_snapshot.py --backfill` (or re-run the
affected days). Backfill rewrites each day from the current LiteLLM token split and
the **current** factor table, so it also updates `factor_revision` to today's
revision — a backfilled historical row records the revision used to recompute it,
not the one that was current at the time. Honest for a chart label; not a historical
audit trail.
## Formulas
```
energy_wh = Σ_models ( out_tokens / 1000 × wh_per_1k_out )
co2e_g = Σ_models ( out_tokens / 1000 × wh_per_1k_out / 1000 × gco2e_per_kwh )
└────────────── Wh ──────────────┘ └─ Wh → kWh ─┘
```
Carbon was once understated by exactly 1000× here — a `/1e6` where `/1e3` was
intended — which is why the tripwire below exists.
## NULL, never zero
`impact_for()` returns an all-NULL impact block for a day with no measured tokens,
and the row is written with NULL energy and carbon. It never writes `0.0`:
> a zero reads as "the co-op used no energy", which is a claim we cannot support, and
> it would survive into a chart as a fact.
The first backfill shipped exactly that bug — it summed the wrong column, every model
totalled zero, and every day in history claimed to have used no energy.
A NULL day renders as a **bare gap in the charts, with nothing explaining it.** That is
deliberate: the surfaces carry no caveat text. Accepted knowingly.
The same fail-closed rule applies to every metric in the snapshot, not only energy:
an unreadable source (Listmonk, Matrix, LiteLLM) yields NULL for that metric and
prints to the log, rather than a number that looks real.
## The tripwire
After summing, `impact_for()` computes the grid intensity its own mix implies and
compares it against a plausible band:
```
implied = co2e_g / energy_wh × 1000 # gCO2e per kWh
if not (5.0 <= implied <= 500.0):
warn "suspect a unit error before trusting these numbers"
```
It warns; it never alters the numbers or suppresses the row. Its purpose is narrow and
earned: the 1000× carbon error kept the energy column plausible, so nothing looked
wrong, and a silent error of that kind would otherwise be found by a member rather
than by us.
## Schedule and backfill
- **`metrics_snapshot` runs daily at 03:15**, from Cloudron's scheduler addon
(`CloudronManifest.json` → `addons.scheduler`), via `/app/code/metrics_snapshot.py`.
It runs after `membership_sweep` (03:00) and `rag_refresh` (03:30).
- It writes **one row per day** into the `metrics_daily` table, in the same SQLite
database as the members table (`members.db`). Columns: `day`, `members_active`,
`members_total`, `members_new`, `newsletter_subs`, `matrix_space_members`,
`spend_usd`, `requests`, `out_tokens`, `energy_wh`, `co2e_g`, `tokens_measured`,
`tokens_estimated`, `factor_revision`, `recorded_at`.
- **Each 03:15 run completes YESTERDAY, then records today live.** The day that
just ended is rewritten with its FULL spend/requests/tokens/impact aggregates
(usage columns only — the membership columns are point-in-time measurements
that are not reconstructible afterwards). Today's row carries the first hours
of live data and is completed by the next run. (Until 2026-11-12 the run
wrote only today's partial and never revisited it, which froze every day at
its first ~3 hours — the November under-count.)
- **`metrics_snapshot.py --backfill` rebuilds history** from the sources and is
idempotent — it rewrites a day rather than duplicating it. It is the tool to run
after changing a factor, and the reason a published chart can move: history is
**rewritten**, not appended to. `--backfill --since YYYY-MM-DD` limits the
rewrite to days from that date and touches ONLY the usage/impact columns, so
a targeted repair of recent days cannot alter the published membership curve.
## What is measured, and what is not
Stated plainly, because a mixed total is easy to over-read:
- **Measured:** GreenPT models — the providers whose API reports impact.
- **Assumed equal to a measurement:** `greenpt/glm-5.3`, from its flash sibling.
- **Estimated:** everything else. Currently that means **all Tinfoil and Regolo
traffic**, which is a real share of co-op usage.
So a day's figure is a blend, and **the split is now recorded per day** —
`tokens_measured` and `tokens_estimated` say how much of the total rested on a
measurement, and the API derives a `provenance` read from them. Before those
columns existed the split was not recorded; such rows carry NULL and read as
`provenance: "none"`. See "Provenance in the API".
One consequence worth knowing: the proxy assumes a 250 gCO2e/kWh grid, while Regolo
runs on 100% renewable energy, so the proxy **overstates** Regolo's carbon. Per-provider
factors are a follow-up; until then, Regolo and Tinfoil figures should be read as upper
bounds rather than measurements.
## Changing the factors
Edit the table in `metrics_snapshot.py` and redeploy — refining a factor is a data
edit, not a code change. Then run `--backfill` if the change should apply to history.
The energy factors are also recorded in `co-op/docs/energy.md` for members, and the two
should not disagree.
+1037
View File
File diff suppressed because it is too large. Load diff
-117
View File
@@ -1,117 +0,0 @@
#!/usr/bin/env python3
"""Nightly docs-RAG refresh — server-side (portal container).
Fetches the co-op docs from the Gitea raw API (public repo, no credentials),
uploads changed files to Open WebUI via the internal network (OWUI_API_KEY,
already in the portal env), attaches them to the shared knowledge collection,
reindexes, and keeps the members group grant intact.
Replaces the bot-hosted refresh script (same logic, no bot dependency).
Silent-ish: prints a one-line summary; exits non-zero on hard failure so the
Cloudron scheduler log captures it.
"""
import json, os, sys, time, hashlib, urllib.request, urllib.error
GITEA_RAW = "https://git.inference.coop/co-op/docs/raw/branch/main/"
OWUI_BASE = os.environ.get("OWUI_BASE", "http://chat:8080")
OWUI_KEY = os.environ.get("OWUI_API_KEY", "")
KB_ID = os.environ.get("DOCS_KNOWLEDGE_ID", "")
GID = "eb348e1a-059a-4a8f-8920-0f73942f6272" # OWUI members group
DOCS = ["README.md", "getting-started.md", "models.md", "api-access.md",
"terms-of-service.md", "privacy-policy.md", "charter.md",
"infrastructure.md", "open-questions.md"]
STATE_PATH = "/app/data/rag_refresh_state.json"
if not OWUI_KEY or not KB_ID:
print("rag_refresh: OWUI_API_KEY / DOCS_KNOWLEDGE_ID not set", file=sys.stderr)
sys.exit(1)
def api(path, body=None, method=None, key=None, base=None, timeout=180):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(
f"{base or OWUI_BASE}{path}", data=data, method=method or ("POST" if data else "GET"),
headers={"Authorization": f"Bearer {key or OWUI_KEY}", "Content-Type": "application/json"})
try:
r = urllib.request.urlopen(req, timeout=timeout)
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
return e.code, e.read().decode()[:200]
def multipart_upload(filename, content):
boundary = "----ragrefresh9x"
part = (f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n'
f"Content-Type: text/markdown\r\n\r\n").encode() + content.encode() + \
f"\r\n--{boundary}--\r\n".encode()
req = urllib.request.Request(
f"{OWUI_BASE}/api/v1/files/", data=part, method="POST",
headers={"Authorization": f"Bearer {OWUI_KEY}",
"Content-Type": f"multipart/form-data; boundary={boundary}"})
r = urllib.request.urlopen(req, timeout=180)
return json.loads(r.read())
def fetch_doc(name):
req = urllib.request.Request(GITEA_RAW + name)
try:
return urllib.request.urlopen(req, timeout=30).read().decode()
except Exception:
return None
state = {}
if os.path.exists(STATE_PATH):
try:
state = json.load(open(STATE_PATH))
except Exception:
state = {}
changed = 0
skipped = 0
for name in DOCS:
content = fetch_doc(name)
if content is None:
print(f"rag_refresh: WARN could not fetch {name}", file=sys.stderr)
continue
newhash = hashlib.sha256(content.encode()).hexdigest()
if state.get(name) == newhash:
skipped += 1
continue
# delete stale file rows with this name, then upload fresh + attach
code, files = api("/api/v1/files/?page=1")
if code == 200 and isinstance(files, dict):
files = files.get("items", []) # OWUI returns {items: [...]}
if code == 200 and isinstance(files, list):
for f in files:
if f.get("filename") == name:
api(f"/api/v1/files/{f['id']}", method="DELETE")
try:
resp = multipart_upload(name, content)
except Exception as e:
print(f"rag_refresh: upload failed for {name}: {e}", file=sys.stderr)
continue
fid = resp.get("id")
# attach can 400 transiently right after upload (file still processing) — retry
code = None
for attempt in range(3):
code, _ = api(f"/api/v1/knowledge/{KB_ID}/file/add", {"file_id": fid})
if code == 200:
break
time.sleep(5 * (attempt + 1))
if code != 200:
print(f"rag_refresh: attach failed for {name}: {code}", file=sys.stderr)
continue
state[name] = newhash
changed += 1
# reindex the KB (chunk copies at attach time go stale otherwise)
if changed:
api("/api/v1/knowledge/reindex", {"knowledge_id": KB_ID}, timeout=300)
# keep the members-group grant intact (guards against grant loss)
api(f"/api/v1/knowledge/{KB_ID}/access/update",
{"access_grants": [{"principal_type": "group", "principal_id": GID, "permission": "read"}]})
json.dump(state, open(STATE_PATH, "w"))
print(f"rag_refresh: changed={changed} skipped={skipped}")
sys.exit(0)
+1
View File
@@ -5,3 +5,4 @@ pydantic==2.9.2
PyJWT==2.9.0
slowapi==0.1.9
psycopg2-binary==2.9.9
cryptography==44.0.2
+49
View File
@@ -0,0 +1,49 @@
#!/bin/sh
# Frequent service-invite sync — run by the Cloudron scheduler addon every
# few minutes.
#
# WHY: a new member is provisioned with an UNACTIVATED Cloudron account, and
# the Loomio/Matrix syncs deliberately skip an unactivated account (never
# invite a half-created one). The member activates later, by following the
# setup link in their welcome email — and until this job existed, the next
# thing to look at them was the 3x/day membership sweep, so a brand-new member
# could sit without forum or Space access for hours.
#
# Calls the portal's own /admin/service-sync endpoint (localhost), which fires
# the same idempotent Loomio + Matrix syncs the sweep runs, but ONLY while some
# member is still awaiting their invites (one SELECT when nobody is).
#
# The ADMIN_TOKEN env var is shared with the main app (the scheduler runs in
# the same launch environment), so we use it to authenticate. Admin auth is a
# header, never a URL token.
#
# Deliberately NOT the full /admin/sweep: that reconciles against Open
# Collective, runs allowance logic and can send member mail. This job must only
# ever send the invites a member is owed.
set -e
if [ -z "$ADMIN_TOKEN" ]; then
echo "service-sync: ADMIN_TOKEN is not set; aborting" >&2
exit 1
fi
python3 - "$ADMIN_TOKEN" <<'PY'
import sys, urllib.request, urllib.error
token = sys.argv[1]
url = "http://127.0.0.1:8000/admin/service-sync"
req = urllib.request.Request(url, method="POST", data=b"", headers={
"Content-Type": "application/json",
"X-Admin-Token": token,
})
try:
with urllib.request.urlopen(req, timeout=300) as resp:
print("service-sync:", resp.read().decode())
except urllib.error.HTTPError as e:
print(f"service-sync: HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"service-sync: request failed: {e}", file=sys.stderr)
sys.exit(1)
PY
+9 -5
View File
@@ -5,19 +5,23 @@
# the portal against the live Open Collective member list: provisions missing
# members, deactivates lapsed members, and syncs Loomio.
#
# The WEBHOOK_TOKEN env var is shared with the main app (scheduler runs in the
# same launch environment), so we use it to authenticate the call.
# The ADMIN_TOKEN env var is shared with the main app (scheduler runs in the
# same launch environment), so we use it to authenticate the call. Admin auth is
# a header, never a URL token (security fix 2026-10-27). The WEBHOOK_TOKEN
# fallback was removed when the cutover completed (ADMIN_TOKEN_LEGACY=0): the
# legacy token now gets 403 on /admin/*, so falling back to it would turn
# "ADMIN_TOKEN unset" into a confusing mid-run 403 instead of a clear abort.
#
# Uses Python (guaranteed present in the base image) rather than curl.
set -e
if [ -z "$WEBHOOK_TOKEN" ]; then
echo "sweep: WEBHOOK_TOKEN not set; aborting" >&2
if [ -z "$ADMIN_TOKEN" ]; then
echo "sweep: ADMIN_TOKEN is not set; aborting" >&2
exit 1
fi
python3 - "$WEBHOOK_TOKEN" <<'PY'
python3 - "$ADMIN_TOKEN" <<'PY'
import sys, urllib.request, urllib.error
token = sys.argv[1]
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Regression tests for app.main.allowance_lapse_decision (grace/deactivation).
Self-contained and runnable:
* from the repo root: python3 tests/test_allowance_lapse.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_allowance_lapse.py
(the container has the app's own dependencies; the host usually does not)
WHY THIS EXISTS
Deactivation is gated OFF (ALLOWANCE_DEACTIVATE=off) and the flag must stay
off until the preview is trusted. That makes the live preview legitimately
show ZERO past-grace members right after a reminder, so this file proves the
decision logic on a SYNTHETIC reminder time instead of waiting a week — and
without altering any real member's rows.
The decision is a pure function (no DB, no network, no clock), so a past
reminder, a grace boundary and the "armed" case are all exercised directly:
- reminder 10 days ago, NOT authorised -> ("would_deactivate", deadline)
[the preview this change adds]
- reminder 3 days ago (inside grace) -> ("in_grace", None)
- reminder exactly at the grace edge -> ("would_deactivate", deadline)
- reminder one second inside the edge -> ("in_grace", None)
- reminder 10 days ago, AUTHORISED -> ("deactivated", deadline)
[the real path, unchanged: needs policy=on AND deactivate=on]
- no reminder at all -> ("in_grace", None)
"""
import os
import sys
from datetime import datetime, timedelta, timezone
# Locate the app package: explicit env, the deployed path, or the repo root.
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import allowance_lapse_decision # noqa: E402
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=timezone.utc)
GRACE = 7.0
# (name, reminder_sent_at, acting, expected_decision, expected_deadline)
CASES = [
("reminder 10d ago, not authorised -> would_deactivate (preview)",
NOW - timedelta(days=10), False, "would_deactivate", NOW - timedelta(days=10) + timedelta(days=7)),
("reminder 3d ago (inside grace) -> in_grace",
NOW - timedelta(days=3), False, "in_grace", None),
("reminder exactly 7d ago (at the edge) -> would_deactivate",
NOW - timedelta(days=7), False, "would_deactivate", NOW),
("reminder 6d23h ago (one hour inside grace) -> in_grace",
NOW - timedelta(days=6, hours=23), False, "in_grace", None),
("reminder 10d ago, AUTHORISED -> deactivated (real path)",
NOW - timedelta(days=10), True, "deactivated", NOW - timedelta(days=10) + timedelta(days=7)),
("no reminder ever sent -> in_grace",
None, False, "in_grace", None),
]
failures = 0
for name, sent_at, acting, expect_dec, expect_dl in CASES:
decision, deadline = allowance_lapse_decision(sent_at, NOW, GRACE, acting)
dl_ok = (deadline == expect_dl)
ok = (decision == expect_dec) and dl_ok
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}\n"
f" decision={decision} (expected {expect_dec}) "
f"deadline={deadline} (expected {expect_dl}) acting={acting}")
print(f"\n{len(CASES) - failures}/{len(CASES)} passed")
sys.exit(1 if failures else 0)
+119
View File
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Regression tests for the allowance-shortfall derivation (OC billing alignment).
Runnable:
* from the repo root: python3 tests/test_allowance_shortfall.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_allowance_shortfall.py
(the container has the app's own dependencies; the host usually does not)
WHY THIS EXISTS
The shortfall credit must be derived FROM DATA and must never be paid twice.
`derive_shortfalls` is pure (no DB, no network, no clock), so the arithmetic,
the per-order boundary, the month-length boundary and the idempotence key are
all exercised directly on synthetic charge ladders.
Covered:
- a truncated first cycle -> one credit, pro-rated to the days lost
- a gap of exactly a full month -> NOT truncated (boundary)
- a gap LONGER than a full month -> NOT truncated (OC deferred a charge)
- credits are NEVER rounded -> 4.5 and 1.5 come out exact
- two orders are judged separately -> a cross-subscription pair is not
mistaken for one truncated cycle
- the reference is the EARLY charge -> it is the idempotence key
"""
import os
import sys
# Locate the app package: explicit env, the deployed path, or the repo root.
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from datetime import datetime, timezone # noqa: E402
from app.main import ( # noqa: E402
derive_shortfalls, shortfall_reason, _usd, SHORTFALL_REMEDIATED,
)
def dt(s):
return datetime.fromisoformat(s + "T00:00:00+00:00")
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
# --- one truncated first cycle: joined/charged 11 Sep, re-aligned to 2 Oct (21d)
recs = [{"slug": "member-a", "order_id": "or_1",
"charges": [(dt("2026-09-11"), "tx_a1"), (dt("2026-10-02"), "tx_a2")]}]
got = derive_shortfalls(recs, budget=15.0)
check("truncated first cycle -> one credit",
[(g["prev"], g["cur"], g["gap_days"], g["days_lost"], g["amount"], g["reference"]) for g in got],
[("2026-09-11", "2026-10-02", 21, 9, 4.5, "tx_a2")])
# --- boundary: a gap of exactly 30 days is a full month -> nothing
recs = [{"slug": "member-b", "order_id": "or_2",
"charges": [(dt("2026-10-02"), "tx_b1"), (dt("2026-11-01"), "tx_b2")]}]
check("gap == full month -> no credit", derive_shortfalls(recs, budget=15.0), [])
# --- a gap LONGER than a month (OC deferred a charge) -> nothing
recs = [{"slug": "member-c", "order_id": "or_3",
"charges": [(dt("2026-09-28"), "tx_c1"), (dt("2026-11-02"), "tx_c2")]}]
check("gap > full month -> no credit", derive_shortfalls(recs, budget=15.0), [])
# --- no rounding: 24-day gap -> 6 days lost -> exact 3.0; 27-day -> 1.5
recs = [{"slug": "member-d", "order_id": "or_4",
"charges": [(dt("2026-10-09"), "tx_d1"), (dt("2026-11-02"), "tx_d2")]}]
check("exact pro-rate, no rounding", [g["amount"] for g in derive_shortfalls(recs, 15.0)], [3.0])
recs = [{"slug": "member-e", "order_id": "or_5",
"charges": [(dt("2026-10-06"), "tx_e1"), (dt("2026-11-02"), "tx_e2")]}]
check("half-dollar stays exact", [g["amount"] for g in derive_shortfalls(recs, 15.0)], [1.5])
# --- per-order boundary: two orders six days apart are NOT one truncated cycle
recs = [
{"slug": "member-f", "order_id": "or_6a", "charges": [(dt("2026-10-16"), "tx_f1")]},
{"slug": "member-f", "order_id": "or_6b", "charges": [(dt("2026-10-22"), "tx_f2")]},
]
check("two subscriptions are judged separately (no cross-order pair)",
derive_shortfalls(recs, budget=15.0), [])
# --- a later (non-first) cycle can be truncated too
recs = [{"slug": "member-g", "order_id": "or_7",
"charges": [(dt("2026-09-02"), "tx_g1"), (dt("2026-10-02"), "tx_g2"),
(dt("2026-10-20"), "tx_g3")]}]
check("a later cycle is caught too",
[(g["prev"], g["cur"], g["reference"]) for g in derive_shortfalls(recs, 15.0)],
[("2026-10-02", "2026-10-20", "tx_g3")])
# --- the reference is the EARLY charge (the idempotence key)
recs = [{"slug": "member-h", "order_id": "or_8",
"charges": [(dt("2026-10-15"), "tx_h1"), (dt("2026-11-02"), "tx_h2")]}]
check("reference is the truncating (second) charge",
[g["reference"] for g in derive_shortfalls(recs, 15.0)], ["tx_h2"])
# --- formatting and reason helpers
check("_usd keeps exact amounts", [_usd(2.0), _usd(4.5), _usd(1.5)], ["$2", "$4.5", "$1.5"])
check("reason names the cycle",
shortfall_reason("2026-10-07", "2026-11-02"),
"allowance shortfall, truncated paid cycle 2026-10-07→2026-11-02 (OC billing alignment)")
# --- the manual-remediation exclusion is keyed on the charge ref alone
# --- (no member PII in this public repo; identity/timeline live in ops docs;
# --- the OC tx id IS the reference key and was approved as such — see the
# --- commit that restored it to match the deployed image)
check("remediated charge excluded by reference",
"tx_Kr6n3rW577OSjr2bIt5IC" in SHORTFALL_REMEDIATED, True)
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
sys.exit(1 if failures else 0)
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Regression test: hostile tokens must be a clean 401/403, never a 500/503.
WHY THIS EXISTS
On 2026-11-20 a scanner (192.238.226.25) POSTed to the Open Collective webhook
URL with a path token containing a non-ASCII character. `secrets.compare_digest`
REFUSES str containing non-ASCII with
TypeError: comparing strings with non-ASCII characters is not supported
so the auth check crashed before rejecting the request. The wrapper turned that
into a 503, the portal recorded it as an OC delivery that might have cost a
member money, and the sweep emailed info@ a false money-critical alarm. The
same crash produced 500s on /admin/* and /broker/* from the same scanner.
The guards proven here:
COMPARISON
1. `_secret_eq` compares arbitrary UTF-8 input and returns a bool; the raw
`compare_digest` is proven to raise, so the regression is real.
2. Empty never matches (a missing secret fails closed).
STATUS CODES
3. A webhook token with non-ASCII chars answers 401 — not 503 — and does not
ask OC to retry.
4. Non-ASCII in the admin, broker and sync-token headers answers 401/403,
not 500.
ORIGIN RECORDING
5. The refused delivery is recorded with its source address and user-agent.
6. The failure report names the source in the email body and says a
non-OC source is a probe, not a purchase.
Runnable: python3 tests/test_auth_probe_hardening.py (from the repo root)
"""
import asyncio
import os
import secrets
import sys
import tempfile
import httpx
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["WEBHOOK_TOKEN"] = "test-webhook-token"
os.environ["ADMIN_TOKEN"] = "test-admin-token"
os.environ["ADMIN_TOKEN_LEGACY"] = "0"
os.environ["BROKER_SECRET"] = "test-broker-secret"
os.environ["LIBRECHAT_SYNC_TOKEN"] = "test-sync-token"
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m # noqa: E402
REAL_ASYNC_CLIENT = httpx.AsyncClient
UA = "probe-test/1.0"
NON_ASCII = "tøken-ø"
results = []
def check(name, ok):
results.append((name, ok))
SENT = []
def fake_send(to, subject, body, *a, **k):
SENT.append({"to": to, "subject": subject, "body": body})
async def main():
m.get_db().close() # create + migrate the fixture schema
# --- 1. The raw stdlib call really does raise: this is the bug. ---
raised = False
try:
secrets.compare_digest(NON_ASCII, NON_ASCII)
except TypeError:
raised = True
check("baseline: secrets.compare_digest raises on non-ASCII str", raised)
check("helper: identical ASCII secrets match", m._secret_eq("abc", "abc") is True)
check("helper: identical non-ASCII secrets match", m._secret_eq(NON_ASCII, NON_ASCII) is True)
check("helper: different non-ASCII secrets do not match",
m._secret_eq(NON_ASCII, "test-webhook-token") is False)
check("helper: empty never matches (fail closed)",
m._secret_eq("", "") is False and m._secret_eq("x", "") is False)
transport = httpx.ASGITransport(app=m.app, client=("192.238.226.25", 44321))
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
# --- 3. Hostile webhook token: 401, not 503. ---
r = await c.post(f"/webhook/opencollective/{NON_ASCII}",
json={"type": "order.processed", "data": {}},
headers={"user-agent": UA})
check(f"webhook: non-ASCII token answers 401 (got {r.status_code})",
r.status_code == 401)
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
check("webhook: the refusal does NOT ask OC to retry", body.get("retry") is not True)
# --- 5. The refusal is recorded with source + user-agent. ---
conn = m.get_db()
row = conn.execute(
"SELECT status, detail, ip, user_agent FROM webhook_failures "
"ORDER BY id DESC LIMIT 1").fetchone()
conn.close()
check(f"record: the 401 is stored (got {row})", row is not None and row[0] == 401)
check("record: the row names the invalid token, not an exception",
row is not None and row[1] == "Invalid webhook token")
check(f"record: the source address is stored (got {row and row[2]!r})",
bool(row and row[2] == "192.238.226.25"))
check(f"record: the user-agent is stored (got {row and row[3]!r})",
bool(row and row[3] == UA))
# --- 4. Hostile header tokens: auth rejection, never 500. ---
for label, path, header in (
("admin", "/admin/aliases", "x-admin-token"),
("broker", "/broker/keys", "x-broker-secret"),
("sync", "/admin/librechat/keys", "x-sync-token"),
):
# httpx encodes str header values as ASCII and refuses non-ASCII;
# send the UTF-8 bytes, which is what a hostile client can send.
r = await c.get(path, headers=[
(header.encode("ascii"), NON_ASCII.encode("utf-8")),
(b"user-agent", UA.encode("utf-8")),
])
check(f"{label}: non-ASCII header token answers 401/403, not 500 "
f"(got {r.status_code})", r.status_code in (401, 403))
# --- 6. The report names the source and calls a non-OC source a probe. ---
SENT.clear()
m.send_email = fake_send
rep = m.webhook_failure_report()
check(f"report: reported the refused delivery (got {rep.get('status')})",
rep.get("status") == "reported")
text = SENT[0]["body"] if SENT else ""
check(f"report: the body names the source (got {text[:120]!r})",
"[source " in text)
check("report: the body distinguishes a probe from an OC purchase",
"probe, not a purchase" in text)
check("report: the body still explains the token-mismatch case",
"WEBHOOK_TOKEN" in text)
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)
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Regression tests for the OC-balance self-heal (the Nov 2026 chart hole).
Incident: the 03:15 snapshot on 2026-11-12 DID record oc_balance_usd=1357.39,
but a repair backfill run hours later rewrote the day through backfill()'s
full-row upsert — whose row dict carries no balance key — and ON CONFLICT wrote
NULL over it. Nothing revisited a day's balance afterwards, so the hole was
permanent and the money chart broke mid-line.
Fixes under test here:
* upsert() never erases a balance it did not measure (COALESCE on conflict);
* the nightly snapshot heals any RECENT day with a missing balance from OC's
transaction ledger (balance column ONLY — membership/usage never touched);
* days before the series' first recorded balance stay NULL by design;
* an OC failure is fail-soft: hole stays, next night retries, nothing raises.
Runnable:
* from the repo root: python3 tests/test_balance_backfill.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 tests/test_balance_backfill.py
"""
import datetime as dt
import os
import sqlite3
import sys
import tempfile
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="balance-heal-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE metrics_snapshot is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"),
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "metrics_snapshot.py")):
sys.path.insert(0, _cand)
break
import metrics_snapshot as ms # noqa: E402
TODAY = ms.today()
YESTERDAY = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=1)).isoformat()
DAY_MINUS2 = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=2)).isoformat()
DAY_MINUS5 = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=5)).isoformat()
FAILED = []
def check(name, cond, detail=""):
if cond:
print(f" ok {name}")
else:
print(f" FAIL {name} {detail}")
FAILED.append(name)
def read_row(day):
conn = sqlite3.connect(_TEST_DB)
try:
conn.row_factory = sqlite3.Row
return conn.execute("SELECT * FROM metrics_daily WHERE day = ?", (day,)).fetchone()
finally:
conn.close()
def wipe():
ms.connect().close() # ensure the table exists (schema init)
conn = sqlite3.connect(_TEST_DB)
conn.execute("DELETE FROM metrics_daily")
conn.commit()
conn.close()
def stub_sources(**kw):
"""Replace every network source with fixed in-memory data."""
ms.from_sqlite = lambda: {"active": kw.get("active", 40), "total": kw.get("total", 71),
"joins": list(kw.get("joins", []))}
ms.from_listmonk = lambda: kw.get("subs", 71)
ms.listmonk_joins = lambda: list(kw.get("joins", []))
ms.from_matrix = lambda: kw.get("matrix", 65)
ms.oc_collective_balance = lambda: kw.get("balance", 123.45)
ms.spend_by_day = lambda since=None: dict(kw.get("spend", {}))
ms.operator_spend_by_day = lambda since=None: None if kw.get("op_spend") is None else dict(kw.get("op_spend") or {})
ms.tokens_by_day_model = lambda since=None: {k: dict(v) for k, v in (kw.get("tokens") or {}).items()}
def seed(day, **cols):
ms.upsert(day, {"spend_usd": None, "requests": None, "out_tokens": None,
"energy_wh": None, "co2e_g": None, "tokens_measured": None,
"tokens_estimated": None, "factor_revision": None, **cols})
# ----------------------------------------------------------------------
print("1. REGRESSION: a full-row rewrite without a balance never erases one "
"(the 2026-11-12 incident)")
wipe()
# The day as the 03:15 snapshot wrote it: membership + usage + a live balance.
seed(TODAY, spend_usd=3.38, requests=674, members_active=113, members_total=113,
members_new=2, newsletter_subs=122, matrix_space_members=36, oc_balance_usd=1357.39)
# Full backfill (the shape the 2026-11-12 18:42 repair ran): its today-branch
# rewrites the day with a dict that has NO oc_balance_usd key.
stub_sources(joins=["2026-11-01"], spend={TODAY: (3.38, 674)}, op_spend={TODAY: 0.9},
tokens={TODAY: {"greenpt/glm-5.3-flash": 379040}})
ms.backfill()
t = read_row(TODAY)
check("backfill rewrote the day (test is live)", t["members_total"] == 71, t["members_total"])
check("the recorded balance SURVIVED the rewrite", t["oc_balance_usd"] == 1357.39,
t["oc_balance_usd"])
print("2. snapshot() with a failed OC read keeps a balance recorded earlier that day")
wipe()
seed(TODAY, spend_usd=0.5, requests=10, members_active=40, members_total=71,
oc_balance_usd=1357.39)
stub_sources(spend={YESTERDAY: (5.0, 100), TODAY: (0.7, 20)}, op_spend=None, tokens={},
balance=None)
ms.snapshot()
t = read_row(TODAY)
check("today's row still refreshed (spend updated)", t["spend_usd"] == 0.7, t["spend_usd"])
check("earlier balance kept when the fresh read failed", t["oc_balance_usd"] == 1357.39,
t["oc_balance_usd"])
print("3. self-heal reconstructs a missing day from the ledger — balance column ONLY")
wipe()
seed(DAY_MINUS2, spend_usd=1.0, requests=50, members_active=39, members_total=70,
oc_balance_usd=1200.0)
# The hole: yesterday's row exists, everything but the balance.
seed(YESTERDAY, spend_usd=2.0, requests=60, members_active=39, members_total=70,
newsletter_subs=71, matrix_space_members=65)
seed(TODAY, spend_usd=0.5, requests=10, members_active=40, members_total=71,
oc_balance_usd=1470.44)
READ_AT = TODAY + "T03:15:58.123Z"
# Ledger after the two cutoffs: yesterday +73.05, day-before +113.05 (all days
# cumulative toward the anchor). Signed as OC stores them: CREDIT +, DEBIT -.
ledger = [
{"createdAt": DAY_MINUS2 + "T10:00:00.000Z", "type": "CREDIT", "amount": {"valueInCents": 5000}},
{"createdAt": DAY_MINUS2 + "T10:00:00.200Z", "type": "DEBIT", "amount": {"valueInCents": -500}},
{"createdAt": YESTERDAY + "T12:00:00.000Z", "type": "CREDIT", "amount": {"valueInCents": 7805}},
{"createdAt": READ_AT, "type": "DEBIT", "amount": {"valueInCents": -1000}}, # exactly at read_at: in the (C, read_at] window
]
ms.oc_fetch_transactions = lambda date_from, date_to: list(ledger)
ms.heal_missing_balances(1470.44, READ_AT)
y = read_row(YESTERDAY)
d2 = read_row(DAY_MINUS2)
t = read_row(TODAY)
check("hole filled: yesterday = anchor - net(yesterday 03:15 .. read_at)",
y["oc_balance_usd"] == 1470.44 - (7805 - 1000) / 100.0, y["oc_balance_usd"])
check("existing days untouched by the heal", d2["oc_balance_usd"] == 1200.0 and t["oc_balance_usd"] == 1470.44)
check("membership columns of the healed day intact",
y["members_active"] == 39 and y["members_total"] == 70 and y["newsletter_subs"] == 71)
check("usage columns of the healed day intact", y["spend_usd"] == 2.0 and y["requests"] == 60)
print("4. pre-history stays NULL — a hole BEFORE the first recorded day is not invented")
wipe()
seed(DAY_MINUS5, spend_usd=1.0, requests=5) # before the series' first balance
seed(DAY_MINUS2, spend_usd=1.0, requests=5, oc_balance_usd=1200.0)
seed(TODAY, oc_balance_usd=1470.44)
ms.oc_fetch_transactions = lambda date_from, date_to: []
ms.heal_missing_balances(1470.44, READ_AT)
d5 = read_row(DAY_MINUS5)
check("day before the first balance stays NULL (gap by design)", d5["oc_balance_usd"] is None,
d5["oc_balance_usd"])
print("5. OC ledger failure is fail-soft: hole stays, nothing raises, no zero written")
wipe()
seed(DAY_MINUS2, oc_balance_usd=1200.0)
seed(YESTERDAY, spend_usd=2.0, members_active=39, oc_balance_usd=None)
seed(TODAY, oc_balance_usd=1470.44)
def _boom(date_from, date_to):
raise RuntimeError("OC unreachable (test)")
ms.oc_fetch_transactions = _boom
ms.heal_missing_balances(1470.44, READ_AT) # must not raise
y = read_row(YESTERDAY)
check("hole left NULL for the next night", y["oc_balance_usd"] is None, y["oc_balance_usd"])
check("no zero written on failure", y["oc_balance_usd"] != 0.0)
print("6. write_balance on a day with NO row inserts balance + NULL everything else")
wipe()
ms.write_balance(YESTERDAY, 1357.39)
y = read_row(YESTERDAY)
check("balance written", y["oc_balance_usd"] == 1357.39)
check("membership/usage columns NULL (fail-closed, never zero)",
y["members_active"] is None and y["spend_usd"] is None and y["requests"] is None)
print("7. anchor=None (OC read failed this run) heals nothing")
wipe()
seed(DAY_MINUS2, oc_balance_usd=1200.0)
seed(YESTERDAY, oc_balance_usd=None)
seed(TODAY, oc_balance_usd=1470.44)
ms.oc_fetch_transactions = lambda date_from, date_to: list(ledger)
ms.heal_missing_balances(None, READ_AT)
y = read_row(YESTERDAY)
check("no heal without an anchor balance", y["oc_balance_usd"] is None, y["oc_balance_usd"])
print()
if FAILED:
print(f"FAILED: {len(FAILED)} check(s): {FAILED}")
sys.exit(1)
print("ALL CHECKS PASSED")
+196
View File
@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Regression tests for the per-member daily usage series (Nov 2026).
The member dashboard's usage chart needs per-day spend/requests for the
signed-in member, bounded by the days parameter. /broker/usage now carries a
`daily` series (additive — every existing field is untouched, so older
dashboards keep working), built by member_daily_usage (DB path) or
daily_series_from_rows (HTTP fallback). These tests pin:
1. the route->handler table for /broker/usage (a decorator landing on the
wrong handler is invisible to every check except a request);
2. the DB path's SQL: day convention matches the co-op daily series
(to_char("startTime", 'YYYY-MM-DD')), the window filter goes on the
column DIRECTLY (a COALESCE with '' on a timestamp column was the
silent-empty-window bug in the model leaderboard), and requests excludes
failed attempts;
3. daily_series_from_rows: team filtering happens BEFORE it is called, rows
without a parseable day are skipped, spend sums failures too, requests
does not, output is day-ascending;
4. broker_get_usage's response contract: `daily` present and fail-soft
(a daily-query failure degrades to [], never an error).
Runnable: python3 tests/test_broker_usage_daily.py
"""
import asyncio
import os
import re
import sys
import tempfile
from pathlib import Path
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="usage-daily-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
ROOT = Path(__file__).resolve().parent.parent
for _cand in (os.environ.get("PORTAL_CODE_DIR"),
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
ROOT = Path(_cand)
break
import app.main as portal # noqa: E402
FAILED = []
def check(name, cond, detail=""):
if cond:
print(f" ok {name}")
else:
print(f" FAIL {name} {detail}")
FAILED.append(name)
# --- 1. route -> handler table (touched route AND its neighbours) ------------
src = (ROOT / "app" / "main.py").read_text()
def handler_for(path_literal):
m = re.search(
r'@app\.get\("' + re.escape(path_literal) + r'"\)\n(?:@[^\n]+\n)*async def (\w+)',
src,
)
return m.group(1) if m else None
check("/broker/usage -> broker_usage", handler_for("/broker/usage") == "broker_usage",
f"got {handler_for('/broker/usage')}")
check("/broker/metrics -> broker_metrics", handler_for("/broker/metrics") == "broker_metrics",
f"got {handler_for('/broker/metrics')}")
check("/broker/keys exists", handler_for("/broker/keys") is not None)
# --- 2. member_daily_usage SQL ------------------------------------------------
captured = {}
class _Cur:
def __init__(self, rows):
self._rows = rows
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def execute(self, sql, params):
captured["sql"] = sql
captured["params"] = list(params)
def fetchall(self):
return [("2026-11-10", 0.5, 3), ("2026-11-11", 1.25, 5)]
class _Conn:
def __init__(self, rows):
self._rows = rows
def cursor(self):
return _Cur(self._rows)
def close(self):
pass
orig_db_ready = portal.litellm_db_ready
orig_pg = portal._pg_connect
portal.litellm_db_ready = lambda: True
portal._pg_connect = lambda: _Conn(None)
try:
out = portal.member_daily_usage(days=90, team_id="team-abc")
sql = re.sub(r"\s+", " ", captured["sql"])
check("day convention matches the co-op series",
"to_char(\"startTime\", 'YYYY-MM-DD')" in sql, sql[:120])
check("window filter on the column directly",
'"startTime" >= %s' in sql
and "COALESCE" not in sql.split("WHERE", 1)[-1], sql[:200])
check("failure rows excluded from requests",
"COUNT(*) FILTER (WHERE status IS DISTINCT FROM 'failure')" in sql)
check("team filter bound as parameter", captured["params"][-1] == "team-abc",
f"params={captured['params']}")
check("rows mapped to day/spend/requests",
out == [{"day": "2026-11-10", "spend": 0.5, "requests": 3},
{"day": "2026-11-11", "spend": 1.25, "requests": 5}], str(out))
# days=0 (no param) -> no window filter at all (backward-compatible default)
portal.member_daily_usage(days=0, team_id="team-abc")
check("days=0 means all time (no window predicate)",
'"startTime" >=' not in captured["sql"])
finally:
portal.litellm_db_ready = orig_db_ready
portal._pg_connect = orig_pg
# DB unconfigured must raise RuntimeError (the caller degrades to an empty
# series) — with the real litellm_db_ready restored and no stub.
db_ready_now = portal.litellm_db_ready()
if db_ready_now:
# A live DB on this host: re-stub to the unconfigured state for this check.
portal.litellm_db_ready = lambda: False
try:
try:
portal.member_daily_usage(days=30, team_id="t")
check("DB unconfigured raises RuntimeError", False, "no raise")
except RuntimeError:
check("DB unconfigured raises RuntimeError", True)
except Exception as e:
check("DB unconfigured raises RuntimeError", False, f"raised {type(e).__name__}: {e}")
finally:
portal.litellm_db_ready = orig_db_ready
else:
try:
portal.member_daily_usage(days=30, team_id="t")
check("DB unconfigured raises RuntimeError", False, "no raise")
except RuntimeError:
check("DB unconfigured raises RuntimeError", True)
except Exception as e:
check("DB unconfigured raises RuntimeError", False, f"raised {type(e).__name__}: {e}")
# --- 3. daily_series_from_rows ------------------------------------------------
rows = [
{"startTime": "2026-11-10 08:15:00+00", "spend": 0.10, "status": "success"},
{"startTime": "2026-11-10 09:00:00+00", "spend": 0.20, "status": "failure"},
{"startTime": "2026-11-11 00:05:00+00", "spend": 0.30, "status": "success"},
{"startTime": "", "spend": 9.99, "status": "success"}, # unparseable day: skipped
]
out = portal.daily_series_from_rows(rows)
check("fallback series: spend sums failures, requests does not",
out == [{"day": "2026-11-10", "spend": 0.3, "requests": 1},
{"day": "2026-11-11", "spend": 0.3, "requests": 1}], str(out))
check("fallback series ascending by day",
[r["day"] for r in out] == sorted(r["day"] for r in out))
check("fallback series on empty/None input", portal.daily_series_from_rows(None) == []
and portal.daily_series_from_rows([]) == [])
# Calendar fill: a day with no usage rows inside the measured span becomes an
# explicit zero (measured), so chart x-spacing is true; days outside the span
# are never invented.
gappy = portal.daily_series_from_rows([
{"startTime": "2026-11-08 10:00:00+00", "spend": 1.0, "status": "success"},
{"startTime": "2026-11-11 10:00:00+00", "spend": 2.0, "status": "success"},
])
check("calendar fill: interior zero days explicit, ends respected",
[r["day"] for r in gappy] == ["2026-11-08", "2026-11-09", "2026-11-10", "2026-11-11"]
and gappy[1] == {"day": "2026-11-09", "spend": 0.0, "requests": 0}
and gappy[0]["spend"] == 1.0 and gappy[3]["spend"] == 2.0, str(gappy))
# --- 4. broker_get_usage response contract ------------------------------------
check("DB path returns 'daily' key (source contract)",
'"daily": daily' in src)
check("daily query is fail-soft in the DB path",
re.search(r"daily usage query failed.*?\n\s*daily = \[\]", src, re.S) is not None)
print()
if FAILED:
print(f"FAILED: {len(FAILED)} check(s): " + ", ".join(FAILED))
sys.exit(1)
print("broker usage daily series: OK")
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Regression test: ONE definition of the co-op's all-time spend.
WHY THIS EXISTS
On 2026-11-13 the panel's card said $941.37 and the member dashboard's said
$900.51 — the same claim, two numbers. The panel used the portal's per-team
query; the dashboard summed the chart series IN THE BROWSER, which disagrees
with the server whenever a row is null, capped or stale. coop_spend_totals()
is now the single source, exposed to the panel's boot payload, the money
payload and the broker's metrics.
The split has to be the same split on every surface, and a failure to compute
it must NEVER look like "$0 spent": the safe wrapper returns {} so callers
omit the key instead of printing a zero that reads as fact.
"""
import pathlib
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
import app.main as m # noqa: E402
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
class FakeCursor:
def __init__(self, rows):
self._rows = rows
def execute(self, *a, **k):
pass
def fetchall(self):
return self._rows
def __enter__(self):
return self
def __exit__(self, *a):
return False
class FakeConn:
def __init__(self, rows):
self._rows = rows
def cursor(self):
return FakeCursor(self._rows)
def close(self):
pass
ROWS = [
("member:alice@example.org", 10.005),
("member:bob@example.org", 5.005),
("agent:infrastructure-bot", 1.5),
("sandbox:throwaway", 0.02),
("", 1.07), # spend rows with no team at all
]
real_ready, real_connect = m.litellm_db_ready, m._pg_connect
try:
m.litellm_db_ready = lambda: True
m._pg_connect = lambda: FakeConn(ROWS)
t = m.coop_spend_totals()
print("1. the split adds up and covers every row")
check(t["member_all_time_spend"] == 15.01,
f"member side is the member: teams ($10.005 + $5.005 -> 15.01, got {t['member_all_time_spend']})")
check(t["own_all_time_spend"] == 2.59,
f"own side is everything else: agents, sandboxes, unattributed (got {t['own_all_time_spend']})")
check(t["own_unattributed_spend"] == 1.07,
f"rows that join to no team alias are named, not left as a silent remainder (got {t['own_unattributed_spend']})")
check(t["own_unattributed_spend"] <= t["own_all_time_spend"],
"unattributed is a part of own, never added on top of the total")
check(t["spend_all_time"] == round(t["member_all_time_spend"] + t["own_all_time_spend"], 2),
"total == member + own, so no dollar is counted twice or dropped")
check(t["spend_all_time"] == round(sum(r[1] for r in ROWS), 2),
f"total is every SpendLogs row ({round(sum(r[1] for r in ROWS), 2)}), the same universe the money chart sums")
print("2. a failure to compute must not look like $0")
def boom():
raise RuntimeError("LiteLLM DB credentials not configured")
m._pg_connect = boom
check(m._coop_spend_totals_safe() == {},
"the safe wrapper returns {} so callers omit the key instead of showing a fake zero")
m.litellm_db_ready = lambda: False
check(m._coop_spend_totals_safe() == {},
"and it degrades the same way when the DB is simply not configured")
finally:
m.litellm_db_ready, m._pg_connect = real_ready, real_connect
print()
if FAILS:
print(f"coop spend totals: {len(FAILS)} FAILURE(S)")
sys.exit(1)
print("coop spend totals: OK — one definition, one number, no fake zeros")
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Regression tests for credit cycle close (issue #12).
Runnable:
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_credit_cycle_close.py
* from the repo root, on a host that has the app's dependencies
WHY THIS EXISTS
LiteLLM zeroes a team's `spend` at budget_reset_at and leaves max_budget
alone, and nothing ever reduced `credit_balance`. Result: a member who bought
a $50 pack and spent it got the $50 back at the next monthly reset — the
allowance returned to $65 instead of $15, forever. Covered here:
- the cap is allowance + credits STILL AVAILABLE (drawn in closed cycles)
- spend inside the CURRENT cycle never shrinks the cap (the inversion bug)
- closing a cycle draws the overage once, and a replay draws nothing
- a draw is capped by the credits actually available
- the issue's worked example end-to-end
"""
import os
import sqlite3
import sys
import tempfile
from datetime import datetime, timezone
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditclose-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import ( # noqa: E402
_prev_month, add_credits, apply_cycle_draw, compute_max_budget,
cycle_start_for_anchor_day, get_credit_balance, get_credits_drawn, get_db,
)
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
def close(a, b):
return round(float(a), 6) == round(float(b), 6)
def check_near(name, got, want):
global failures
ok = close(got, want)
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
# --- cycle boundary math ---------------------------------------------------
check("_prev_month steps back across a year boundary",
_prev_month(datetime(2026, 1, 1, tzinfo=timezone.utc)).isoformat(),
datetime(2025, 12, 1, tzinfo=timezone.utc).isoformat())
check("cycle_start_for_anchor_day is the last occurrence at/before now",
cycle_start_for_anchor_day(28, datetime(2026, 11, 27, 12, tzinfo=timezone.utc)).isoformat(),
datetime(2026, 10, 28, tzinfo=timezone.utc).isoformat())
# --- cap arithmetic --------------------------------------------------------
# allowance $15 + $50 pack, nothing drawn, fresh cycle
eff = compute_max_budget(15, 50, 0.0, 0.0)
check_near("fresh cycle cap = allowance + pack", eff["max_budget"], 65.0)
check_near("fresh cycle credits remaining = pack", eff["credits_remaining"], 50.0)
# mid-cycle spend NEVER shrinks the cap (the inversion bug)
mid = compute_max_budget(15, 50, 40.0, 0.0)
check_near("mid-cycle cap unchanged as credits burn", mid["max_budget"], 65.0)
check_near("mid-cycle credits used derived from spend", mid["credits_used"], 25.0)
check_near("mid-cycle credits remaining = pack - used", mid["credits_remaining"], 25.0)
# after the cycle closes with $50 drawn
after = compute_max_budget(15, 50, 0.0, 50.0)
check_near("after close cap = allowance only (pack spent)", after["max_budget"], 15.0)
check_near("after close credits remaining = 0", after["credits_remaining"], 0.0)
# every dollar of purchased credit raises the cap by a dollar
check_near("credit add raises the cap 1:1",
compute_max_budget(15, 70, 0.0, 50.0)["max_budget"], 35.0)
check_near("drawn beyond purchased never goes negative",
compute_max_budget(15, 50, 0.0, 80.0)["max_budget"], 15.0)
# --- a real (temporary) DB: apply_cycle_draw ---------------------------------
conn = get_db() # runs schema + migrations
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
"VALUES ('pack@example.com', '', 1, 'member', 15.0, 50.0)"
)
conn.commit()
conn.close()
drawn = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0)
check_near("cycle draws the overage ($65 spend - $15 allowance)", drawn, 50.0)
check_near("credits_drawn recorded", get_credits_drawn("pack@example.com"), 50.0)
check_near("credit_balance still says total purchased", get_credit_balance("pack@example.com"), 50.0)
# replay of the same cycle draws nothing
again = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0)
check_near("replaying a closed cycle draws nothing", again, 0.0)
check_near("credits_drawn unchanged by the replay", get_credits_drawn("pack@example.com"), 50.0)
rows = sqlite3.connect(_TEST_DB).execute(
"SELECT COUNT(*) FROM credit_ledger WHERE reference = ?",
("cycle-close:pack@example.com:2026-10-28",)).fetchone()[0]
check("exactly ONE ledger row for the cycle", rows, 1)
# the issue's reproduction: after the reset the cap is the allowance, not $65
after = compute_max_budget(15, get_credit_balance("pack@example.com"), 0.0,
get_credits_drawn("pack@example.com"))
check_near("issue #12: next cycle cap is $15, not $65", after["max_budget"], 15.0)
# a draw cannot exceed what is left
conn = get_db()
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
"VALUES ('small@example.com', '', 1, 'member', 15.0, 10.0)"
)
conn.commit()
conn.close()
apply_cycle_draw("small@example.com", "2026-10-01", spend=100.0, allowance=15.0)
check_near("draw capped by credits available", get_credits_drawn("small@example.com"), 10.0)
check_near("cap after capped draw = allowance",
compute_max_budget(15, 10, 0.0, 10.0)["max_budget"], 15.0)
# spend under the allowance owes nothing
conn = get_db()
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
"VALUES ('under@example.com', '', 1, 'member', 15.0, 20.0)"
)
conn.commit()
conn.close()
check_near("no overage, no draw",
apply_cycle_draw("under@example.com", "2026-10-01", spend=9.0, allowance=15.0), 0.0)
check_near("balance untouched", get_credits_drawn("under@example.com"), 0.0)
# --- a clawback that would land under recorded spend is DEFERRED ------------
import asyncio # noqa: E402
import app.main as m # noqa: E402
now = m.datetime.now(m.timezone.utc)
anchor = now.day if now.day <= 28 else 28
conn = get_db()
m._ensure_allowance_tables(conn) # adds anchor_day
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance, anchor_day) "
"VALUES ('defer@example.com', '', 1, 'member', 15.0, 20.0, ?)", (anchor,))
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('defer@example.com', 20.0, 'pack (test)', 'test-pack', '2026-10-01 00:00:00')")
conn.commit()
conn.close()
state = {"spend": 40.0, "cap": 35.0}
applied = []
async def fake_team(email):
return "team:defer" if email == "defer@example.com" else None
async def fake_update(team_id, budget):
applied.append(budget)
state["cap"] = budget
m.litellm_team_id_for_email = fake_team
m.litellm_update_team_budget = fake_update
m.get_team_budget_from_db = lambda tid: {"spend": state["spend"], "max_budget": state["cap"],
"budget_reset_at": None}
m.cycle_spend_from_ledger = lambda tid, a, b: 40.0
m.CREDIT_CLOSE_FROM = "2026-01-01"
r1 = asyncio.run(m.close_credit_cycles())
check_near("draw recorded even while the cap is deferred", get_credits_drawn("defer@example.com"), 20.0)
check("cap NOT lowered under recorded spend",
any(d["email"] == "defer@example.com" for d in r1["deferred"]), True)
check("no cap push while spend > new cap", applied, [])
state["spend"] = 0.0 # what LiteLLM does at the member's reset
r2 = asyncio.run(m.close_credit_cycles())
check("cap applied once spend resets", applied, [15.0])
check("no second draw on the same cycle", r2["credits_drawn"], 0.0)
# --- lowering a pack below what was drawn must not swallow NEW credits ----
add_credits("small@example.com", -10.0, reason="admin correction (test)")
check_near("drawn follows the pack down when it is reduced", get_credits_drawn("small@example.com"), 0.0)
check_near("balance reduced to zero", get_credit_balance("small@example.com"), 0.0)
add_credits("small@example.com", 5.0, reason="new pack (test)")
check_near("a new pack is fully available after the correction",
compute_max_budget(15, get_credit_balance("small@example.com"), 0.0,
get_credits_drawn("small@example.com"))["credits_remaining"], 5.0)
print()
if failures:
print(f"{failures} FAILURE(S)")
sys.exit(1)
print("all checks passed")
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Regression tests: a cycle draw may only charge spend credits could cover.
A pack bought mid-cycle must not be charged for spend incurred before it
existed. Reproduces the consensus_polo100 case: $27.81 spent before the $10
pack arrived, then $0.62 after it; the eligible draw is $0.62, not $10.
"""
import os
import sys
import tempfile
from datetime import datetime, timezone
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditelig-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
import app.main as m # noqa: E402
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
def check_near(name, got, want):
global failures
ok = round(float(got), 6) == round(float(want), 6)
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
conn = m.get_db()
m._ensure_allowance_tables(conn) # adds anchor_day
for email, purchased, anchor in [
("midcycle@example.com", 10.0, 15),
("carried@example.com", 50.0, 15),
("none@example.com", 0.0, 15),
("partial@example.com", 20.0, 15)]:
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, "
"credit_balance, credits_drawn, anchor_day) VALUES (?, '', 1, 'member', 15.0, ?, 0, ?)",
(email, purchased, anchor))
# Pack bought inside the cycle, after the allowance had already been overspent.
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('midcycle@example.com', 10.0, 'pack', 'pack-mid', '2026-11-12 13:05:26')")
# Pack held from before the cycle.
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('carried@example.com', 50.0, 'pack', 'pack-carry', '2026-09-20 10:00:00')")
# Pack arrives when only part of the allowance has been used.
conn.execute(
"INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('partial@example.com', 20.0, 'pack', 'pack-part', '2026-10-20 12:00:00')")
conn.commit()
conn.close()
CS = datetime(2026, 10, 15, tzinfo=timezone.utc)
CE = datetime(2026, 11, 15, tzinfo=timezone.utc)
# Spend windows for the mid-cycle member: 27.81376 before the pack, 0.624698 after.
def fake_spend(team_id, start, end):
if team_id == "t-mid":
if end.day == 12 and end.month == 11:
return 27.81376
if start == CS and end == CE:
return 28.438458
if team_id == "t-partial" and start == CS and end == datetime(2026, 10, 20, 12, tzinfo=timezone.utc):
return 5.0
return None
m.cycle_spend_from_ledger = fake_spend
# mid-cycle pack: only spend after the pack is eligible
got = m.credit_eligible_overage("midcycle@example.com", "t-mid", CS, CE, 15.0, 28.438458)
check_near("mid-cycle pack is not charged for earlier spend", got, 0.624698)
# pack carried in: whole overage is eligible
got = m.credit_eligible_overage("carried@example.com", "t-carry", CS, CE, 15.0, 28.438458)
check_near("credits at cycle start cover the whole overage", got, 13.438458)
# no credits: nothing eligible
got = m.credit_eligible_overage("none@example.com", "t-none", CS, CE, 15.0, 28.438458)
check_near("no credits means no eligible draw", got, 0.0)
# partial allowance left: overage above what remains is eligible
got = m.credit_eligible_overage("partial@example.com", "t-partial", CS, CE, 15.0, 20.0)
check_near("allowance is consumed before credits", got, 5.0)
# the eligible figure drives the draw, and the replay still draws nothing
drawn = m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698)
check_near("draw uses the credit-eligible overage", drawn, 0.624698)
check_near("credits_drawn records only that amount", m.get_credits_drawn("midcycle@example.com"), 0.624698)
check_near("purchased total is unchanged", m.get_credit_balance("midcycle@example.com"), 10.0)
check_near("replay draws nothing",
m.apply_cycle_draw("midcycle@example.com", "2026-10-15", 28.438458, 15.0, eligible=0.624698), 0.0)
print()
if failures:
print(f"{failures} FAILURE(S)")
sys.exit(1)
print("all checks passed")
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Regression tests for credit-pack webhook idempotence (audit H1, 2026-11-05).
Runnable:
* from the repo root: python3 tests/test_credit_pack_idempotence.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_credit_pack_idempotence.py
(the container has the app's own dependencies; the host usually does not)
WHY THIS EXISTS
The webhook credit-pack grant used to key its dedupe on `data.get('id')`,
which is absent from real OC deliveries — every recorded reference came out
`oc:<slug>:` (empty suffix), so the key could not distinguish two purchases
by the same member, and NO exists-check guarded the grant at all. One
re-delivered (or replayed, or forged-but-OC-resolvable) event then credits
the pack a second time.
Covered:
- the reference is built per-ORDER (per-purchase), non-empty
- a replayed order credits exactly once, even though the handler runs
twice (simulated by replaying the same grant sequence)
- a NEW order from the same member is never blocked by an earlier one
- a LEGACY empty-suffix ledger row neither matches nor rejects a new
grant (no re-shaping of historical rows — the invariant the fix
must respect)
- held_credits.oc_reference carries a UNIQUE index (one hold per
purchase; NULLs and distinct legacy refs stay legal)
- the DB starts with the unique index present even though legacy
rows exist (no duplicate live rows to violate it)
"""
import os
import sqlite3
import sys
import tempfile
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditpack-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
# Locate the app package: explicit env, the deployed path, or the repo root.
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import ( # noqa: E402
add_credits, credit_pack_reference, credit_reference_exists, get_credit_balance, get_db,
)
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
def grant_once(email, amount, ref):
"""The exact grant sequence the webhook now runs (exists-check gates add)."""
if credit_reference_exists(ref):
return "already_credited"
add_credits(email, amount, reason="credit pack purchase (Open Collective)", reference=ref)
return "credits_added"
# --- reference building: per-order, non-empty, distinct per purchase ---
check("reference keyed on the order id",
credit_pack_reference("caseyg", {"idV2": "or_abc123"}), "oc:or_abc123")
check("two purchases differ even from one member",
credit_pack_reference("caseyg", {"idV2": "or_1"}) != credit_pack_reference("caseyg", {"idV2": "or_2"}),
True)
try:
credit_pack_reference("caseyg", {})
check("missing order idV2 refused (no ambiguous/empty reference)", False, True)
credit_pack_reference("caseyg", {"idV2": ""})
check("empty order idV2 refused", False, True)
except ValueError:
check("missing/empty order idV2 refused (no ambiguous/empty reference)", True, True)
# --- replay on a real (temporary) DB: one replay = exactly one credit ---
conn = get_db() # initializes schema (incl. the unique index) on the temp db
conn.execute("INSERT INTO members (email, key_token, active) VALUES ('p@example.com', '', 1)")
conn.commit()
ref_a = credit_pack_reference("p", {"idV2": "or_test_a"})
r1 = grant_once("p@example.com", 10.0, ref_a) # first delivery
r2 = grant_once("p@example.com", 10.0, ref_a) # re-delivery of the SAME order
check("first delivery grants", r1, "credits_added")
check("replay of the same order is refused", r2, "already_credited")
n = conn.execute("SELECT COUNT(*) FROM credit_ledger WHERE reference = ?", (ref_a,)).fetchone()[0]
check("exactly ONE ledger row for the replayed order", n, 1)
check("balance credited once (10, not 20)", get_credit_balance("p@example.com"), 10.0)
# --- a NEW purchase from the same member is never blocked ---
ref_b = credit_pack_reference("p", {"idV2": "or_test_b"})
r3 = grant_once("p@example.com", 5.0, ref_b)
check("a different order still credits normally", r3, "credits_added")
check("balance includes the second purchase", get_credit_balance("p@example.com"), 15.0)
# --- legacy empty-suffix rows: never matched, never reshaped ---
grant_once("legacy@example.com", 23.0, "oc:caseyg:") # simulate a pre-fix ledger row
legacy_rows = conn.execute(
"SELECT COUNT(*) FROM credit_ledger WHERE reference = 'oc:caseyg:'").fetchone()[0]
check("legacy row stored exactly as it was written", legacy_rows, 1)
new_from_legacy_member = credit_pack_reference("caseyg", {"idV2": "or_new"})
check("a new purchase does NOT match the legacy empty-suffix row",
credit_reference_exists(new_from_legacy_member), False)
check("a new purchase by the legacy member credits normally",
grant_once("legacy@example.com", 15.0, new_from_legacy_member), "credits_added")
still = conn.execute(
"SELECT COUNT(*) FROM credit_ledger WHERE reference = 'oc:caseyg:'").fetchone()[0]
check("the legacy row was neither rejected nor re-shaped", still, 1)
# --- held_credits.oc_reference: UNIQUE index semantics ---
idx = conn.execute(
"SELECT name FROM sqlite_master WHERE type='index' AND name='idx_held_credits_oc_reference'"
).fetchone()
check("unique index exists on a fresh (and the live-shaped) db", bool(idx), True)
conn.execute(
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('buyer-a', NULL, 'Buyer A', 20.0, 'oc:buyer-a:or_h1', 'held')")
try:
conn.execute(
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('buyer-a', NULL, 'Buyer A', 20.0, 'oc:buyer-a:or_h1', 'held')")
conn.commit()
check("second hold for the SAME order rejected by the unique index", False, True)
except sqlite3.IntegrityError:
conn.rollback()
check("second hold for the SAME order rejected by the unique index", True, True)
conn.execute(
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('buyer-b', NULL, 'Buyer B', 10.0, 'oc:buyer-b:or_h2', 'held')")
conn.commit()
check("a different purchase still gets its own hold", True, True)
conn.execute(
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('unknown', NULL, NULL, 10.0, NULL, 'held')")
conn.execute(
"INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('unknown', NULL, NULL, 10.0, NULL, 'held')")
conn.commit()
check("NULL oc_reference rows stay legal (index does not overblock)", True, True)
conn.close()
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
sys.exit(1 if failures else 0)
+377
View File
@@ -0,0 +1,377 @@
#!/usr/bin/env python3
"""Regression test: credit-pack reconciliation (issue #7).
WHY THIS EXISTS
Credits are granted on exactly ONE path — the OC `order.processed` webhook —
and that path can fail AFTER the money has moved. On 2026-11-13 two purchases
did: a $50 pack whose delivery 500'd (httpx's invisible 5-second default), and
a $10 pack with no delivery in the retained log at all. Neither produced a
ledger row, and nothing on a schedule noticed. The reconcile pass reads OC's
OWN order list and compares it with our books.
The thing that makes this dangerous rather than merely absent is the matching:
our own stored references are NOT uniform, so the obvious
`oc:<slug>:<order.id>` test reported 21 already-credited purchases as missing
on its first run. A pass that "fixes" those would double-credit members. This
test pins down, case by case, what counts as accounted for:
* newer ledger rows carry the v2 id `oc:alice:or_…`
* older ledger rows carry a HYPHENATED id `oc:bob:8k03reyd-…`
* legacy rows carry an EMPTY suffix `oc:erin:`
* non-member purchases live in `held_credits`, not the ledger, and are
accounted for — they took the hold path on purpose
and that a purchase with NO such record is reported (dry run) or granted ONCE
(apply), using the same reference the webhook writes, so the two paths are
idempotent against each other in both directions.
Network is STUBBED; assertions are on our own recorded state.
Runnable: python3 tests/test_credit_pack_reconcile.py (from the repo root)
"""
import os
import sys
import asyncio
import tempfile
from datetime import datetime, timedelta, timezone
import httpx
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.ADMIN_TOKEN = "test-admin-token"
m.ADMIN_TOKEN_LEGACY = ""
m.CREDIT_RECONCILE = "report" # the shipped default
m.CREDIT_RECONCILE_DAYS = 30
NOW = datetime.now(timezone.utc)
def iso(days_ago: float) -> str:
return (NOW - timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
def stamp(days_ago: float) -> str:
return (NOW - timedelta(days=days_ago)).strftime("%Y-%m-%d %H:%M:%S")
def order(oid, slug, amount, days_ago=1.0, tier="Credit pack", status="PAID",
frequency="ONETIME"):
return {"id": oid, "status": status, "createdAt": iso(days_ago),
"frequency": frequency, "amount": {"value": amount, "currency": "USD"},
"platformTipAmount": {"value": 0}, "totalAmount": {"value": amount},
"tier": {"name": tier, "slug": (tier or "").lower().replace(" ", "-")},
"fromAccount": {"slug": slug, "name": slug.title(), "type": "INDIVIDUAL"}}
ORDERS = [
# accounted by the EXACT v2 reference (and the ledger amount deliberately
# disagrees, to prove the exact match does not need the fuzzy second signal)
order("or_AAA", "alice", 50, 2.0),
# accounted only by the SECOND signal: older rows carry a hyphenated id
order("or_BBB", "bob", 50, 3.0),
# accounted only by the SECOND signal: a legacy EMPTY-suffix reference
order("or_EEE", "erin", 5, 4.0),
# accounted as HELD — a non-member purchase recorded on the hold path
order("or_HHH", "holdguy", 10, 5.0),
# GENUINELY UNACCOUNTED, and by an active member → the one real candidate
order("or_CCC", "carol", 10, 0.5),
# unaccounted, but the buyer is not an active member → hold path, not a grant
order("or_DDD", "dave", 10, 0.7),
# unaccounted and active, but outside the window → not this pass's business
order("or_FFF", "frank", 10, 100.0),
# not a credit pack / not paid / not one-time → never examined as a pack
order("or_G1", "carol", 15, 1.0, tier="Membership"),
order("or_G2", "carol", 10, 1.0, status="PENDING"),
order("or_G3", "carol", 10, 1.0, status="REFUNDED"),
order("or_G4", "carol", 10, 1.0, frequency="MONTHLY"),
]
class Boom(Exception):
pass
async def fake_orders(per_page=100, max_pages=3):
if FAIL_ORDERS:
raise Boom("OC said 500")
return list(ORDERS)
async def fake_index():
if FAIL_INDEX:
raise Boom("member index unavailable")
return {e: {"slug": e.split("@")[0]} for e in
("alice@x.org", "bob@x.org", "carol@x.org", "dave@x.org",
"erin@x.org", "frank@x.org", "gina@x.org")}
BUDGET_PUSHES = []
SENT = []
def fake_send(to, subject, body, *a, **k):
SENT.append({"to": to, "subject": subject, "body": body})
async def fake_budget(email):
BUDGET_PUSHES.append(email)
return 25.0
FAIL_ORDERS = False
FAIL_INDEX = False
results = []
def check(name, ok):
results.append((name, bool(ok)))
def ledger_rows():
conn = m.get_db()
conn.row_factory = __import__("sqlite3").Row
rows = [dict(r) for r in conn.execute(
"SELECT email, delta, reference, created_at FROM credit_ledger ORDER BY id")]
conn.close()
return rows
def balance(email):
return m.get_credit_balance(email)
def seed():
conn = m.get_db()
conn.execute("DELETE FROM members")
conn.execute("DELETE FROM credit_ledger")
conn.execute("DELETE FROM held_credits")
# A fresh world: the report markers are part of the state under test, so a
# leftover fingerprint from an earlier section would silence a real notice.
conn.execute("DELETE FROM portal_state")
for email, slug, active in (("alice@x.org", "alice", 1), ("bob@x.org", "bob", 1),
("carol@x.org", "carol", 1), ("dave@x.org", "dave", 0),
("erin@x.org", "erin", 1), ("frank@x.org", "frank", 1)):
conn.execute(
"INSERT INTO members (email, slug, active, account_type, credit_balance) "
"VALUES (?, ?, ?, 'member', 0)", (email, slug, active))
# alice: the v2 form, with an amount that DISAGREES with the order ($48 ≠ $50)
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('alice@x.org', 48.0, 'credit pack', ?, ?)",
("oc:alice:or_AAA", stamp(2.0)))
# bob: the hyphenated legacy id for the SAME order (or_BBB)
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('bob@x.org', 50.0, 'credit pack', ?, ?)",
("oc:bob:8k03reyd-5agmq5x4-4nkplbwo-z7j4nxv9", stamp(3.0)))
# erin: the empty-suffix legacy form
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('erin@x.org', 5.0, 'credit pack', 'oc:erin:', ?)", (stamp(4.0),))
# holdguy: a non-member purchase held, never a ledger row
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference, "
"status, created_at) VALUES ('holdguy', 'hold@x.org', 'Hold Guy', 10.0, "
"'oc:holdguy:', 'pending', ?)", (stamp(5.0),))
conn.commit()
conn.close()
def names(res):
return sorted(c["slug"] for c in res["candidates"])
async def main():
global FAIL_ORDERS, FAIL_INDEX
m.fetch_collective_orders = fake_orders
m.fetch_member_index = fake_index
m.sync_team_budget_from_balance = fake_budget
m.send_email = fake_send
# ---------- dry run: report only, change nothing --------------------------
seed()
before = ledger_rows()
res = await m.reconcile_credit_packs(apply=False)
check(f"dry run reports ok (got {res.get('status')})", res.get("status") == "ok")
check("dry run is marked dry_run", res.get("dry_run") is True)
check(f"packs in window counted (got {res.get('packs_in_window')})",
res.get("packs_in_window") == 6)
check(f"only the unaccounted active-member pack is a candidate (got {names(res)})",
names(res) == ["carol"])
check(f"the inactive member's pack is a hold, not a grant (got {res['needs_hold']})",
[c["slug"] for c in res["needs_hold"]] == ["dave"])
check("dry run applied nothing", res.get("applied") == [])
check("dry run wrote no ledger row", ledger_rows() == before)
check(f"dry run left carol's balance alone (got {balance('carol@x.org')})",
balance("carol@x.org") == 0.0)
check("dry run pushed no budget", BUDGET_PUSHES == [])
# the three accounting shapes that a v2-only match would have called missing
for oid, slug, why in (("or_AAA", "alice", "exact v2 reference"),
("or_BBB", "bob", "hyphenated legacy id"),
("or_EEE", "erin", "empty-suffix legacy reference"),
("or_HHH", "holdguy", "held (non-member) purchase")):
o = next(x for x in ORDERS if x["id"] == oid)
ev = m.credit_pack_accounted(o, ledger_rows(), [
dict(r) for r in
conn_rows("SELECT id, slug, email, amount, oc_reference, status, created_at FROM held_credits")
])
check(f"accounted: {why} ({oid}) -> {ev}", ev is not None)
check("a genuinely unaccounted order stays unaccounted",
m.credit_pack_accounted(next(x for x in ORDERS if x["id"] == "or_CCC"),
ledger_rows(), []) is None)
# A manual grant with NO reference links to its member by EMAIL, and the slug
# and email local part routinely differ ("henry-smith" vs "h.smith@x.org").
# Matching only on the slug in the reference drops that row — which is how a
# hand-credited purchase comes to look like a gap.
henry = order("or_HH2", "henry-smith", 12, 1.0)
henry_rows = [{"email": "h.smith@x.org", "delta": 12.0, "reference": None,
"created_at": stamp(1.0), "reason": "manual application"}]
check("a reference-less manual grant is matched via the MEMBER EMAIL",
m.credit_pack_accounted(henry, henry_rows, [],
member_email="h.smith@x.org") is not None)
check("...and is NOT matched without it (the slug alone finds nothing)",
m.credit_pack_accounted(henry, henry_rows, []) is None)
# ---------- a read that fails is UNKNOWN, never 'nothing missing' ---------
FAIL_ORDERS = True
res = await m.reconcile_credit_packs(apply=False)
check(f"order fetch failure is skipped/order_fetch_failed (got {res})",
res.get("status") == "skipped" and res.get("reason") == "order_fetch_failed")
FAIL_ORDERS = False
FAIL_INDEX = True
res = await m.reconcile_credit_packs(apply=False)
check(f"member index failure is skipped/member_index_failed (got {res})",
res.get("status") == "skipped" and res.get("reason") == "member_index_failed")
FAIL_INDEX = False
# ---------- apply=1 while the policy is still 'report' --------------------
seed()
res = await m.reconcile_credit_packs(apply=True)
check("apply is IGNORED while CREDIT_RECONCILE != 'on'",
res.get("dry_run") is True and res.get("applied") == [])
check(f"and still nothing was credited (got {balance('carol@x.org')})",
balance("carol@x.org") == 0.0)
# ---------- CREDIT_RECONCILE=on: grant exactly once ----------------------
seed()
SENT.clear()
m.CREDIT_RECONCILE = "on"
res = await m.reconcile_credit_packs(apply=True)
check(f"apply grants the one candidate (got {res.get('applied')})",
[c["slug"] for c in res.get("applied", [])] == ["carol"])
check(f"carol credited $10 (got {balance('carol@x.org')})",
balance("carol@x.org") == 10.0)
ref = f"oc:carol:or_CCC"
check(f"the grant used the webhook's own reference ({ref})",
any(r["reference"] == ref for r in ledger_rows()))
check(f"exactly one ledger row was added (got {len(ledger_rows())})",
len(ledger_rows()) == 4)
check("the budget was pushed once", BUDGET_PUSHES == ["carol@x.org"])
check("the inactive member was NOT credited",
balance("dave@x.org") == 0.0)
check("the out-of-window member was NOT credited",
balance("frank@x.org") == 0.0)
# The money notice: someone is told when a purchase had to be recovered —
# and NOT told again about a set they have already heard about.
check(f"the grant mails a notice naming the order (got {len(SENT)})",
len(SENT) == 1 and "or_CCC" in SENT[0]["body"] and "carol" in SENT[0]["body"]
and SENT[0]["to"] == "info@inference.coop")
# the webhook and this pass must dedupe each other, whichever runs first
check("the webhook would now answer already_credited for this order",
m.credit_reference_exists(m.credit_pack_reference("carol", {"idV2": "or_CCC"})))
res = await m.reconcile_credit_packs(apply=True)
check(f"a second apply changes nothing (got {res.get('applied')})",
res.get("applied") == [] and res.get("candidates") == [])
check(f"carol's balance unchanged by the re-run (got {balance('carol@x.org')})",
balance("carol@x.org") == 10.0)
check(f"still one row for the order (got {len(ledger_rows())})",
len(ledger_rows()) == 4)
check(f"a re-run with nothing to report mails nothing (got {len(SENT)})", len(SENT) == 1)
# ---------- a candidate must SHOW the nearby rows a human needs ----------
# A manual grant can be real and carry no per-order reference: ntnsndr's three
# launch-day $5 packs were credited as +20.00 then corrected by -10.75, netting
# exactly 3 x $5.00, with no reference on any row. The matcher must NOT read
# that as accounted for (that would hide real gaps), so the candidate has to
# carry enough context for a reviewer to tell the two apart.
seed()
conn = m.get_db()
conn.execute("INSERT INTO members (email, slug, active, account_type, credit_balance) "
"VALUES ('gina@x.org', 'gina', 1, 'member', 0)")
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference, created_at) "
"VALUES ('gina@x.org', 7.5, 'manual application', NULL, ?)", (stamp(0.5),))
conn.commit()
conn.close()
async def only_gina(per_page=100, max_pages=3):
return [order("or_GGG", "gina", 10, 0.5)]
saved_orders = m.fetch_collective_orders
m.fetch_collective_orders = only_gina
res = await m.reconcile_credit_packs(apply=False)
cand = (res.get("candidates") or [{}])[0]
check(f"an unreferenced nearby grant is SURFACED on the candidate "
f"(got {cand.get('nearby_book_rows')})",
any(abs(float(n["delta"]) - 7.5) < 0.01
for n in cand.get("nearby_book_rows") or []))
check("a nearby unreferenced grant does NOT count as accounted for",
len(res.get("candidates") or []) == 1)
check(f"the pass still leaves the money alone (got {balance('gina@x.org')})",
balance("gina@x.org") == 0.0)
m.fetch_collective_orders = saved_orders
# ---------- the endpoint -------------------------------------------------
# Re-seed: the direct apply above already credited carol, so the endpoint
# would have no candidate and the check would pass for the wrong reason.
seed()
m.CREDIT_RECONCILE = "report"
async def endpoint_checks():
transport = httpx.ASGITransport(app=m.app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
r = await c.post("/admin/credit-pack-reconcile")
check(f"endpoint needs the admin token (got {r.status_code})",
r.status_code in (401, 403))
r = await c.post("/admin/credit-pack-reconcile",
headers={"X-Admin-Token": "test-admin-token"})
body = r.json()
check(f"endpoint defaults to a DRY RUN (got {body})",
r.status_code == 200 and body.get("dry_run") is True)
r = await c.post("/admin/credit-pack-reconcile?apply=1",
headers={"X-Admin-Token": "test-admin-token"})
body = r.json()
check("endpoint ?apply=1 is still a dry run while the policy is 'report'",
body.get("dry_run") is True and body.get("applied") == [])
m.CREDIT_RECONCILE = "on"
r = await c.post("/admin/credit-pack-reconcile?apply=1",
headers={"X-Admin-Token": "test-admin-token"})
body = r.json()
check(f"endpoint ?apply=1 grants once the policy is 'on' (got {body})",
body.get("dry_run") is False
and [x["slug"] for x in body.get("applied", [])] == ["carol"])
m.CREDIT_RECONCILE = "report"
await endpoint_checks()
def conn_rows(sql):
conn = m.get_db()
conn.row_factory = __import__("sqlite3").Row
rows = conn.execute(sql).fetchall()
conn.close()
return rows
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)
+23
View File
@@ -0,0 +1,23 @@
import asyncio, os, sys, tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "sources.db")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
m.DB_PATH = os.environ["DB_PATH"]
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, source) VALUES (?,?,?,?)",
("a@example.org", "slug-a", 1, "oc-incognito"))
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, source) VALUES (?,?,?,?)",
("b@example.org", "slug-b", 1, "oc-incognito"))
conn.commit(); conn.close()
m.fetch_member_index = lambda: [("a@example.org", "slug-a"), ("other@example.org", "slug-z")]
r = asyncio.run(m.derive_member_sources())
conn = m.get_db()
a = conn.execute("SELECT source, oc_email FROM members WHERE email='a@example.org'").fetchone()
b = conn.execute("SELECT source, oc_email FROM members WHERE email='b@example.org'").fetchone()
conn.close()
print(" flipped:", r["flipped"], "| a:", tuple(a), "| b:", tuple(b))
assert tuple(a) == ("oc", "a@example.org"), "visible email must flip the source and record it"
assert tuple(b) == ("oc-incognito", None), "a profile still hiding its email stays incognito"
print("DERIVE SOURCES OK: flips only where the profile now shows an email")
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Tests for app.main._current_dues (the member's CURRENT OC dues level).
The admin panel's "Dues" column shows what a member pays on Open Collective
(e.g. $10/mo). That figure is persisted by reconcile_allowances from the OC
orders it already fetches; this file pins the pure extraction rules:
* a live MONTHLY order -> its per-charge amount + 'MONTHLY';
* a live YEARLY order -> its amount + 'YEARLY' (no monthly normalization);
* ACTIVE and PROCESSING both count (a payment in flight is still the level);
* ONE-TIME orders never become dues — credit packs are purchases, not dues;
* CANCELLED / ERROR / PAST_DUE recurrences are not what the member pays now;
* no orders, an unparseable amount or a zero amount -> (None, None).
NULL is the ONLY honest answer; the code must never fall back to the $15
allowance or to a guessed tier.
python3 tests/test_dues_level.py
"""
import os
import sys
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import _current_dues # noqa: E402
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
def order(freq, status, amount, created="2026-11-17T01:52:56.450Z"):
return {"frequency": freq, "status": status,
"amount": {"value": amount, "currency": "USD"},
"totalAmount": {"value": amount, "currency": "USD"},
"createdAt": created, "lastChargedAt": created}
print("1. a live monthly subscription is the dues level")
check(_current_dues([order("MONTHLY", "ACTIVE", 10)]) == (10.0, "MONTHLY"),
"$10/month ACTIVE monthly -> (10.0, 'MONTHLY')")
check(_current_dues([order("MONTHLY", "PROCESSING", 12.5)]) == (12.5, "MONTHLY"),
"a PROCESSING monthly is still the current level (12.5, 'MONTHLY')")
print("2. yearly dues are reported as charged — not divided into months")
check(_current_dues([order("YEARLY", "ACTIVE", 120)]) == (120.0, "YEARLY"),
"$120/year ACTIVE yearly -> (120.0, 'YEARLY') (the panel appends '/yr')")
print("3. one-time orders are purchases, never a dues level")
check(_current_dues([order("ONETIME", "PAID", 10)]) == (None, None),
"a PAID $10 one-time order does not become dues")
check(_current_dues([order("ONETIME", "PAID", 10),
order("MONTHLY", "ACTIVE", 10)]) == (10.0, "MONTHLY"),
"a member with BOTH a one-time pack and a monthly subscription reads the monthly")
print("4. ended subscriptions do not report a stale level")
check(_current_dues([order("MONTHLY", "CANCELLED", 10)]) == (None, None),
"a CANCELLED monthly -> (None, None)")
check(_current_dues([order("MONTHLY", "ERROR", 10)]) == (None, None),
"an ERROR (failed charge) monthly -> (None, None)")
print("5. nothing readable -> NULL, never a guess")
check(_current_dues([]) == (None, None), "no orders -> (None, None)")
check(_current_dues(None) == (None, None), "a missing order list -> (None, None)")
check(_current_dues([{"frequency": "MONTHLY", "status": "ACTIVE"}]) == (None, None),
"a monthly with no totalAmount -> (None, None)")
check(_current_dues([order("MONTHLY", "ACTIVE", 0)]) == (None, None),
"a $0 monthly -> (None, None), not dues of zero")
check(_current_dues([{"frequency": "MONTHLY", "status": "ACTIVE",
"totalAmount": {"value": "not-a-number"}}]) == (None, None),
"an unparseable amount -> (None, None)")
print("6. stacked live monthlies are summed (not newest-only)")
old = order("MONTHLY", "ACTIVE", 5, "2024-01-01T00:00:00.000Z")
new = order("MONTHLY", "ACTIVE", 10, "2026-11-17T01:52:56.450Z")
check(_current_dues([new, old]) == (15.0, "MONTHLY"),
"two live monthly subscriptions are summed ($5 + $10 = $15)")
print()
if FAILS:
print(f"dues level: {len(FAILS)} FAILURE(S)")
sys.exit(1)
print("dues level: all checks passed")
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""Regression test: the first-login service-sync hook (activation path).
WHY THIS EXISTS
New members were deliberately skipped by the Loomio/Matrix syncs until their
Cloudron account was activated (never invite a half-created account), but
nothing fired the syncs at the moment they DID activate — the 3x/day sweep
was the pickup, so a member could wait hours for forum/space access. The
hook on the broker identity path closes that gap. The guards that must hold
are proven here on a FIXTURE db with the network STUBBED:
CHEAP GATE
1. An established member (loomio_invited_at set) schedules NOTHING and
triggers no Cloudron call — one SELECT, zero further work.
ACTIVATION FILTER (fail-closed)
2. A never-invited member whose Cloudron account is NOT activated fires no
sync — never invite a half-created account.
3. A member Cloudron does not know fires no sync.
4. An unreadable Cloudron user list fires no sync (fail-closed — unlike
the sweep's fail-open roster filter, the hook decides whether to fire
at all, so it must be sure).
FIRES
5. A never-invited member whose Cloudron account IS activated fires BOTH
syncs (Loomio then Matrix) exactly once, as a background task.
SAFETY
6. A sync failure is swallowed and logged; the inflight flag clears so a
later gate hit can retry (sweep remains the backstop).
7. While a sync is in flight, further gate hits schedule nothing (the
full-roster reconcile already covers every pending member).
8. The gate NEVER raises — even when its own DB read fails, the broker
response must be untouched.
Runnable: python3 tests/test_first_login_sync.py (from the repo root)
"""
import os
import sys
import tempfile
import asyncio
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"]
results = []
def check(name, ok):
results.append((name, ok))
async def drain():
"""Await every task the gate scheduled, so assertions are deterministic."""
cur = asyncio.current_task()
pending = [t for t in asyncio.all_tasks() if t is not cur]
if pending:
await asyncio.gather(*pending, return_exceptions=True)
CLOUDRON_USERS = [] # what the (stubbed) Cloudron user list returns
cloudron_calls = 0
sync_calls = [] # ("loomio"|"matrix") in fire order
sync_gate = None # optional asyncio.Event: hold the sync in flight
async def fake_fetch_users(client=None):
global cloudron_calls
cloudron_calls += 1
if CLOUDRON_USERS is None:
return None
return CLOUDRON_USERS
async def fake_loomio_sync():
sync_calls.append("loomio")
if sync_gate is not None:
await sync_gate.wait()
async def fake_matrix_sync():
sync_calls.append("matrix")
async def boom_loomio_sync():
raise RuntimeError("simulated Loomio outage")
async def main():
global CLOUDRON_USERS, cloudron_calls, sync_calls, sync_gate
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
for slug, email in (("est", "est@x.org"), ("new", "new@x.org"),
("pending", "pending@x.org"), ("ghost", "ghost@x.org")):
conn.execute(
"INSERT OR REPLACE INTO members (email, slug, active) VALUES (?, ?, 1)",
(email, slug),
)
conn.commit()
conn.close()
m.cloudron_fetch_all_users = fake_fetch_users
m.sync_loomio_memberships = fake_loomio_sync
m.sync_matrix_space = fake_matrix_sync
# --- 1. CHEAP GATE: an established member schedules nothing at all. ---
m.mark_loomio_invited("est@x.org")
cloudron_calls = 0
sync_calls = []
m.maybe_first_login_service_sync("est@x.org")
await drain()
check("established member: no sync scheduled", sync_calls == [])
check("established member: no Cloudron call", cloudron_calls == 0)
check("established member: inflight flag stays clear",
m._first_login_sync_inflight is False)
# --- 2. ACTIVATION FILTER: account not activated -> never fires. ---
CLOUDRON_USERS = [{"email": "new@x.org", "inviteAccepted": False}]
cloudron_calls = 0
sync_calls = []
m.maybe_first_login_service_sync("new@x.org")
await drain()
check("not-activated member: no sync fired", sync_calls == [])
check("not-activated member: activation WAS checked", cloudron_calls == 1)
check("not-activated member: inflight flag cleared",
m._first_login_sync_inflight is False)
# --- 3. Unknown to Cloudron -> never fires. ---
CLOUDRON_USERS = [{"email": "other@x.org", "inviteAccepted": True}]
sync_calls = []
m.maybe_first_login_service_sync("ghost@x.org")
await drain()
check("member unknown to Cloudron: no sync fired", sync_calls == [])
# --- 4. FAIL CLOSED: unreadable Cloudron user list -> never fires. ---
CLOUDRON_USERS = None
sync_calls = []
m.maybe_first_login_service_sync("new@x.org")
await drain()
check("cloudron outage: no sync fired (fail-closed)", sync_calls == [])
check("cloudron outage: inflight flag cleared",
m._first_login_sync_inflight is False)
# --- 5. FIRES: activated + outstanding invites -> both syncs, once each. ---
CLOUDRON_USERS = [{"email": "NEW@x.org", "inviteAccepted": True}] # case-insensitive
sync_calls = []
m.maybe_first_login_service_sync("new@x.org")
await drain()
check("activated member: Loomio sync fired first, then Matrix",
sync_calls == ["loomio", "matrix"])
check("activated member: inflight flag cleared after the run",
m._first_login_sync_inflight is False)
# --- 6. SAFETY: a sync failure is swallowed; the gate stays usable. ---
m.sync_loomio_memberships = boom_loomio_sync
sync_calls = []
m.maybe_first_login_service_sync("new@x.org")
err = None
try:
await drain()
except Exception as e: # pragma: no cover
err = e
check("loomio outage: nothing escapes the background task", err is None)
check("loomio outage: matrix still attempted", sync_calls == ["matrix"])
check("loomio outage: inflight flag cleared for the next attempt",
m._first_login_sync_inflight is False)
m.sync_loomio_memberships = fake_loomio_sync
# --- 7. INFLIGHT: a second gate hit while a sync runs schedules nothing. ---
sync_gate = asyncio.Event()
sync_calls = []
m.maybe_first_login_service_sync("new@x.org") # task starts, blocks in loomio stub
await asyncio.sleep(0) # let it reach the blocking stub
check("inflight: flag is set while the sync runs",
m._first_login_sync_inflight is True)
m.maybe_first_login_service_sync("pending@x.org") # second member, same moment
m.maybe_first_login_service_sync("new@x.org") # same member again
sync_gate.set()
await drain()
check("inflight: exactly ONE sync ran for three gate hits",
sync_calls == ["loomio", "matrix"])
sync_gate = None
# --- 8. The gate NEVER raises, even if its own DB read fails. ---
real_invited = m.get_loomio_invited_at
def broken_invited(_email):
raise RuntimeError("simulated DB failure")
m.get_loomio_invited_at = broken_invited
err = None
try:
m.maybe_first_login_service_sync("new@x.org")
await drain()
except Exception as e:
err = e
check("gate swallows its own DB failure (broker response untouched)", err is None)
check("gate DB failure schedules nothing", sync_calls == ["loomio", "matrix"])
m.get_loomio_invited_at = real_invited
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)
+8
View File
@@ -0,0 +1,8 @@
import os, sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
v=m._fx_verdict(1.0975); assert v["alert"] is False, v
v=m._fx_verdict(1.13); assert v["alert"] is True and v["drift_pct"] > 0, v
v=m._fx_verdict(1.07); assert v["alert"] is True and v["drift_pct"] < 0, v
v=m._fx_verdict(1.0995); assert v["alert"] is False, v # 0.18% drift
print("FX VERDICT OK: thresholds and signs behave")
+288
View File
@@ -0,0 +1,288 @@
#!/usr/bin/env python3
"""Guest-account SELF-CANCEL tests — structurally isolated from live services.
Same harness contract as test_guest_lifecycle.py: a FIXTURE database with the
network layer REPLACED BY A RAISING GUARD, so any code path that tries to
reach Cloudron, LiteLLM, OC, Listmonk or SMTP outside the stubs fails the
test loudly instead of acting on live systems.
GUARD
1. A paying member can NEVER cancel through the guest path (403).
2. An unknown identity is refused.
CANCEL (the full self-service flow)
3. The row deactivates (active=0) and the account is KEPT.
4. The Cloudron user leaves the guests group for the ended-guests group.
5. The gateway budget is zeroed (revoke path called).
6. The newsletter unsubscribe fires.
7. The credit RETURN is written: a NEGATIVE ledger delta whose reason
names the cancellation and the original guest reference, deduped on
its own reference; the member's credit_balance goes to 0.
8. The guests ledger records inviter → recipient → 'cancelled by
recipient' (rows appended, never rewritten).
IDEMPOTENCE
9. A second cancel is a NO-OP: no second ledger row, no re-deactivation
calls, and the reported status is the recorded one.
PARTIAL-FAILURE REPLAY
10. A cancel whose return row already exists (deactivation failed
mid-way last time) reports the recorded amount and writes no second
ledger row.
ENDED-STATE READBACK (GET /broker/guest-status payload pieces)
11. The cancelled guest reports ended + cancelled + the returned amount;
a live guest reports active with its remaining credits; a member
reports guest: false.
Runnable: python3 tests/test_guest_cancel.py (from the repo root)
"""
import asyncio
import base64
import os
import sys
import tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
os.environ.setdefault("GUESTS_ENDED_GROUP_ID", "gid-fixture-guests-ended")
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"]
results = []
def check(name, ok, detail=""):
results.append((name, bool(ok), detail))
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
class _NoNetwork:
"""Guard: ANY httpx client construction inside the test is a failure."""
def __init__(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
def __call__(self, *a, **k): # pragma: no cover
raise AssertionError("live network attempted during fixture test")
m.httpx.AsyncClient = _NoNetwork
calls = {"group": [], "revoke": [], "listmonk": [], "email": []}
async def rec_switch(user_id, add_gid=None, remove_gids=()):
calls["group"].append((user_id, add_gid))
async def rec_group(user_id, group_id=None):
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
async def rec_revoke(email):
calls["revoke"].append(email)
return True
async def rec_listmonk(email, subscribe):
calls["listmonk"].append((email, bool(subscribe)))
def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject))
return True
TEAM_SPEND = {}
def fake_team_db(team_id):
return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0),
"budget_reset_at": None}
async def fake_team_id(email):
return "team-" + email
m.cloudron_switch_group = rec_switch
m.cloudron_set_group = rec_group
m.cloudron_set_active = rec_group # same signature (uid, bool)
m.litellm_team_id_for_email = fake_team_id
m.get_team_budget_from_db = fake_team_db
m.revoke_member_litellm_access = rec_revoke
m.listmonk_sync = rec_listmonk
m.send_email = rec_email
def seed_gift(conn, email, active=1, credits=2.0, balance=0.0):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type, guest_expires_at) "
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, ?, 'guest', "
"datetime('now', '+30 days'))",
(email, email, active, balance, credits),
)
conn.execute(
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
"VALUES ('member-one@x.org', ?, datetime('now'), 'active')", (email,)
)
def ledger_rows(conn, email):
return conn.execute(
"SELECT delta, reason, reference FROM credit_ledger WHERE email = ? "
"ORDER BY id", (email,)
).fetchall()
def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
# the inviter: an active member (guard requirement), and a PAYING member
# whose cancellation must be refused
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type) "
"VALUES ('member-one@x.org', 'enc', 'uid-m1', 'memberone', 1, 15.0, 0.0, 'member')")
conn.commit()
conn.close()
# --- 1/2. the member guard ----------------------------------------------
try:
asyncio.run(m.cancel_guest_account("member-one@x.org"))
check("guard: paying member cannot cancel via the guest path", False, "no 403 raised")
except m.HTTPException as e:
check("guard: paying member cannot cancel via the guest path", e.status_code == 403,
str(e.status_code))
try:
asyncio.run(m.cancel_guest_account("nobody@x.org"))
check("guard: unknown identity refused", False, "no 403 raised")
except m.HTTPException as e:
check("guard: unknown identity refused", e.status_code == 403, str(e.status_code))
# --- 3-8. the full cancel flow ------------------------------------------
conn = m.get_db()
seed_gift(conn, "invited@x.org", active=1, credits=2.0)
# the grant row production writes at provisioning (add_credits on the
# guest reference) — the return is audited against it
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) "
"VALUES ('invited@x.org', 2.0, 'guest account — $2 credit from a member', "
"'guest:invited@x.org')")
conn.commit()
conn.close()
out = asyncio.run(m.cancel_guest_account("invited@x.org"))
conn = m.get_db()
row = conn.execute("SELECT active, account_type, credit_balance FROM members "
"WHERE email = 'invited@x.org'").fetchone()
check("cancel: row deactivated, account kept",
row[0] == 0 and row[1] == "guest", str(row))
check("cancel: credit balance drawn to 0", row[2] == 0.0, str(row))
check("cancel: group moved guests → ended-guests",
any(u == "uid-invited@x.org" and g == m.GUESTS_ENDED_GROUP_ID
for u, g in calls["group"]), str(calls["group"]))
check("cancel: gateway budget zeroed (revoke called)",
"invited@x.org" in calls["revoke"], str(calls["revoke"]))
check("cancel: newsletter unsubscribed",
("invited@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
led = ledger_rows(conn, "invited@x.org")
grants = [r for r in led if r[2] == "guest:invited@x.org"]
returns = [r for r in led if r[2] == "guest-return:invited@x.org"]
check("cancel: ledger holds the $2 grant and ONE negative return row",
len(grants) == 1 and grants[0][0] == 2.0 and len(returns) == 1
and returns[0][0] == -2.0, str(led))
check("cancel: return reason names the cancellation and the guest reference",
len(returns) == 1 and "cancelled by recipient" in returns[0][1]
and "guest:invited@x.org" in returns[0][1], str(returns))
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
"WHERE recipient_email = 'invited@x.org'").fetchone()
check("cancel: guests ledger shows inviter → recipient → cancelled by recipient",
g and g[0] == "member-one@x.org" and g[1] == "invited@x.org"
and g[2] == "cancelled by recipient", str(g))
check("cancel: result reports the returned amount",
out.get("status") == "cancelled" and out.get("credits_returned") == 2.0, str(out))
conn.close()
# --- 9. idempotence: the second cancel is a no-op -----------------------
calls["group"].clear(); calls["revoke"].clear(); calls["listmonk"].clear()
out2 = asyncio.run(m.cancel_guest_account("invited@x.org"))
conn = m.get_db()
led2 = ledger_rows(conn, "invited@x.org")
check("idempotent: second cancel reports already_ended",
out2.get("status") == "already_ended"
and out2.get("guest_status") == "cancelled by recipient", str(out2))
check("idempotent: no second return row",
len([r for r in led2 if r[2] == "guest-return:invited@x.org"]) == 1, str(led2))
check("idempotent: no re-deactivation side effects",
not calls["group"] and not calls["revoke"] and not calls["listmonk"],
str(calls))
conn.close()
# --- 10. partial-failure replay: return row exists, deactivation failed -
conn = m.get_db()
seed_gift(conn, "halfway@x.org", active=1, credits=4.0)
# simulate the ledger row written before a crash: return recorded, row still active
conn.execute("UPDATE members SET credit_balance = 0.0 WHERE email = 'halfway@x.org'")
conn.execute("INSERT INTO credit_ledger (email, delta, reason, reference) "
"VALUES ('halfway@x.org', -4.0, 'guest cancelled by recipient — "
"unspent credit returned to the co-op (original guest: "
"guest:halfway@x.org)', 'guest-return:halfway@x.org')")
conn.commit()
conn.close()
out3 = asyncio.run(m.cancel_guest_account("halfway@x.org"))
conn = m.get_db()
led3 = ledger_rows(conn, "halfway@x.org")
check("replay: the recorded return is reported, not re-written",
len([r for r in led3 if r[2] == "guest-return:halfway@x.org"]) == 1
and out3.get("credits_returned") == 4.0, str(led3) + " / " + str(out3))
check("replay: deactivation still completed",
conn.execute("SELECT active FROM members WHERE email='halfway@x.org'"
).fetchone()[0] == 0)
conn.close()
# --- 11. the guest-status payload pieces ---------------------------------
# member: guest false
conn = m.get_db()
ok_member = conn.execute("SELECT 1 FROM members WHERE email='member-one@x.org'").fetchone()
conn.close()
if ok_member:
# call the payload logic directly (the route needs a Request object)
conn = m.get_db()
row = conn.execute("SELECT active, balance, credit_balance FROM members "
"WHERE email = 'member-one@x.org'").fetchone()
conn.close()
check("status: a member is not a guest (payload contract)",
not m.is_guest_account("member-one@x.org"))
# cancelled guest: ended + cancelled + returned amount
st_cancelled = {
"ended": True, "guest_status": m._guest_ledger_status("invited@x.org"),
"cancelled": m._guest_ledger_status("invited@x.org") == "cancelled by recipient",
"credits_returned": m._guest_returned_credits("invited@x.org"),
}
check("status: cancelled guest reads ended + cancelled + amount returned",
st_cancelled["ended"] and st_cancelled["cancelled"]
and st_cancelled["credits_returned"] == 2.0, str(st_cancelled))
# live guest: active with remaining credits
conn = m.get_db()
seed_gift(conn, "live@x.org", active=1, credits=2.0)
conn.commit()
conn.close()
st_live = {
"active": bool(conn_active := 1),
"guest_status": m._guest_ledger_status("live@x.org"),
}
check("status: live guest reads active with an 'active' ledger row",
st_live["active"] and st_live["guest_status"] == "active", str(st_live))
failed = [r for r in results if not r[1]]
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+259
View File
@@ -0,0 +1,259 @@
#!/usr/bin/env python3
"""Parallel guest invitations cannot slip two guests past the 30-day rule.
WHY THIS EXISTS
The one-guest-per-member-per-30-days rule is a READ of the guests ledger,
provisioning takes seconds of external calls, and the ledger row that closes
the window is written LAST. Two PARALLEL direct calls (curl, not the
dashboard JS) could therefore both pass the guard before either row exists.
The member invite path now runs under _GUEST_INVITE_LOCK, which makes
check-and-send atomic for the single-process uvicorn app.
Proven here, against a FIXTURE database with the network layer replaced by
raising guards (any live call fails the test loudly):
1. With the lock DISABLED, two parallel invites from the same member BOTH
provision — the race is real, and the test has teeth.
2. With the real lock, the same parallel pair yields exactly ONE
provisioned guest; the second is refused 429 inside the 30-day window.
3. Exactly one ledger row and one members row exist per accepted invite;
the refused recipient is unborn (no row, no credit, no email).
Runnable: python3 tests/test_guest_concurrency.py (from the repo root)
"""
import asyncio
import base64
import os
import sys
import tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
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"]
results = []
def check(name, ok, detail=""):
results.append((name, bool(ok), detail))
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
class _NoNetwork:
def __init__(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
def __call__(self, *a, **k): # pragma: no cover
raise AssertionError("live network attempted during fixture test")
class _FakeClient(_NoNetwork):
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
async def post(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
m.httpx.AsyncClient = _FakeClient
# --- provisioning stubs: same contract as test_guest_requests, but
# cloudron_create_user SUSPENDS briefly, forcing real task interleaving so the
# parallel window is actually exercised (without a suspension point asyncio
# would run the two requests back-to-back and prove nothing). ----------------#
calls = {"group": [], "email": [], "listmonk": [], "budget": [], "uids": 0}
async def fake_user_create(email, name):
calls["uids"] += 1
await asyncio.sleep(0.05) # the suspension that opens the parallel window
return f"uid-fixture-{calls['uids']}"
async def rec_group(user_id, group_id=None):
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject or ""))
return True
async def rec_listmonk(email, subscribe):
calls["listmonk"].append((email, bool(subscribe)))
async def rec_budget(team_id, budget):
calls["budget"].append((team_id, round(float(budget), 2)))
async def fake_team(email, budget, budget_duration="30d"):
return "team-fixture"
async def fake_key(email, budget, team_id):
return "sk-fixture"
async def fake_invite_link(user_id):
return "https://my.example/setupaccount.html?inviteToken=x"
def fake_team_db(team_id):
return {"max_budget": None, "spend": 0.0, "budget_reset_at": None}
m.cloudron_create_user = fake_user_create
m.cloudron_set_group = rec_group
m.cloudron_set_active = rec_group
m.cloudron_get_invite_link = fake_invite_link
m.litellm_get_or_create_team = fake_team
m.litellm_create_key = fake_key
m.litellm_update_team_budget = rec_budget
m.get_team_budget_from_db = fake_team_db
m.send_email = rec_email
m.listmonk_sync = rec_listmonk
# --- real Request objects (the slowapi limiter decorator requires them) ----- #
from starlette.requests import Request as StarletteRequest # noqa: E402
import json as _json # noqa: E402
def make_request(body=None):
raw = _json.dumps(body or {}).encode()
headers = {"content-type": "application/json", "content-length": str(len(raw))}
async def receive():
return {"type": "http.request", "body": raw, "more_body": False}
scope = {
"type": "http", "method": "POST", "path": "/", "query_string": b"",
"headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],
"server": ("testserver", 80), "client": ("testclient", 123),
}
return StarletteRequest(scope, receive)
def seed_member(conn, email):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type) "
"VALUES (?, 'enc', 'uid-' || ?, '', 1, ?, 0, 'member')",
(email, email, m.MEMBER_BUDGET),
)
class _NoLock:
"""Stands in for the real lock to demonstrate the unguarded race."""
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def parallel_pair(inviter, recipients):
"""Fire TWO member invites at once (the direct-call attack shape)."""
m._verify_broker_secret = lambda request: inviter
return await asyncio.gather(
*(m.broker_guest_invite(make_request({"email": r})) for r in recipients),
return_exceptions=True,
)
def ledger_count(inviter):
conn = m.get_db()
n = conn.execute("SELECT COUNT(*) FROM guests WHERE inviter_email=?",
(inviter,)).fetchone()[0]
conn.close()
return n
def row_count(email):
conn = m.get_db()
n = conn.execute("SELECT COUNT(*) FROM members WHERE email=?", (email,)).fetchone()[0]
conn.close()
return n
def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
m._ensure_allowance_tables(conn)
# --- 1. the RACE, unguarded: prove two parallel invites both provision -- #
seed_member(conn, "racer-one@x.org")
conn.commit()
conn.close()
real_lock = m._GUEST_INVITE_LOCK
m._GUEST_INVITE_LOCK = _NoLock()
try:
out = asyncio.run(parallel_pair(
"racer-one@x.org", ["race-a@x.org", "race-b@x.org"]))
finally:
m._GUEST_INVITE_LOCK = real_lock
provisioned = [o for o in out if isinstance(o, dict)]
refused = [o for o in out if isinstance(o, Exception)]
check("race (unguarded): both parallel invites slipped through "
"(the test has teeth — this is the defect the lock closes)",
len(provisioned) == 2 and not refused,
f"provisioned={len(provisioned)} refused={len(refused)}")
check("race (unguarded): two ledger rows — the rule is broken without "
"serialization", ledger_count("racer-one@x.org") == 2,
str(ledger_count("racer-one@x.org")))
# --- 2. the LOCK: the same parallel pair now yields exactly one guest --- #
conn = m.get_db()
seed_member(conn, "racer-two@x.org")
conn.commit()
conn.close()
calls["email"].clear()
out = asyncio.run(parallel_pair(
"racer-two@x.org", ["race-c@x.org", "race-d@x.org"]))
provisioned = [o for o in out if isinstance(o, dict)]
refused = [o for o in out if isinstance(o, Exception)]
check("lock: exactly ONE of two parallel invites provisions",
len(provisioned) == 1 and len(refused) == 1,
f"provisioned={len(provisioned)} refused={len(refused)} "
f"{[type(o).__name__ for o in out]}")
check("lock: the refusal is the over-limit error (429, 30-day window)",
refused and getattr(refused[0], "status_code", None) == 429
and "30 days" in str(getattr(refused[0], "detail", "")),
f"{refused}")
check("lock: exactly ONE ledger row for the inviter",
ledger_count("racer-two@x.org") == 1,
str(ledger_count("racer-two@x.org")))
born = sum(1 for r in ("race-c@x.org", "race-d@x.org") if row_count(r))
check("lock: exactly ONE recipient account was created", born == 1, str(born))
check("lock: the refused recipient is unborn (no row, no guest, no credit)",
sum(1 for r in ("race-c@x.org", "race-d@x.org") if row_count(r) == 0) == 1)
check("lock: exactly ONE invitation email left the building",
len(calls["email"]) == 1, str(calls["email"]))
# --- 3. sequential semantics unchanged: the second invite still refuses - #
conn = m.get_db()
refusal = m.guest_request_guard(conn, "racer-two@x.org", "race-e@x.org")
conn.close()
check("aftermath: a later invite from the same member is still refused "
"(one per 30 days, unchanged)",
refusal is not None and "30 days" in refusal, str(refusal))
failed = [r for r in results if not r[1]]
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Regression tests: guest conversion carries only UNSPENT credit.
Runnable:
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_guest_conversion_draw.py
* from the repo root, on a host that has the app's dependencies
WHY THIS EXISTS
A guest has no monthly cycle, so nothing ever drew their spend against the
$2 pack. Converting a guest kept the full $2 credit_balance, handing back
credits already used — while guest-access.md promises only the UNSPENT
credit carries over. record_guest_conversion_draw() records the consumed
part as a draw, deduped on a ledger reference.
"""
import os
import sys
import tempfile
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="guestdraw-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import ( # noqa: E402
compute_max_budget, get_credit_balance, get_credits_drawn, get_db,
record_guest_conversion_draw,
)
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
def check_near(name, got, want):
global failures
ok = round(float(got), 6) == round(float(want), 6)
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
conn = get_db()
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
"VALUES ('g1@example.com', '', 1, 'guest', 0.0, 2.0)")
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) "
"VALUES ('g2@example.com', '', 1, 'guest', 0.0, 2.0)")
conn.commit()
conn.close()
used = record_guest_conversion_draw("g1@example.com", 1.9)
check_near("consumed guest spend is drawn", used, 1.9)
check_near("credits_drawn records it", get_credits_drawn("g1@example.com"), 1.9)
check_near("credit_balance stays the purchased total", get_credit_balance("g1@example.com"), 2.0)
check_near("only the unspent credit is available",
compute_max_budget(15, 2, 0.0, get_credits_drawn("g1@example.com"))["credits_remaining"], 0.1)
check_near("a replay draws nothing", record_guest_conversion_draw("g1@example.com", 1.9), 0.0)
check_near("credits_drawn unchanged by replay", get_credits_drawn("g1@example.com"), 1.9)
check_near("spend above the pack is capped", record_guest_conversion_draw("g2@example.com", 5.0), 2.0)
check_near("pack fully drawn", get_credits_drawn("g2@example.com"), 2.0)
check_near("no credit left", compute_max_budget(15, 2, 0.0, 2.0)["credits_remaining"], 0.0)
check_near("zero spend draws nothing", record_guest_conversion_draw("g1@example.com", 0.0), 0.0)
print()
if failures:
print(f"{failures} FAILURE(S)")
sys.exit(1)
print("all checks passed")
+317
View File
@@ -0,0 +1,317 @@
#!/usr/bin/env python3
"""Guest invited state — a provisioned-but-NOT-set-up guest never reads 'active'.
WHY THIS EXISTS
A guest invitation provisions IMMEDIATELY (Cloudron user + invitation email
with the setup link), but the Cloudron account is not ACCEPTED until the
guest clicks that link (inviteAccepted=false, no username) — they cannot
log in yet. Every surface that reads the guest's state must therefore show
'invited' (awaiting setup) at that point, never 'active', and flip to the
ordinary state only when the invite is accepted. Display/state semantics
only: access rules, the guest cap and the expiry box are unchanged.
Every path here runs against a FIXTURE database with the network layer
REPLACED: any code path that reaches Cloudron/LiteLLM/OC/Listmonk outside
the stubs fails the test loudly instead of acting on live systems.
1. guest_invite_pending — the derivation itself: accepted, username-set,
unseen-record (fetch failed) and no-user-id cases.
2. GET /admin/overview: a fresh guest (inviteAccepted=false, no
username) reports state='invited' with an 'awaiting setup' reason.
Once accepted, state FOLLOWS THE LEDGER STATUS (active / expired /
...) — the single derivation point for the guest display state,
consumed as-is by the panel and dashboard; a guest with no ledger
row falls back to the membership state.
3. Simulated acceptance (inviteAccepted flips true, or a username is
chosen) → the same endpoint reports state='active'.
4. A FAILED Cloudron users fetch never claims 'invited' — the row falls
back to the membership state rather than inventing a state the data
does not show.
5. An established MEMBER row is untouched by the guest branch: state
'active', empty reason, still in members[].
6. The member's trail (GET /broker/guests) carries state='invited' for
the un-accepted guest and state=<ledger status> once accepted.
Runnable: python3 tests/test_guest_invited_state.py (from the repo root)
"""
import asyncio
import base64
import os
import sys
import tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
os.environ["ADMIN_TOKEN"] = "test-admin-token" # admin endpoints authenticate on this
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
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"]
results = []
def check(name, ok, detail=""):
results.append((name, bool(ok), detail))
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
# --- Cloudron users fixture (the ONLY external signal this feature reads) --- #
CLOUDRON_USERS = {
"uid-guest@x.org": {"inviteAccepted": False, "username": None},
"uid-member@x.org": {"inviteAccepted": True, "username": "established"},
}
class _FakeResponse:
status_code = 200
def raise_for_status(self):
pass
def json(self):
return [] # LiteLLM /team/list: no teams in this fixture
class _FakeClient:
"""Answers only what admin_overview asks: cloudron_fetch_all_users (stubbed
separately) and the LiteLLM team/list GET (empty)."""
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, url, **k):
return _FakeResponse()
class _NoNetwork:
def __init__(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
def __call__(self, *a, **k): # pragma: no cover
raise AssertionError("live network attempted during fixture test")
m.httpx.AsyncClient = _FakeClient # ONLY _FakeClient.__init__-safe paths run
async def fetch_users_ok(client):
return [{"id": uid, "username": v.get("username"),
"inviteAccepted": v.get("inviteAccepted", False)}
for uid, v in CLOUDRON_USERS.items()]
async def fetch_users_broken(client):
return None # page 1 unresolvable — the documented fetch-failure shape
m.cloudron_fetch_all_users = fetch_users_ok
# The overview's all-time-spend query is a PG read — absent in the fixture and
# fail-soft by design; make that loud rather than implicit.
def _no_pg(*a, **k):
raise AssertionError("live PG attempted during fixture test")
m._pg_connect = _no_pg
# --- real Request objects (the slowapi limiter decorator requires them) ----- #
from starlette.requests import Request as StarletteRequest # noqa: E402
import json as _json # noqa: E402
def make_request(method="GET", body=None, headers=None):
raw = _json.dumps(body or {}).encode()
headers = dict(headers or {})
if raw and "content-length" not in headers:
headers["content-length"] = str(len(raw))
async def receive():
return {"type": "http.request", "body": raw, "more_body": False}
scope = {
"type": "http", "method": method, "path": "/", "query_string": b"",
"headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
"server": ("testserver", 80), "client": ("testclient", 123),
}
return StarletteRequest(scope, receive)
def seed_account(conn, email, account_type="member", active=1, uid=None):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type) "
"VALUES (?, 'enc', ?, '', ?, ?, 0, ?)",
(email, uid or ("uid-" + email), active, 0.0, account_type),
)
def seed_guest_ledger(conn, inviter, recipient, status="active"):
conn.execute(
"INSERT INTO guests (inviter_email, recipient_email, oc_reference, "
"guest_expires_at, status, created_at) "
"VALUES (?, ?, NULL, datetime('now', '+60 days'), ?, datetime('now'))",
(inviter, recipient, status),
)
def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
m._ensure_allowance_tables(conn)
# --- 1. the derivation itself --------------------------------------------
check("derive: accepted invite is not pending",
m.guest_invite_pending("u", {}, {"u": True}) is False)
check("derive: a chosen username counts as accepted (first login)",
m.guest_invite_pending("u", {"u": "theirname"}, {"u": False}) is False)
check("derive: un-accepted + no username IS pending",
m.guest_invite_pending("u", {}, {"u": False}) is True)
check("derive: a record we never saw is NOT pending (fetch failed)",
m.guest_invite_pending("u", {}, {}) is False)
check("derive: no user id is never pending",
m.guest_invite_pending(None, {}, {"u": False}) is False)
# --- 2-5. /admin/overview --------------------------------------------------
inviter = "info@inference.coop" # the admin path's inviter
seed_account(conn, "member@x.org", account_type="member", active=1)
seed_account(conn, "guest@x.org", account_type="guest", active=1)
seed_account(conn, "ended@x.org", account_type="guest", active=0)
seed_guest_ledger(conn, inviter, "guest@x.org")
seed_guest_ledger(conn, inviter, "ended@x.org", status="expired")
conn.commit()
conn.close()
async def overview():
return await m.admin_overview(make_request(
"GET", headers={"X-Admin-Token": "test-admin-token"}))
data = asyncio.run(overview())
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
check("overview: fresh guest listed under guests[], never members[]",
len(data["guests"]) == 2 and not any(x["email"] == "guest@x.org" for x in data["members"]),
str([x["email"] for x in data["guests"]]))
check("overview: un-accepted guest reads state='invited'",
g["state"] == "invited", str(g.get("state")))
check("overview: invited reason is the awaiting-setup line",
str(g.get("state_reason", "")).startswith("awaiting setup"),
str(g.get("state_reason")))
check("overview: ledger status still the record of record",
g.get("guest_status") == "active", str(g.get("guest_status")))
check("overview: activated flag agrees (pending)",
g.get("activated") is False, str(g.get("activated")))
ended = [x for x in data["guests"] if x["email"] == "ended@x.org"][0]
check("overview: ended guest reads its LEDGER status ('expired'), not the bare flag",
ended["state"] == "expired" and ended["state_reason"] == "",
f"{ended.get('state')} / {ended.get('state_reason')!r}")
# The ledger is the record of record even when it disagrees with the
# members.active flag: an active-flagged guest whose access has ENDED
# (expired ledger row, active flag not yet flipped) reads 'expired'.
conn = m.get_db()
CLOUDRON_USERS["uid-lapsed@x.org"] = {"inviteAccepted": True, "username": "lapsedg"}
seed_account(conn, "lapsed@x.org", account_type="guest", active=1,
uid="uid-lapsed@x.org")
seed_guest_ledger(conn, inviter, "lapsed@x.org", status="expired")
# ...and a guest with NO ledger row falls back to the membership state.
CLOUDRON_USERS["uid-noledger@x.org"] = {"inviteAccepted": True, "username": "noledger"}
seed_account(conn, "noledger@x.org", account_type="guest", active=1,
uid="uid-noledger@x.org")
conn.commit()
conn.close()
data = asyncio.run(overview())
lapsed = [x for x in data["guests"] if x["email"] == "lapsed@x.org"][0]
check("overview: ledger status wins over the active flag (lapsed guest = 'expired')",
lapsed["state"] == "expired", str(lapsed.get("state")))
noledger = [x for x in data["guests"] if x["email"] == "noledger@x.org"][0]
check("overview: no ledger row → membership-state fallback ('active')",
noledger["state"] == "active", str(noledger.get("state")))
# --- 3. simulated acceptance: the flip to active ---------------------------
CLOUDRON_USERS["uid-guest@x.org"]["inviteAccepted"] = True
data = asyncio.run(overview())
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
check("overview: after acceptance the guest reads state='active'",
g["state"] == "active", str(g.get("state")))
check("overview: accepted guest carries no awaiting-setup reason",
g.get("state_reason", "") == "", str(g.get("state_reason")))
check("overview: activated flag agrees (yes)",
g.get("activated") is True, str(g.get("activated")))
# ...and the username-only variant (the guest finished setup by name):
CLOUDRON_USERS["uid-guest@x.org"]["inviteAccepted"] = False
CLOUDRON_USERS["uid-guest@x.org"]["username"] = "theirname"
data = asyncio.run(overview())
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
check("overview: a chosen username alone flips the guest to active",
g["state"] == "active", str(g.get("state")))
CLOUDRON_USERS["uid-guest@x.org"]["username"] = None
# --- 4. a failed Cloudron fetch never claims 'invited' ---------------------
m.cloudron_fetch_all_users = fetch_users_broken
data = asyncio.run(overview())
g = [x for x in data["guests"] if x["email"] == "guest@x.org"][0]
check("overview: users fetch failed → fallback state, never 'invited'",
g["state"] == "active" and g["state_reason"] == "",
f"{g.get('state')} / {g.get('state_reason')!r}")
m.cloudron_fetch_all_users = fetch_users_ok
# --- 5. an established member's row is untouched ----------------------------
data = asyncio.run(overview()) # fresh payload from the working fetch
mem = [x for x in data["members"] if x["email"] == "member@x.org"][0]
check("overview: established member state unchanged ('active', no reason)",
mem["state"] == "active" and mem["state_reason"] == "",
f"{mem.get('state')} / {mem.get('state_reason')!r}")
check("overview: established member activated (not caught by the guest branch)",
mem.get("activated") is True, str(mem.get("activated")))
# --- 6. the member's trail carries the same derivation ----------------------
m._verify_broker_secret = lambda request: "member@x.org"
conn = m.get_db()
seed_guest_ledger(conn, "member@x.org", "friend@x.org")
seed_account(conn, "friend@x.org", account_type="guest", active=1)
conn.commit()
conn.close()
CLOUDRON_USERS["uid-friend@x.org"] = {"inviteAccepted": False, "username": None}
view = asyncio.run(m.broker_guest_list(make_request("GET")))
trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"]
check("trail: un-accepted guest carries state='invited'",
len(trail_guests) == 1 and trail_guests[0]["state"] == "invited",
str(view["trail"]))
check("trail: ledger status still 'active' underneath",
trail_guests and trail_guests[0]["status"] == "active", str(view["trail"]))
CLOUDRON_USERS["uid-friend@x.org"]["inviteAccepted"] = True
view = asyncio.run(m.broker_guest_list(make_request("GET")))
trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"]
check("trail: after acceptance state follows the ledger status",
trail_guests and trail_guests[0]["state"] == "active", str(view["trail"]))
conn = m.get_db()
conn.execute("UPDATE members SET active = 0 WHERE email = 'friend@x.org'")
conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'friend@x.org'")
conn.commit()
conn.close()
view = asyncio.run(m.broker_guest_list(make_request("GET")))
trail_guests = [t for t in view["trail"] if t.get("kind") == "guest"]
check("trail: an ended guest shows its ledger status, never 'invited'",
trail_guests and trail_guests[0]["state"] == "expired", str(view["trail"]))
failed = [name for name, ok, _ in results if not ok]
print()
print(f"{len(results) - len(failed)}/{len(results)} checks passed")
if failed:
print("FAILED: " + ", ".join(failed))
sys.exit(1)
if __name__ == "__main__":
main()
+383
View File
@@ -0,0 +1,383 @@
#!/usr/bin/env python3
"""Guest-account lifecycle tests — structurally isolated from live services.
WHY THIS EXISTS
Guest accounts (operator feature, 2026-11-08) touch money ($2 of credits),
Cloudron groups and email. Every path proven here runs against a FIXTURE
database with the network layer REPLACED BY A RAISING GUARD: any code path
that tries to reach Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP
outside the stubs fails the test loudly instead of acting on live systems.
GUARDS (abuse protection — one guest per inviter per 30d, one per recipient)
1. An inviter who is not an active member is refused.
2. A SECOND guest by the same inviter within the window is refused.
3. A recipient who already received a guest (ledger) or already has a
portal row is refused.
PROVISION
4. The full guest pipeline marks the row (account_type='guest', balance 0,
credit_balance 5, guest_expires_at set, anchor day kept), records
inviter → recipient in the guests ledger, subscribes the newsletter,
and sends the guest welcome email — no Loomio/Matrix calls.
CONVERT (guest → member)
5. Group moves guests → members; allowance set to MEMBER_BUDGET; the
unspent guest credit carries; the cap lifts to allowance + credits
(15 + 5); the anchor day is KEPT; the congrats email goes out; the
guests-ledger row becomes 'converted'; Loomio + Matrix syncs fire.
LIFECYCLE (sweep pass)
6. An EXPIRED guest (past guest_expires_at, credits remaining) is
deactivated by the sweep: row active=0, group → inactive, budget
zeroed, newsletter unsubscribed, ledger status 'expired'.
7. A DEPLETED guest (spend reached the credits) is deactivated likewise,
status 'depleted'.
8. A healthy guest (not expired, credits left) is left untouched.
Runnable: python3 tests/test_guest_lifecycle.py (from the repo root)
"""
import asyncio
import base64
import os
import sys
import tempfile
from datetime import datetime, timedelta, timezone
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
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"]
results = []
def check(name, ok, detail=""):
results.append((name, bool(ok), detail))
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
class _NoNetwork:
"""Guard: ANY httpx client construction inside the test is a failure."""
def __init__(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
def __call__(self, *a, **k): # pragma: no cover
raise AssertionError("live network attempted during fixture test")
m.httpx.AsyncClient = _NoNetwork
# --- recorders -------------------------------------------------------------- #
calls = {"group": [], "budget": [], "pin": [], "email": [], "listmonk": [],
"loomio": 0, "matrix": 0, "revoke": [], "owui": [], "subscribe": []}
async def fake_fetch_users(client):
# No existing Cloudron account for the fixture addresses.
return []
async def fake_email_exists(email):
return False
async def rec_switch(user_id, add_gid=None, remove_gids=()):
calls["group"].append((user_id, add_gid))
async def rec_group(user_id, group_id=None):
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
async def rec_budget(team_id, budget):
calls["budget"].append((team_id, round(float(budget), 2)))
async def rec_pin(team_id, reset_at):
calls["pin"].append((team_id, str(reset_at)))
def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject))
return True # send_email's contract: truthy = the send left the building
async def rec_listmonk(email, subscribe):
calls["listmonk"].append((email, bool(subscribe)))
async def rec_loomio():
calls["loomio"] += 1
async def rec_matrix():
calls["matrix"] += 1
async def rec_revoke(email):
calls["revoke"].append(email)
return True
async def rec_owui(uid):
calls["owui"].append(uid)
return True
CALL_KEYS = ("group", "budget", "pin", "email", "listmonk", "loomio", "matrix",
"revoke", "owui", "subscribe")
def reset_calls():
for k in CALL_KEYS:
calls[k] = 0 if k in ("loomio", "matrix") else []
TEAM_SPEND = {} # team_id -> cycle spend (default 0.0)
def fake_team_db(team_id):
return {"max_budget": None, "spend": TEAM_SPEND.get(team_id, 0.0),
"budget_reset_at": None}
async def fake_team_id(email):
return "team-" + email
async def fake_get_or_create_team(email, budget, budget_duration="30d"):
return "team-fixture"
async def fake_create_key(email, budget, team_id):
return "sk-fixture-key"
async def fake_user_create(email, name):
return "uid-fixture"
async def fake_invite_link(user_id):
return "https://my.example/setupaccount.html?inviteToken=x"
async def fake_activated(user_id):
return False
m.cloudron_fetch_all_users = fake_fetch_users
m.cloudron_email_exists = fake_email_exists
m.cloudron_switch_group = rec_switch
m.cloudron_set_group = rec_group
m.cloudron_set_active = rec_group # same signature (uid, bool); recorded nowhere critical
m.cloudron_create_user = fake_user_create
m.cloudron_get_invite_link = fake_invite_link
m.cloudron_is_activated = fake_activated
m.litellm_get_or_create_team = fake_get_or_create_team
m.litellm_create_key = fake_create_key
m.litellm_team_id_for_email = fake_team_id
m.litellm_update_team_budget = rec_budget
m.litellm_pin_reset_date = rec_pin
m.get_team_budget_from_db = fake_team_db
m.send_email = rec_email
m.listmonk_sync = rec_listmonk
m.sync_loomio_memberships = rec_loomio
m.sync_matrix_space = rec_matrix
m.revoke_member_litellm_access = rec_revoke
m.owui_add_to_members_group = rec_owui
def seed_member(conn, email, account_type="member", active=1, balance=None,
credits=None, anchor=None, expires=None, slug=""):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type, anchor_day, guest_expires_at) "
"VALUES (?, 'enc', 'uid-' || ?, ?, ?, ?, ?, ?, ?, ?)",
(email, email, slug, active,
balance if balance is not None else m.MEMBER_BUDGET,
credits if credits is not None else 0.0,
account_type, anchor, expires),
)
def row_of(conn, email, col):
return conn.execute(f"SELECT {col} FROM members WHERE email = ?", (email,)).fetchone()[0]
def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
m._ensure_allowance_tables(conn) # anchor_day column (as production does)
conn.close()
inviter = "member-one@x.org"
# --- 1. inviter must be an active member -------------------------------
conn = m.get_db()
seed_member(conn, inviter, active=1)
conn.commit()
conn.close()
conn = m.get_db()
check("guard: non-member inviter refused",
m.guest_provision_guard(conn, "stranger@x.org", "friend@x.org") is not None)
check("guard: active member inviter allowed",
m.guest_provision_guard(conn, inviter, "friend@x.org") is None)
# --- 2. one guest per inviter per 30 days -------------------------------
conn.execute(
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
"VALUES (?, 'friend@x.org', datetime('now'), 'active')", (inviter,))
conn.commit()
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
check("guard: second guest within 30 days refused", refusal is not None and "30 days" in refusal,
str(refusal))
# backdate the ledger row: outside the window the inviter may guest again
conn.execute("UPDATE guests SET created_at = datetime('now', '-31 days')")
check("guard: guest allowed again after the window",
m.guest_provision_guard(conn, inviter, "friend2@x.org") is None)
# --- 3. one guest per recipient ever ------------------------------------
conn.execute("UPDATE guests SET recipient_email = 'friend2@x.org'")
conn.commit()
refusal = m.guest_provision_guard(conn, inviter, "friend2@x.org")
check("guard: recipient already in ledger refused", refusal is not None, str(refusal))
seed_member(conn, "existing@x.org", account_type="member", active=1)
conn.commit()
check("guard: existing member as recipient refused",
m.guest_provision_guard(conn, inviter, "existing@x.org") is not None)
conn.close()
# --- 4. the full guest pipeline (provision_guest_member) ------------------
reset_calls()
asyncio.run(m.provision_guest_member("invited@x.org", "Invited Friend", inviter))
conn = m.get_db()
check("provision: row marked guest", row_of(conn, "invited@x.org", "account_type") == "guest")
check("provision: allowance balance 0", row_of(conn, "invited@x.org", "balance") == 0.0)
check("provision: $2 credit", row_of(conn, "invited@x.org", "credit_balance") == 2.0)
check("provision: guest_expires_at set", bool(row_of(conn, "invited@x.org", "guest_expires_at")))
check("provision: group = guests group",
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
check("provision: cap set to 2.00 (one-time)",
(calls["budget"] and calls["budget"][0][1] == 2.0), str(calls["budget"]))
check("provision: invitation email sent (merged invite + welcome)",
any("invited to the Inference Cooperative" in s for _, s in calls["email"]), str(calls["email"]))
check("provision: newsletter subscribed",
("invited@x.org", True) in calls["listmonk"], str(calls["listmonk"]))
check("provision: NO loomio/matrix calls", calls["loomio"] == 0 and calls["matrix"] == 0)
g = conn.execute("SELECT inviter_email, recipient_email, status FROM guests "
"WHERE recipient_email = 'invited@x.org'").fetchone()
check("provision: guests ledger records inviter→recipient",
bool(g) and g[0] == inviter and g[1] == "invited@x.org" and g[2] == "active", str(g))
conn.close()
# --- 5. conversion (guest → member) -------------------------------------
reset_calls()
anchor_before = row_of(m.get_db(), "invited@x.org", "anchor_day")
asyncio.run(m.convert_guest_to_member("invited@x.org", "Invited Friend", "invitedfriend"))
conn = m.get_db()
check("convert: account_type back to member",
row_of(conn, "invited@x.org", "account_type") == "member")
check("convert: allowance lifted to MEMBER_BUDGET",
row_of(conn, "invited@x.org", "balance") == m.MEMBER_BUDGET)
check("convert: unspent guest credit carried",
row_of(conn, "invited@x.org", "credit_balance") == 2.0)
check("convert: group moved to members",
calls["group"] and calls["group"][0][1] == m.MEMBERS_GROUP_ID, str(calls["group"]))
check("convert: cap lifted to 17.00 (15 + 2 credits)",
(calls["budget"] and calls["budget"][0][1] == m.MEMBER_BUDGET + 2.0), str(calls["budget"]))
check("convert: anchor day kept", row_of(conn, "invited@x.org", "anchor_day") == anchor_before)
check("convert: congrats email sent",
any("member now" in s for _, s in calls["email"]), str(calls["email"]))
check("convert: Loomio + Matrix syncs fired", calls["loomio"] == 1 and calls["matrix"] == 1)
check("convert: guests ledger status converted",
conn.execute("SELECT status FROM guests WHERE recipient_email='invited@x.org'"
).fetchone()[0] == "converted")
check("convert: expiry cleared", row_of(conn, "invited@x.org", "guest_expires_at") is None)
conn.close()
# --- 6/7/8. lifecycle sweep: expired / depleted / healthy ---------------
past = (datetime.now(timezone.utc) - timedelta(days=1)).isoformat()
future = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat()
conn = m.get_db()
seed_member(conn, "expired@x.org", account_type="guest", active=1, balance=0.0,
credits=5.0, anchor=8, expires=past)
seed_member(conn, "healthy@x.org", account_type="guest", active=1, balance=0.0,
credits=5.0, anchor=8, expires=future)
seed_member(conn, "depleted@x.org", account_type="guest", active=1, balance=0.0,
credits=5.0, anchor=8, expires=future)
# A guest whose guest ended BEFORE the reaching-limits email shipped: the
# sweep's catch-up pass must tell them exactly once.
seed_member(conn, "already-gone@x.org", account_type="guest", active=0, balance=0.0,
credits=5.0, anchor=8, expires=past)
for e in ("expired@x.org", "healthy@x.org", "depleted@x.org", "already-gone@x.org"):
conn.execute("INSERT INTO guests (inviter_email, recipient_email, guest_expires_at, status) "
"VALUES (?, ?, ?, 'active')", (inviter, e, future))
conn.execute("UPDATE guests SET status = 'expired' WHERE recipient_email = 'already-gone@x.org'")
conn.commit()
conn.close()
TEAM_SPEND.clear() # healthy + expired have unspent credits
reset_calls()
out = asyncio.run(m.reconcile_guest_lifecycles())
conn = m.get_db()
check("lifecycle: expired guest deactivated by the sweep",
row_of(conn, "expired@x.org", "active") == 0)
check("lifecycle: expired guest group → inactive",
any(e == "uid-expired@x.org" and g == m.INACTIVE_GROUP_ID
for e, g in calls["group"]), str(calls["group"]))
check("lifecycle: expired guest budget zeroed (revoke path called)",
"expired@x.org" in calls["revoke"], str(calls["revoke"]))
check("lifecycle: expired guest unsubscribed",
("expired@x.org", False) in calls["listmonk"], str(calls["listmonk"]))
check("lifecycle: ledger status 'expired'",
conn.execute("SELECT status FROM guests WHERE recipient_email='expired@x.org'"
).fetchone()[0] == "expired")
check("lifecycle: healthy guest untouched",
row_of(conn, "healthy@x.org", "active") == 1 and
not any(e == "uid-healthy@x.org" for e, _ in calls["group"]))
check("lifecycle: counts report expired=1 depleted=0",
out.get("expired") == 1 and out.get("depleted") == 0, str(out))
check("lifecycle: reaching-limits email sent once to the expired guest",
sum(1 for to, s in calls["email"]
if to == "expired@x.org" and "guest access has ended" in s) == 1,
str(calls["email"]))
check("lifecycle: catch-up told the pre-shutdown guest exactly once",
sum(1 for to, s in calls["email"]
if to == "already-gone@x.org" and "guest access has ended" in s) == 1,
str(calls["email"]))
check("lifecycle: notice counts in the sweep result",
out.get("lapse_notices") == 2, str(out))
conn.close()
TEAM_SPEND["team-depleted@x.org"] = 5.5 # depleted: spend reached the credits
reset_calls()
out = asyncio.run(m.reconcile_guest_lifecycles())
conn = m.get_db()
check("lifecycle: depleted guest deactivated",
row_of(conn, "depleted@x.org", "active") == 0)
check("lifecycle: depleted ledger status",
conn.execute("SELECT status FROM guests WHERE recipient_email='depleted@x.org'"
).fetchone()[0] == "depleted")
check("lifecycle: healthy guest STILL untouched on second pass",
row_of(conn, "healthy@x.org", "active") == 1)
check("lifecycle: counts report depleted=1", out.get("depleted") == 1, str(out))
check("lifecycle: depleted guest also told once",
sum(1 for to, s in calls["email"]
if to == "depleted@x.org" and "guest access has ended" in s) == 1,
str(calls["email"]))
check("lifecycle: ONCE per guest — second sweep sent no repeat notices",
sum(1 for to, s in calls["email"] if "guest access has ended" in s) == 1
and m.guest_lapse_notice_sent("expired@x.org")
and m.guest_lapse_notice_sent("already-gone@x.org"),
str(calls["email"]))
check("lifecycle: healthy guest never emailed",
not any(to == "healthy@x.org" for to, _ in calls["email"]), str(calls["email"]))
conn.close()
failed = [r for r in results if not r[1]]
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+444
View File
@@ -0,0 +1,444 @@
#!/usr/bin/env python3
"""Member self-serve guest invitations — structurally isolated from live services.
WHY THIS EXISTS
The member path creates REAL guest accounts ($2 of credits, Cloudron users,
invitation email) IMMEDIATELY on a valid request (operator decision,
2026-11-08: the trial-era approval gate is gone — nothing waits, nothing is
pending). Every path proven here runs against a FIXTURE database with the
network layer REPLACED BY A RAISING GUARD: any code path that tries to reach
Cloudron, LiteLLM, OC, Listmonk, Loomio, Matrix or SMTP outside the stubs
fails the test loudly instead of acting on live systems.
IMMEDIATE PROVISIONING (POST /broker/guests, member broker identity)
1. A valid member invitation provisions at once through the FULL guest
pipeline: row marked account_type='guest', the $2 non-expiring credit,
the LiteLLM cap at $2, guest_expires_at set (the 60-day box), a guests
ledger row inviter → recipient, the invitation email (the INVITING
member named in it), and the newsletter subscription.
2. NO guest_requests row is written — no pending state exists anywhere.
3. The member's own trail shows the new guest (active) and the rolling
window flips them ineligible with next_eligible_at.
PROTECTIONS (member path — every rule still enforced)
4. A SECOND invitation by the same member inside the rolling 30-day
window is refused (one guest per member per month — the window is
counted from the guests ledger).
5. A recipient who is an EXISTING MEMBER is refused.
6. A recipient with a PRIOR guest (ledger row) is refused.
7. A recipient on MANUAL_MEMBERS is refused.
8. A non-member (no portal row) and a GUEST account are refused — only
members invite guests.
9. Re-inviting an address that was just provisioned is refused (one guest
per recipient ever — the moved-state guard behind the endpoint).
10. The GATE IS GONE: the app defines no guest-request approve/reject
routes and no GUEST_AUTO_APPROVE flag — nothing to approve anywhere.
LEGACY HISTORY
11. A rejected request from the trial period still shows in the member's
trail (history only); a rejected request blocks nothing.
PANEL LEDGER FEED
12. GET /admin/guest-ledger serves the guests ledger (the panel's
duplicate-send guard reads it).
Runnable: python3 tests/test_guest_requests.py (from the repo root)
"""
import asyncio
import base64
import os
import sys
import tempfile
from datetime import datetime, timedelta, timezone
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
os.environ["ADMIN_TOKEN"] = "test-admin-token" # admin endpoints authenticate on this
os.environ.setdefault("GUESTS_GROUP_ID", "gid-fixture-guests")
os.environ.setdefault("MEMBERS_GROUP_ID", "gid-fixture-members")
os.environ.setdefault("INACTIVE_GROUP_ID", "gid-fixture-inactive")
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"]
results = []
def check(name, ok, detail=""):
results.append((name, bool(ok), detail))
print(("PASS " if ok else "FAIL ") + name + (f" [{detail}]" if detail and not ok else ""))
class _NoNetwork:
"""Guard: ANY httpx client construction inside the test is a failure."""
def __init__(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
def __call__(self, *a, **k): # pragma: no cover
raise AssertionError("live network attempted during fixture test")
# The trail now derives each guest's invited/active state from the Cloudron
# user record, so it opens an httpx client around a STUBBED users fetch: the
# client is constructible but every real HTTP attempt still raises — the
# guard, kept.
class _FakeClient(_NoNetwork):
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
async def post(self, *a, **k):
raise AssertionError("live network attempted during fixture test")
m.httpx.AsyncClient = _FakeClient
# Cloudron users fixture for the invited-state derivation: the fixture guest's
# Cloudron user id is 'uid-fixture' (fake_user_create below) with the invite
# NOT yet accepted. Tests flip `inviteAccepted` to simulate acceptance.
CLOUDRON_USERS = {"uid-fixture": {"inviteAccepted": False, "username": None}}
async def fake_fetch_users(client):
return [{"id": uid, "username": v.get("username"),
"inviteAccepted": v.get("inviteAccepted", False)}
for uid, v in CLOUDRON_USERS.items()]
m.cloudron_fetch_all_users = fake_fetch_users
# --- recorders (same contract as test_guest_lifecycle) ---------------------- #
calls = {"group": [], "budget": [], "email": [], "listmonk": [], "loomio": 0,
"matrix": 0}
async def fake_email_exists(email):
return False
m.cloudron_email_exists = fake_email_exists
async def rec_switch(user_id, add_gid=None, remove_gids=()):
calls["group"].append((user_id, add_gid))
async def rec_group(user_id, group_id=None):
calls["group"].append((user_id, group_id or m.MEMBERS_GROUP_ID))
def rec_email(to, subject, text_body=None, html_body=None):
calls["email"].append((to, subject, text_body or ""))
return True
async def rec_listmonk(email, subscribe):
calls["listmonk"].append((email, bool(subscribe)))
async def rec_loomio():
calls["loomio"] += 1
async def rec_matrix():
calls["matrix"] += 1
async def fake_team_id(email):
return "team-" + email
async def fake_get_or_create_team(email, budget, budget_duration="30d"):
return "team-fixture"
async def fake_create_key(email, budget, team_id):
return "***"
async def fake_user_create(email, name):
return "uid-fixture"
async def fake_invite_link(user_id):
return "https://my.example/setupaccount.html?inviteToken=x"
async def fake_activated(user_id):
return False
def fake_team_db(team_id):
return {"max_budget": None, "spend": 0.0, "budget_reset_at": None}
m.cloudron_switch_group = rec_switch
m.cloudron_set_group = rec_group
m.cloudron_set_active = rec_group
m.cloudron_create_user = fake_user_create
m.cloudron_get_invite_link = fake_invite_link
m.cloudron_is_activated = fake_activated
m.litellm_get_or_create_team = fake_get_or_create_team
m.litellm_create_key = fake_create_key
m.litellm_team_id_for_email = fake_team_id
m.litellm_update_team_budget = async_rec_budget = (lambda *a: None) # replaced below
m.get_team_budget_from_db = fake_team_db
m.send_email = rec_email
m.listmonk_sync = rec_listmonk
m.sync_loomio_memberships = rec_loomio
m.sync_matrix_space = rec_matrix
async def rec_budget(team_id, budget):
calls["budget"].append((team_id, round(float(budget), 2)))
m.litellm_update_team_budget = rec_budget
# --- real Request objects (the slowapi limiter decorator requires them) ----- #
from starlette.requests import Request as StarletteRequest # noqa: E402
import json as _json # noqa: E402
def make_request(method="GET", body=None, headers=None):
raw = _json.dumps(body or {}).encode()
headers = dict(headers or {})
if raw and "content-length" not in headers:
headers["content-length"] = str(len(raw))
async def receive():
return {"type": "http.request", "body": raw, "more_body": False}
scope = {
"type": "http", "method": method, "path": "/", "query_string": b"",
"headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
"server": ("testserver", 80), "client": ("testclient", 123),
}
return StarletteRequest(scope, receive)
def seed_member(conn, email, account_type="member", active=1):
conn.execute(
"INSERT INTO members (email, key_token, cloudron_user_id, slug, active, "
"balance, credit_balance, account_type) "
"VALUES (?, 'enc', 'uid-' || ?, '', ?, ?, 0, ?)",
(email, email, active, m.MEMBER_BUDGET, account_type),
)
def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
m._ensure_allowance_tables(conn)
inviter = "member-one@x.org"
seed_member(conn, inviter, active=1)
conn.execute("UPDATE members SET slug = 'member-one' WHERE email = ?", (inviter,))
conn.commit()
conn.close()
# --- 1-3. a valid invitation PROVISIONS IMMEDIATELY ----------------------
reset = lambda: calls.update({"group": [], "budget": [], "email": [],
"listmonk": [], "loomio": 0, "matrix": 0})
reset()
conn = m.get_db()
refusal = m.guest_request_guard(conn, inviter, "friend@x.org")
check("guard: passes for an active member + fresh recipient",
refusal is None, str(refusal))
conn.close()
async def post_guest(email_addr, recipient, name=""):
"""Drive the POST /broker/guests handler directly (auth is stubbed)."""
m._verify_broker_secret = lambda request: email_addr
return await m.broker_guest_invite(
make_request("POST", {"email": recipient, "name": name}))
outcome = asyncio.run(post_guest(inviter, "friend@x.org", "Friend"))
check("invite: status is provisioned (immediate, nothing pending)",
outcome.get("status") == "provisioned", str(outcome))
check("invite: no pending_approval status anywhere in the response",
"pending" not in str(outcome).lower(), str(outcome))
check("invite: response carries the cap and the box",
outcome.get("budget") == m.GUEST_BUDGET
and outcome.get("expires_in_days") == int(m.GUEST_DAYS), str(outcome))
conn = m.get_db()
acct = conn.execute(
"SELECT account_type, balance, credit_balance, guest_expires_at "
"FROM members WHERE email = ?", ("friend@x.org",)).fetchone()
check("invite: recipient row marked guest",
acct and acct[0] == "guest", str(acct))
check("invite: allowance balance 0 (the $2 is all credit)",
acct and acct[1] == 0.0, str(acct))
check("invite: $2 non-expiring credit granted",
acct and acct[2] == m.GUEST_BUDGET, str(acct))
check("invite: 60-day box set (guest_expires_at)",
acct and bool(acct[3]), str(acct))
if acct and acct[3]:
exp = datetime.strptime(str(acct[3])[:19], "%Y-%m-%d %H:%M:%S")
delta = exp - datetime.now(timezone.utc).replace(tzinfo=None)
check("invite: expiry sits ~GUEST_DAYS out",
timedelta(0) < delta <= timedelta(days=int(m.GUEST_DAYS)),
str(acct[3]))
ledger = conn.execute(
"SELECT inviter_email, recipient_email, status FROM guests "
"WHERE recipient_email = 'friend@x.org'").fetchall()
check("invite: ledger row inviter → recipient (active)",
ledger and ledger[0][0] == inviter and ledger[0][2] == "active", str(ledger))
reqs = conn.execute("SELECT COUNT(*) FROM guest_requests").fetchone()[0]
check("invite: NO guest_requests row written (no pending state exists)",
reqs == 0, str(reqs))
conn.close()
check("invite: LiteLLM cap set to the guest budget (one-time)",
calls["budget"] == [("team-fixture", round(m.GUEST_BUDGET, 2))],
str(calls["budget"]))
check("invite: Cloudron user created into the guests group",
calls["group"] and calls["group"][0][1] == m.GUESTS_GROUP_ID, str(calls["group"]))
check("invite: invitation email sent to the recipient AT ONCE",
len(calls["email"]) == 1 and calls["email"][0][0] == "friend@x.org",
str(calls["email"]))
check("invite: invitation email NAMES the inviting member",
"member-one" in calls["email"][0][2], str(calls["email"]))
check("invite: newsletter subscribe fired",
calls["listmonk"] == [("friend@x.org", True)], str(calls["listmonk"]))
check("invite: NO Loomio/Matrix invites", not calls["loomio"] and not calls["matrix"])
# --- 3. the member's own trail shows the guest + the closed window -------
m._verify_broker_secret = lambda request: inviter
view = asyncio.run(m.broker_guest_list(make_request("GET")))
guests = [t for t in view["trail"] if t.get("kind") == "guest"]
check("trail: the new guest visible to the member as active",
len(guests) == 1 and guests[0]["recipient"] == "friend@x.org"
and guests[0]["status"] == "active", str(view["trail"]))
check("trail: un-accepted invite shows state='invited' (never reads active)",
guests and guests[0]["state"] == "invited", str(guests))
CLOUDRON_USERS["uid-fixture"]["inviteAccepted"] = True # simulate acceptance
view = asyncio.run(m.broker_guest_list(make_request("GET")))
guests = [t for t in view["trail"] if t.get("kind") == "guest"]
check("trail: after acceptance the state follows the ledger (active)",
guests and guests[0]["state"] == "active", str(guests))
check("trail: no pending entries in the member's trail",
not any(t.get("status") == "pending" for t in view["trail"]),
str(view["trail"]))
check("trail: member is not eligible inside the 30-day window",
view["eligible"] is False, str(view["eligible"]))
check("trail: next_eligible_at given", bool(view["next_eligible_at"]),
str(view["next_eligible_at"]))
# --- 4. second invitation inside the window: refused (1/month) -----------
conn = m.get_db()
refusal = m.guest_request_guard(conn, inviter, "friend2@x.org")
check("limit: second guest within 30 days refused",
refusal is not None and "30 days" in refusal, str(refusal))
# another member may still invite a DIFFERENT recipient
seed_member(conn, "member-two@x.org", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "member-two@x.org", "other@x.org")
check("limit: a DIFFERENT member is not blocked by someone else's guest",
refusal is None, str(refusal))
conn.close()
# --- 5-8. recipient-side + inviter-side refusal paths ---------------------
conn = m.get_db()
seed_member(conn, "existing@x.org", account_type="member", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "member-two@x.org", "existing@x.org")
check("refusal: existing member as recipient", refusal is not None, str(refusal))
conn.execute(
"INSERT INTO guests (inviter_email, recipient_email, created_at, status) "
"VALUES ('member-two@x.org', 'prior@x.org', datetime('now'), 'active')")
conn.commit()
refusal = m.guest_request_guard(conn, "member-two@x.org", "prior@x.org")
check("refusal: prior guest (ledger) as recipient", refusal is not None, str(refusal))
conn.close()
old_manual = set(m.MANUAL_MEMBERS)
m.MANUAL_MEMBERS = {"manual@x.org"}
conn = m.get_db()
refusal = m.guest_request_guard(conn, "member-two@x.org", "manual@x.org")
check("refusal: recipient on MANUAL_MEMBERS", refusal is not None, str(refusal))
conn.close()
m.MANUAL_MEMBERS = old_manual
# --- 8. only members reach the member path -------------------------------
conn = m.get_db()
# a non-member: no portal row at all → guest_provision_guard refuses
refusal = m.guest_request_guard(conn, "stranger@x.org", "someone@x.org")
check("refusal: non-member inviter", refusal is not None, str(refusal))
seed_member(conn, "guest-acct@x.org", account_type="guest", active=1)
conn.commit()
refusal = m.guest_request_guard(conn, "guest-acct@x.org", "someone@x.org")
check("refusal: a GUEST cannot invite guests", refusal is not None, str(refusal))
conn.close()
# --- 9. re-inviting a just-provisioned address is refused (moved state) --
reset()
conn = m.get_db()
seed_member(conn, "member-three@x.org", active=1)
conn.commit()
conn.close()
try:
asyncio.run(post_guest("member-three@x.org", "friend@x.org"))
check("moved-state: duplicate invite refused", False, "no exception raised")
except Exception as e:
code = getattr(e, "status_code", None)
check("moved-state: duplicate invite refused (429)",
code == 429 and "already received a guest account" in str(getattr(e, "detail", e)),
str(e))
conn = m.get_db()
reqs = conn.execute("SELECT COUNT(*) FROM guest_requests").fetchone()[0]
check("moved-state: still NO pending state written", reqs == 0, str(reqs))
conn.close()
# --- 10. the gate is GONE from the app -----------------------------------
paths = {getattr(r, "path", "") for r in m.app.routes}
gone = [p for p in paths if "guest-requests" in p]
check("gate gone: no guest-request routes remain on the app",
not gone, str(sorted(gone)))
check("gate gone: GUEST_AUTO_APPROVE no longer exists",
not hasattr(m, "GUEST_AUTO_APPROVE"), str(getattr(m, "GUEST_AUTO_APPROVE", None)))
# --- 11. legacy rejected history shows in the trail; blocks nothing ------
conn = m.get_db()
conn.execute(
"INSERT INTO guest_requests (inviter_email, recipient_email, status, decided_at, note) "
"VALUES (?, 'rejected-back-then@x.org', 'rejected', datetime('now'), 'not right now')",
(inviter,))
conn.commit()
conn.close()
m._verify_broker_secret = lambda request: inviter
view = asyncio.run(m.broker_guest_list(make_request("GET")))
rej = [t for t in view["trail"] if t.get("kind") == "request"
and t.get("recipient") == "rejected-back-then@x.org"]
check("legacy: a rejected request still shows in the trail (history)",
len(rej) == 1 and rej[0]["status"] == "rejected", str(view["trail"]))
check("legacy: no pending entries ever appear in the trail",
not any(t.get("status") == "pending" for t in view["trail"]),
str(view["trail"]))
conn = m.get_db()
# (member-three is already seeded and active with a fresh recipient; the
# point is a legacy rejection blocks nothing)
refusal = m.guest_request_guard(conn, "member-three@x.org", "fresh@x.org")
check("legacy: a legacy rejection does not count against anyone's window",
refusal is None, str(refusal))
conn.close()
# --- 12. the panel's ledger feed -----------------------------------------
fed = asyncio.run(m.admin_guest_ledger(
make_request("GET", headers={"X-Admin-Token": "test-admin-token"})))
recips = [r["recipient"] for r in fed.get("ledger", [])]
check("ledger feed: serves the guests ledger for the panel's guard",
"friend@x.org" in recips and "prior@x.org" in recips, str(fed))
check("ledger feed: no pending key in the payload",
"pending" not in fed and "decided" not in fed, str(sorted(fed.keys())))
print()
passed = sum(1 for _, ok, _ in results if ok)
print(f"{passed}/{len(results)} checks passed")
return 0 if passed == len(results) else 1
if __name__ == "__main__":
sys.exit(main())
+316
View File
@@ -0,0 +1,316 @@
#!/usr/bin/env python3
"""Regression test: the Loomio sync is idempotent and non-duplicating.
WHY THIS EXISTS
On 2026-11-04 a live run of sync_loomio_memberships() emailed a Loomio invite
notification to (effectively) the whole membership. The guards that must hold
are proven here on a FIXTURE db with the network STUBBED:
ADD / dedupe
1. A member already in the Loomio group is skipped SILENTLY — no invite
payload ever contains their address.
2. members.loomio_invited_at is a second guard: an address we have handed
over before is never sent again, even if it is not (yet) visible in the
live roster.
3. `remove_absent` is never sent (no evict-then-re-add re-invite path).
4. FAIL CLOSED — if the live roster cannot be read, nothing is sent.
5. Running the sync twice adds nobody a second time.
REMOVE / reconciliation (a deactivation MUST still propagate to Loomio)
6. A member in the group who is no longer active is removed exactly once.
7. The operator allowlist is never removed, even when not active.
8. Removal is targeted — it never re-sends a present member's address, so it
cannot re-invite or notify anyone who is staying.
9. A second run removes nobody again (the roster no longer lists them).
10. remove_loomio_membership treats 404 as success (idempotent, no error).
The sync is ON by default (kill switch LOOMIO_SYNC_ENABLED=0 pauses it).
Runnable: python3 tests/test_loomio_guard.py (from the repo root)
"""
import os
import sys
import tempfile
import asyncio
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["LOOMIO_API_KEY"] = "test-user-key"
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
os.environ["LOOMIO_GROUP_ID"] = "1"
# Leave LOOMIO_SYNC_ENABLED unset -> the sync must default to ENABLED.
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"]
# Keep the membership assertions isolated: no extra keep accounts, and no
# username-fix pass (it makes its own /api/b3/users calls).
m.LOOMIO_ALWAYS_KEEP = ["keep@x.org"]
posts = [] # every b2/memberships POST payload
deletes = [] # every b3 membership DELETE url
ROSTER = {} # email -> membership id currently in the group
GET_FAILS = False # exercise fail-closed
DELETE_STATUS = 200 # toggle to prove 404 tolerance
ADDED_OMIT = set() # emails the fake Loomio accepts but does NOT add
class FakeResp:
def __init__(self, status=200, payload=None):
self.status_code = status
self._payload = payload or {}
self.text = str(payload or {})
def raise_for_status(self):
if self.status_code >= 400:
raise RuntimeError(f"HTTP {self.status_code}")
def json(self):
return self._payload
class FakeClient:
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, url, headers=None, params=None):
if GET_FAILS:
raise RuntimeError("simulated Loomio roster read failure")
offset = (params or {}).get("offset", 0)
limit = (params or {}).get("limit", 50)
rows = [{"id": i, "user_email": e} for e, i in ROSTER.items()]
page = rows[offset:offset + limit]
return FakeResp(200, {"memberships": page, "meta": {"total": len(rows)}})
async def post(self, url, headers=None, json=None):
posts.append({"url": url, "json": json or {}})
sent = (json or {}).get("emails", [])
return FakeResp(200, {"added_emails": [e for e in sent if e not in ADDED_OMIT]})
async def delete(self, url, headers=None):
deletes.append(url)
return FakeResp(DELETE_STATUS)
async def patch(self, *a, **k):
return FakeResp(200, {})
async def fake_active():
# active members: new@ / old@ are NOT in the group; member@ IS.
return ["new@x.org", "old@x.org", "member@x.org"]
async def fake_activated(emails):
return emails
async def noop_fix(_client):
return {}
results = []
def check(name, ok):
results.append((name, ok))
async def main():
global GET_FAILS, ROSTER, DELETE_STATUS, ADDED_OMIT
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
for e in ("new@x.org", "old@x.org", "member@x.org"):
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (e,))
conn.commit()
conn.close()
cols = [r[1] for r in m.get_db().execute("PRAGMA table_info(members)").fetchall()]
m.get_db().close()
check("migration: members.loomio_invited_at exists", "loomio_invited_at" in cols)
check("migration: members.loomio_opt_out exists", "loomio_opt_out" in cols)
m.get_active_member_emails = fake_active
m.filter_loomio_activated = fake_activated
m.httpx.AsyncClient = FakeClient
m.loomio_fix_usernames = noop_fix
check("default: sync is ENABLED when the flag is unset", m.LOOMIO_SYNC_ENABLED is True)
# Loomio group currently holds: an active member (member@), and the operator
# allowlist account (keep@) which is NOT an active portal member.
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
# --- 1. ADD path: only the never-seen address is invited. ---
m.mark_loomio_invited("old@x.org") # recorded -> excluded by layer (b)
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
body = posts[0]["json"] if posts else {}
check("add: exactly one invite call", len(posts) == 1)
check("add: only the never-seen address is invited", body.get("emails") == ["new@x.org"])
check("add: a member ALREADY in Loomio is skipped silently",
"member@x.org" not in (body.get("emails") or []))
check("add: the record guard excludes a previously-invited address",
"old@x.org" not in (body.get("emails") or []))
check("add: remove_absent is NEVER sent (no re-add path)", "remove_absent" not in body)
check("add: the newly-invited address is recorded",
m.get_loomio_invited_at("new@x.org") is not None)
check("reconcile: a stamped-but-absent member's stamp is cleared (not yet re-invited)",
m.get_loomio_invited_at("old@x.org") is None)
check("add: nothing removed when nobody has lapsed", deletes == [])
# --- 2. Second run: the cleared member is invited once, then recorded. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99} # Loomio now has new@
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
body = posts[0]["json"] if posts else {}
check("reconcile: the cleared member is re-invited on the next pass",
body.get("emails") == ["old@x.org"])
check("reconcile: the re-invite is recorded", m.get_loomio_invited_at("old@x.org") is not None)
check("reconcile: a present member is never re-invited",
"member@x.org" not in (body.get("emails") or []))
# --- 2b. Third run: nothing left to invite. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("double-run: no second invite", posts == [])
check("double-run: no removals", deletes == [])
# --- 3. REMOVE path: a lapsed member is removed exactly once. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88, "lapsed@x.org": 77}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("remove: the lapsed member is removed exactly once",
deletes == [f"{m.LOOMIO_BASE}/api/b3/memberships/77"])
check("remove: the live active member is NOT removed",
f"{m.LOOMIO_BASE}/api/b3/memberships/10" not in deletes)
check("remove: the operator allowlist is NEVER removed (even though not active)",
f"{m.LOOMIO_BASE}/api/b3/memberships/2" not in deletes)
check("remove: no re-invite is sent while removing", posts == [])
check("remove: it does not send present members to any endpoint",
all("keep@x.org" not in (p["json"].get("emails") or []) for p in posts))
# --- 4. Second run after the removal changes nothing. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "new@x.org": 99, "old@x.org": 88} # lapsed gone
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("remove double-run: nothing removed again", deletes == [])
check("remove double-run: nothing invited", posts == [])
# --- 5. A re-run against a STALE roster (member already gone) must not error:
# Loomio answers 404 for an absent membership, which is success. ---
ROSTER = {"member@x.org": 10, "keep@x.org": 2, "old@x.org": 88, "lapsed@x.org": 77}
DELETE_STATUS = 404
posts.clear(); deletes.clear()
err = None
try:
await m.sync_loomio_memberships()
except Exception as e: # pragma: no cover
err = e
check("idempotent remove: a 404 (already absent) is treated as success", err is None)
check("idempotent remove: still no re-invite", posts == [])
DELETE_STATUS = 200
# --- 6. FAIL CLOSED: an unreadable roster stops BOTH phases. ---
ROSTER = {"lapsed@x.org": 77, "old@x.org": 88}
GET_FAILS = True
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("fail-closed: no invite when the roster is unreadable", posts == [])
check("fail-closed: no removal when the roster is unreadable", deletes == [])
GET_FAILS = False
# --- 7. The kill switch really pauses everything. ---
m.LOOMIO_SYNC_ENABLED = False
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("kill switch: no calls at all when LOOMIO_SYNC_ENABLED=0",
posts == [] and deletes == [])
m.LOOMIO_SYNC_ENABLED = True
# --- 8. Recording is idempotent — an existing timestamp is never overwritten. ---
first = m.get_loomio_invited_at("member@x.org")
m.mark_loomio_invited("member@x.org")
check("mark_loomio_invited never overwrites an existing timestamp",
m.get_loomio_invited_at("member@x.org") == first)
# --- 9. remove_loomio_membership status handling (200/204/404 ok, 500 not). ---
async with FakeClient() as c:
DELETE_STATUS = 204
check("remove_loomio_membership: 204 is success", await m.remove_loomio_membership(c, 1))
DELETE_STATUS = 500
check("remove_loomio_membership: 500 is a failure", not await m.remove_loomio_membership(c, 1))
DELETE_STATUS = 200
# --- 10. OPT-OUT: a member who deliberately left is never re-invited. ---
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_opt_out) VALUES (?, 1, 1)",
("left@x.org",))
conn.commit()
conn.close()
m.mark_loomio_invited("left@x.org")
async def active_with_left():
return ["member@x.org", "left@x.org"]
m.get_active_member_emails = active_with_left
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("opt-out: a member who left is not re-invited", posts == [])
check("opt-out: their stamp is left intact", m.get_loomio_invited_at("left@x.org") is not None)
# --- 11. RECONCILE CAP: many stamped-but-absent members mean a bad roster
# read, not a mass re-invite. Nothing is cleared. ---
many = [f"miss{n}@x.org" for n in range(1, m.LOOMIO_RECONCILE_MAX + 2)]
conn = m.get_db()
for e in many:
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (e,))
conn.commit()
conn.close()
for e in many:
m.mark_loomio_invited(e)
async def active_with_many():
return ["member@x.org"] + many
m.get_active_member_emails = active_with_many
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("cap: an over-cap stamp reconciliation sends no invites", posts == [])
check("cap: stamps are untouched when the cap is exceeded",
all(m.get_loomio_invited_at(e) is not None for e in many))
# --- 12. NOT ADDED: if Loomio accepts the payload but adds nothing for an
# address, it must stay unstamped and eligible. ---
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", ("lost@x.org",))
conn.commit()
conn.close()
async def active_with_lost():
return ["member@x.org", "lost@x.org"]
m.get_active_member_emails = active_with_lost
ADDED_OMIT = {"lost@x.org"}
ROSTER = {"member@x.org": 10, "keep@x.org": 2}
posts.clear(); deletes.clear()
await m.sync_loomio_memberships()
check("not-added: the address is sent", posts and posts[0]["json"]["emails"] == ["lost@x.org"])
check("not-added: an address Loomio did not add stays unstamped",
m.get_loomio_invited_at("lost@x.org") is None)
ADDED_OMIT = set()
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)
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
"""Regression test: Loomio handle collisions are resolved, not left mangled.
WHY THIS EXISTS
Loomio usernames are unique per INSTANCE, not per group. The rename pass
derives a target from the Cloudron username (the OAuth uid) or, before first
SSO login, from the email local part. Both can collide with a handle someone
else already holds:
* a plain Cloudron username — "matt" is held by another member;
* Open Collective aliases — every OC member's address starts
"opencollective@", so the local part resolves to "opencollective" and
collides with whichever OC member took it first.
A 422 "username has already been taken" must fall back to the member's portal
slug (name-based, e.g. "matt-h"), never leave the member on an autogenerated
handle.
Runnable: python3 tests/test_loomio_usernames.py (from the repo root)
"""
import os
import sys
import tempfile
import asyncio
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["LOOMIO_API_KEY"] = "test-user-key"
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
os.environ["LOOMIO_GROUP_ID"] = "1"
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"]
TAKEN = {"matt", "opencollective"}
class FakeResp:
def __init__(self, status=200, payload=None):
self.status_code = status
self._payload = payload or {}
self.text = str(payload or {})
def raise_for_status(self):
if self.status_code >= 400:
raise RuntimeError(f"HTTP {self.status_code}")
def json(self):
return self._payload
USERS = [
{"id": 300, "username": "matthiehnouk8f", "email": "matt@mattharwood.com",
"identities": [{"identity_type": "oauth", "uid": "matt"}]},
{"id": 313, "username": "opencollectivewbvgr", "email": "opencollective@jeremiahlee.com",
"identities": []},
{"id": 9, "username": "joshuaztanxk2", "email": "joshua.z.tan@example.org",
"identities": [{"identity_type": "oauth", "uid": "joshua.z.tan"}]},
{"id": 5, "username": "amarino", "email": "amarino@solo.ist",
"identities": [{"identity_type": "oauth", "uid": "amarino"}]},
]
class FakeClient:
def __init__(self, *a, **k):
self.patches = []
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, url, headers=None, params=None):
return FakeResp(200, {"users": USERS})
async def patch(self, url, headers=None, json=None):
uid = int(url.rsplit("/", 1)[-1])
name = (json or {}).get("username")
self.patches.append((uid, name))
if name in TAKEN:
return FakeResp(422, {"errors": {"username": ["has already been taken"]}})
return FakeResp(200, {"user": {"id": uid, "username": name}})
results = []
def check(name, ok):
results.append((name, ok))
async def main():
conn = m.get_db() # create + migrate
for email, slug in (
("matt@mattharwood.com", "matt-h"),
("opencollective@jeremiahlee.com", "jeremiah-lee"),
("joshua.z.tan@example.org", "joshua-z-tan"),
("amarino@solo.ist", "amarino"),
):
conn.execute("INSERT OR REPLACE INTO members (email, slug) VALUES (?, ?)", (email, slug))
conn.commit()
conn.close()
client = FakeClient()
out = await m.loomio_fix_usernames(client)
by_uid = {}
for uid, name in client.patches:
by_uid.setdefault(uid, []).append(name)
# Matt Harwood: Cloudron uid "matt" is taken -> portal slug "matt-h".
check("collision: the taken Cloudron username is tried first",
by_uid.get(300, [])[0] == "matt")
check("collision: falls back to the portal slug",
by_uid.get(300) == ["matt", "matt-h"])
# Jeremiah Lee: OC alias local part "opencollective" is taken -> slug.
check("collision: an OC alias local part is tried first",
by_uid.get(313, [])[0] == "opencollective")
check("collision: an OC alias collision falls back to the slug",
by_uid.get(313) == ["opencollective", "jeremiah-lee"])
# Joshua Tan: a dot-containing uid is sanitized, not passed through.
check("sanitize: a dotted uid becomes a legal handle",
by_uid.get(9) == ["joshua_z_tan"])
# A human-chosen handle is out of scope and never renamed.
check("skip: a hand-chosen handle is never renamed", 5 not in by_uid)
check("summary: three handled, one skipped",
out == {"fixed": 3, "skipped": 1})
# No patch ever sends an illegal character.
check("sanitize: every attempted handle is Loomio-legal",
all(n and n == m._loomio_safe_username(n) for _, names in by_uid.items() for n in names))
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)
+30
View File
@@ -0,0 +1,30 @@
import asyncio, os, sys, tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "aliases.db")
os.environ.setdefault("ADMIN_TOKEN", "admin-test")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
m.DB_PATH = os.environ["DB_PATH"]; m.ADMIN_TOKEN = "admin-test"
conn = m.get_db(); m._ensure_allowance_tables(conn)
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance, source) VALUES (?,?,?,?,?)",
("a@example.org", "main-slug", 1, 0.0, "oc"))
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
("hidden-abc", "", "A", 10.0, "oc:hidden-abc:ref1"))
conn.commit(); conn.close()
import httpx
async def add():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://p", timeout=60) as c:
r = await c.post("/admin/aliases", headers={"x-admin-token": "admin-test"},
json={"slug": "hidden-abc", "email": "a@example.org"})
return r.status_code, r.json()
st, d = asyncio.run(add())
assert st == 200, (st, d)
r1 = asyncio.run(m.settle_held_credits(send=False))
conn = m.get_db(); bal = conn.execute("SELECT credit_balance FROM members WHERE email='a@example.org'").fetchone()[0]; conn.close()
print(" alias add:", st, "| granted:", r1["granted"], "| balance:", bal)
assert bal == 10.0, "a purchase from the aliased hidden profile must credit the member"
assert len(r1["granted"]) == 1
r2 = asyncio.run(m.settle_held_credits(send=False))
assert len(r2["granted"]) == 0 and bal == 10.0
print("ALIAS TABLE OK: hidden-profile hold credits the member; no double-apply")
+171
View File
@@ -0,0 +1,171 @@
#!/usr/bin/env python3
"""Membership events — the durable record of who lapsed and who returned.
WHY THIS EXISTS
Before this table, a lapse was only members.active = 0: no date, no reason,
no source. A former member was indistinguishable from someone who had never
paid, and a returning payer silently erased the fact that they had lapsed.
Every deactivation/reactivation transition now writes one row, and the admin
overview carries the log plus the latest deactivation per member.
The tests pin:
1. deactivate_member logs ONE row on the active -> inactive transition;
a repeated call (OC re-delivery / second sweep pass) does not duplicate.
2. store_member logs `reactivated` when it flips an inactive member back on.
3. backfill gives a pre-existing inactive member one row with occurred_at
NULL and a reason derived from allowance_log; it runs once.
4. the overview helper returns the newest-first log and maps the latest
deactivation to the member's email (None date for a backfilled row).
Runnable: python3 tests/test_membership_events.py (from the repo root)
"""
import base64
import os
import sys
import tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "events-fixture.db")
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
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"]
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
def rows(q, args=()):
conn = m.get_db()
try:
return conn.execute(q, args).fetchall()
finally:
conn.close()
print("1. deactivation logs exactly one transition")
conn = m.get_db()
m._ensure_allowance_tables(conn)
conn.execute("DELETE FROM members")
conn.execute("DELETE FROM membership_events")
conn.execute("DELETE FROM portal_state")
conn.execute(
"INSERT INTO members (email, active, account_type) VALUES (?, 1, 'member')",
("lapse@example.org",),
)
conn.commit()
conn.close()
m.deactivate_member(
"lapse@example.org",
reason="Membership lapsed: no longer on the live Open Collective member list",
source="sweep",
)
ev = rows(
"SELECT email, event, reason, source, occurred_at, account_type "
"FROM membership_events WHERE email = ?",
("lapse@example.org",),
)
check(len(ev) == 1, "one deactivation row written")
check(ev[0][1] == "deactivated", "event is 'deactivated'")
check(ev[0][3] == "sweep", "source records the calling path")
check("Open Collective" in ev[0][2], "reason records why")
check(bool(ev[0][4]), "live transition carries occurred_at")
check(ev[0][5] == "member", "account_type is carried onto the event")
# A re-delivered webhook / second sweep pass must not append another lapse.
m.deactivate_member(
"lapse@example.org",
reason="duplicate delivery",
source="webhook-opencollective",
)
ev = rows(
"SELECT event FROM membership_events WHERE email = ?",
("lapse@example.org",),
)
check(len(ev) == 1, "a repeated deactivation writes no duplicate row")
print("2. a returning payer is logged as reactivated")
m.store_member("lapse@example.org", "sk-fixture", "uid-fixture")
ev = rows(
"SELECT event, source FROM membership_events WHERE email = ? ORDER BY id",
("lapse@example.org",),
)
check([r[0] for r in ev] == ["deactivated", "reactivated"],
"deactivated then reactivated, in order")
check(ev[-1][1] == "provision", "reactivation source is provisioning")
active = rows("SELECT active FROM members WHERE email = ?", ("lapse@example.org",))
check(active[0][0] == 1, "member is active again")
print("3. backfill gives a pre-existing inactive member a dated-unknown row")
conn = m.get_db()
conn.execute("DELETE FROM membership_events")
conn.execute("DELETE FROM portal_state")
conn.execute("DELETE FROM members")
conn.execute(
"INSERT INTO members (email, active, account_type, welcome_sent_at) "
"VALUES (?, 0, 'member', ?)",
("old@example.org", "2026-11-11 19:00:47"),
)
conn.execute(
"INSERT INTO allowance_log (email, cycle, decision, evidence, decided_at) "
"VALUES (?, ?, ?, ?, ?)",
("old@example.org", "2026-11-16", "in_grace",
"no recurring (monthly) contribution on Open Collective; reminder sent 2026-11-16 (grace 7d)",
"2026-11-18 11:02:37"),
)
conn.commit()
m._backfill_membership_events(conn)
conn.commit()
ev = conn.execute(
"SELECT event, reason, source, occurred_at, detail FROM membership_events "
"WHERE email = ?", ("old@example.org",),
).fetchall()
conn.close()
check(len(ev) == 1, "one backfilled row")
check(ev[0][0] == "deactivated" and ev[0][2] == "backfill",
"backfill event/source are explicit")
check(ev[0][3] is None, "backfilled occurred_at stays NULL (unknown date)")
check("in_grace" in ev[0][1] and "2026-11-18" in ev[0][1],
"backfill reason quotes the allowance decision and date")
check("exact" in ev[0][4].lower(), "detail says the exact date is unknown")
# Re-running the backfill must not duplicate the row (the marker gates it).
conn = m.get_db()
m._backfill_membership_events(conn)
conn.commit()
n = conn.execute(
"SELECT COUNT(*) FROM membership_events WHERE email = ?", ("old@example.org",),
).fetchone()[0]
conn.close()
check(n == 1, "backfill is idempotent")
print("4. the overview helper returns the log and the latest deactivation")
conn = m.get_db()
conn.execute(
"INSERT INTO membership_events (email, account_type, event, reason, source, occurred_at) "
"VALUES (?, 'member', 'reactivated', ?, 'provision', ?)",
("old@example.org", "Returned to active membership", "2026-11-24 12:00:00"),
)
conn.commit()
events, latest = m._membership_events_for_overview(conn)
conn.close()
check(len(events) == 2, "both events are in the log")
check(events[0]["event"] == "reactivated", "newest event sorts first")
check("old@example.org" in latest, "latest deactivation is keyed by email")
check(latest["old@example.org"]["at"] is None,
"backfilled latest deactivation reports an unknown date")
check(latest["old@example.org"]["source"] == "backfill",
"latest deactivation keeps its source")
print()
if FAILS:
print(f"FAILED: {len(FAILS)} check(s) red")
sys.exit(1)
print("all membership-event checks green")
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Regression test: the panel's membership state must not call a paying member "grace".
WHY THIS EXISTS
On 2026-11-13 mark@ofosos.org showed as in grace. He was current: the reminder
went out 2026-11-04 for the cycle that looked unpaid, his grace window elapsed
2026-11-11, and the reconciliation logged `renewed` for him at 19:02 that
afternoon — his next charge is 2026-11-26, which had not arrived and was not
supposed to.
The state function asked "is there a row in payment_reminders?" and stopped
there. That table is a HISTORY, kept so the sweep does not re-remind inside a
cycle; it is not a state. Two bugs followed: a reminder never expired (grace is
PAYMENT_GRACE_DAYS long), and a renewal never cleared it.
Ordering matters too: the same member had allowance_log id 2296 dated 2026-11-11
next to id 2286 dated 2026-11-13, so "latest by id" reads the WRONG decision.
"""
import os
import sys
import tempfile
import pathlib
from datetime import datetime, timedelta, timezone
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "state-fixture.db")
import app.main as m # noqa: E402
m.DB_PATH = os.environ["DB_PATH"]
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
NOW = datetime.now(timezone.utc)
def stamp(dt):
return dt.strftime("%Y-%m-%d %H:%M:%S")
conn = m.get_db()
m._ensure_allowance_tables(conn)
conn.execute("DELETE FROM payment_reminders")
conn.execute("DELETE FROM allowance_log")
EMAIL = "mark@ofosos.org"
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (EMAIL,))
print("1. a RENEWAL after a reminder means active — the actual bug")
conn.execute("INSERT INTO payment_reminders (email, cycle, sent_at) VALUES (?,?,?)",
(EMAIL, "2026-10-26", stamp(NOW - timedelta(days=9)))) # reminded 9d ago
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
(EMAIL, "2026-10-26", "in_grace", stamp(NOW - timedelta(days=9))))
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
(EMAIL, "2026-10-26", "renewed", stamp(NOW - timedelta(hours=2))))
conn.commit()
state, why = m.member_membership_state(EMAIL, True)
check(state == "active", f"paid member reads active, not grace (got {state!r}: {why})")
print("2. the LATEST decision wins, even when an older row has a higher id")
conn.execute("DELETE FROM allowance_log")
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
(EMAIL, "2026-10-26", "renewed", stamp(NOW - timedelta(hours=2)))) # id 1
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
(EMAIL, "2026-10-26", "in_grace", stamp(NOW - timedelta(days=9)))) # id 2, OLDER date
conn.commit()
state, why = m.member_membership_state(EMAIL, True)
check(state == "active",
f"an older-dated row inserted later does not override the renewal (got {state!r}: {why})")
print("3. a reminder INSIDE the grace window still reads in_grace")
conn.execute("DELETE FROM allowance_log")
conn.execute("UPDATE payment_reminders SET sent_at = ? WHERE email = ?",
(stamp(NOW - timedelta(days=2)), EMAIL))
conn.commit()
state, why = m.member_membership_state(EMAIL, True)
check(state == "in_grace", f"two days into a {int(m.PAYMENT_GRACE_DAYS)}-day grace reads in_grace (got {state!r})")
print("4. grace EXPIRES — no reminder row may mean grace forever")
conn.execute("UPDATE payment_reminders SET sent_at = ? WHERE email = ?",
(stamp(NOW - timedelta(days=int(m.PAYMENT_GRACE_DAYS) + 3)), EMAIL))
conn.commit()
state, why = m.member_membership_state(EMAIL, True)
check(state == "awaiting_contribution", f"past the window reads awaiting, not grace (got {state!r})")
check("elapsed" in why, f"and says the grace elapsed (got {why!r})")
print("5. a previewed deactivation is not grace either")
conn.execute("INSERT INTO allowance_log (email, cycle, decision, decided_at) VALUES (?,?,?,?)",
(EMAIL, "2026-10-26", "would_deactivate", stamp(NOW - timedelta(hours=1))))
conn.commit()
state, why = m.member_membership_state(EMAIL, True)
check(state == "awaiting_contribution", f"would_deactivate reads awaiting (got {state!r})")
print("6. nobody flagged is simply active")
conn.execute("DELETE FROM payment_reminders")
conn.execute("DELETE FROM allowance_log")
conn.commit()
state, why = m.member_membership_state(EMAIL, True)
check(state == "active" and why == "", f"clean member reads active with no reason (got {state!r}, {why!r})")
print("7. inactive is still inactive")
check(m.member_membership_state(EMAIL, False)[0] == "inactive", "active=0 reads inactive")
print("8. an unreadable database fails SAFE, not into a grace badge")
real = m.get_db
try:
def boom():
raise RuntimeError("db locked")
m.get_db = boom
state, why = m.member_membership_state(EMAIL, True)
check(state == "active", f"a failed read does not invent a payment problem (got {state!r})")
finally:
m.get_db = real
conn.close()
print()
if FAILS:
print(f"membership state: {len(FAILS)} FAILURE(S)")
sys.exit(1)
print("membership state: OK — renewals clear grace, grace expires, reads fail safe")
+27
View File
@@ -0,0 +1,27 @@
import asyncio, os, sys, tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "status.db")
os.environ.setdefault("BROKER_SECRET", "test-secret")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
m.DB_PATH = os.environ["DB_PATH"]
m.BROKER_SECRET = "test-secret"
conn = m.get_db()
m._ensure_allowance_tables(conn)
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance, balance, source) VALUES (?,?,?,?,?,?)",
("lapsed@example.org", "lapsed", 0, 3.0, 0.0, "oc"))
conn.execute("INSERT INTO allowance_log (email, cycle, decision, evidence, anchor_day) VALUES (?,?,?,?,?)",
("lapsed@example.org", "2026-11-05", "awaiting_contribution", "no live recurring contribution in this cycle", 5))
conn.commit(); conn.close()
import httpx
async def run():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://p", timeout=60) as c:
r = await c.get("/broker/membership-status", headers={"x-broker-secret": "test-secret", "x-member-email": "lapsed@example.org"})
return r.status_code, r.json()
st, d = asyncio.run(run())
print(" route:", st, "| active:", d.get("active"), "| state:", d.get("state"), "| min:", d.get("minimum_contribution"), "| decision:", (d.get("last_decision") or {}).get("decision"))
assert st == 200 and d["active"] is False and d["minimum_contribution"] == 5.0
assert (d.get("last_decision") or {}).get("decision") == "awaiting_contribution"
assert d.get("contribute_url")
print("MEMBERSHIP STATUS ROUTE OK: answers for a lapsed member, states minimum and last decision")
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""Regression tests for the metrics day-completion fix (Nov 2026 under-count).
Bug: snapshot() wrote only TODAY's row at 03:15 UTC — the first ~3 hours of
that day's traffic — and never revisited it, so every metrics_daily row was
frozen at its first hours (Nov 6 read $1.20/93 requests vs a true $34.26/4508).
Fix: each run completes YESTERDAY's row with its full-day usage/impact
aggregates (usage columns ONLY — membership columns are point-in-time
measurements that must survive), then records today live as before.
backfill() gains --since: a targeted usage-only repair that leaves the
published membership curve untouched.
Runnable:
* from the repo root: python3 tests/test_metrics_completion.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 tests/test_metrics_completion.py
"""
import datetime as dt
import os
import sqlite3
import sys
import tempfile
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="metrics-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE metrics_snapshot is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"),
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "metrics_snapshot.py")):
sys.path.insert(0, _cand)
break
import metrics_snapshot as ms # noqa: E402
TODAY = ms.today()
YESTERDAY = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=1)).isoformat()
DAY_BEFORE = (dt.date.fromisoformat(TODAY) - dt.timedelta(days=2)).isoformat()
FAILED = []
def check(name, cond, detail=""):
if cond:
print(f" ok {name}")
else:
print(f" FAIL {name} {detail}")
FAILED.append(name)
def stub_sources(spend, op_spend, tokens, joins=(), active=40, total=71,
subs=71, matrix=65, balance=123.45):
"""Replace every network source with fixed in-memory data."""
ms.from_sqlite = lambda: {"active": active, "total": total, "joins": list(joins)}
ms.from_listmonk = lambda: subs
ms.listmonk_joins = lambda: list(joins)
ms.from_matrix = lambda: matrix
ms.oc_collective_balance = lambda: balance
ms.spend_by_day = lambda since=None: dict(spend)
ms.operator_spend_by_day = lambda since=None: None if op_spend is None else dict(op_spend)
ms.tokens_by_day_model = lambda since=None: {k: dict(v) for k, v in tokens.items()}
def read_row(day):
conn = sqlite3.connect(_TEST_DB)
try:
conn.row_factory = sqlite3.Row
return conn.execute("SELECT * FROM metrics_daily WHERE day = ?", (day,)).fetchone()
finally:
conn.close()
def seed(day, **cols):
"""Insert a row with arbitrary columns (the nightly snapshot's shape)."""
ms.upsert(day, {"spend_usd": None, "requests": None, "out_tokens": None,
"energy_wh": None, "co2e_g": None, "tokens_measured": None,
"tokens_estimated": None, "factor_revision": None, **cols})
# ----------------------------------------------------------------------
print("1. snapshot() completes YESTERDAY with full-day usage, records today live")
stub_sources(
spend={YESTERDAY: (29.0604, 3384), TODAY: (2.19, 691)},
op_spend={YESTERDAY: 1.1613, TODAY: 0.5},
tokens={YESTERDAY: {"greenpt/glm-5.3-flash": 500000},
TODAY: {"greenpt/glm-5.3-flash": 100000}},
joins=["2026-11-01"],
)
row = ms.snapshot()
y = read_row(YESTERDAY)
t = read_row(TODAY)
check("yesterday spend_usd = full-day total", y["spend_usd"] == 29.0604, y["spend_usd"])
check("yesterday requests = full-day count", y["requests"] == 3384, y["requests"])
check("yesterday operator_spend carried", y["operator_spend_usd"] == 1.1613, y["operator_spend_usd"])
check("yesterday out_tokens from full day", y["out_tokens"] == 500000, y["out_tokens"])
check("yesterday energy computed from tokens", y["energy_wh"] is not None and y["energy_wh"] > 0)
check("yesterday co2e_g computed (>0, unit tripwire band)", y["co2e_g"] is not None and y["co2e_g"] > 0)
check("today's row keeps the live partial", t["spend_usd"] == 2.19 and t["requests"] == 691)
check("today's row carries live membership", t["members_total"] == 71 and t["members_active"] == 40)
check("today's row carries oc_balance", t["oc_balance_usd"] == 123.45)
check("yesterday's membership columns are NULL (not measured, never 0)",
y["members_active"] is None and y["members_total"] is None and y["newsletter_subs"] is None)
print("2. completion overwrites a stale partial WITHOUT touching membership columns")
conn = sqlite3.connect(_TEST_DB)
conn.execute("DELETE FROM metrics_daily")
conn.commit()
conn.close()
# What the OLD nightly code left behind: partial usage + that morning's counts.
seed(YESTERDAY, spend_usd=2.192, requests=691, members_active=39, members_total=70,
newsletter_subs=70, matrix_space_members=64)
stub_sources(
spend={YESTERDAY: (29.0604, 3384), TODAY: (0.5, 100)},
op_spend={YESTERDAY: 1.1613, TODAY: None},
tokens={YESTERDAY: {"greenpt/glm-5.3-flash": 500000}},
)
ms.snapshot()
y = read_row(YESTERDAY)
check("stale partial spend replaced with full-day value", y["spend_usd"] == 29.0604, y["spend_usd"])
check("stale partial requests replaced", y["requests"] == 3384, y["requests"])
check("members_active preserved from that morning", y["members_active"] == 39, y["members_active"])
check("members_total preserved", y["members_total"] == 70, y["members_total"])
check("newsletter_subs preserved", y["newsletter_subs"] == 70)
check("matrix_space_members preserved", y["matrix_space_members"] == 64)
print("3. upsert_usage on a missing row INSERTs usage + NULL membership (fail-closed)")
conn = sqlite3.connect(_TEST_DB)
conn.execute("DELETE FROM metrics_daily")
conn.commit()
conn.close()
ms.upsert_usage(DAY_BEFORE, {"spend_usd": 5.0, "requests": 42, "out_tokens": None,
"energy_wh": None, "co2e_g": None, "tokens_measured": None,
"tokens_estimated": None, "factor_revision": None,
"operator_spend_usd": None})
y = read_row(DAY_BEFORE)
check("usage columns written", y["spend_usd"] == 5.0 and y["requests"] == 42)
check("membership columns NULL, never zero",
y["members_active"] is None and y["members_total"] is None and y["members_new"] is None)
print("4. backfill(since=...) repairs usage only — membership curve untouched")
conn = sqlite3.connect(_TEST_DB)
conn.execute("DELETE FROM metrics_daily")
conn.commit()
conn.close()
# Three days as the nightly snapshots wrote them: membership present, usage partial.
for d, sp, rq in ((DAY_BEFORE, 1.0, 50), (YESTERDAY, 2.0, 60)):
seed(d, spend_usd=sp, requests=rq, members_active=39, members_total=70,
members_new=3, newsletter_subs=70, matrix_space_members=64)
seed(TODAY, spend_usd=0.5, requests=10, members_active=40, members_total=71)
stub_sources(
spend={DAY_BEFORE: (17.8791, 4493), YESTERDAY: (29.0604, 3384), TODAY: (0.5, 10)},
op_spend={DAY_BEFORE: 0.2, YESTERDAY: 1.1613, TODAY: None},
tokens={DAY_BEFORE: {"greenpt/deepseek-v4.1-flash": 200000},
YESTERDAY: {"greenpt/glm-5.3-flash": 500000}},
joins=["2026-11-01"],
)
ms.backfill(since=YESTERDAY)
y = read_row(YESTERDAY)
db = read_row(DAY_BEFORE)
t = read_row(TODAY)
check("repaired day matches ground truth spend", y["spend_usd"] == 29.0604, y["spend_usd"])
check("repaired day matches ground truth requests", y["requests"] == 3384, y["requests"])
check("repaired day keeps its membership columns",
y["members_active"] == 39 and y["members_total"] == 70 and y["members_new"] == 3)
check("day BEFORE --since untouched", db["spend_usd"] == 1.0 and db["requests"] == 50)
check("today still gets the full live update", t["members_total"] == 71)
print("5. full backfill (no --since) rebuilds membership columns as before")
conn = sqlite3.connect(_TEST_DB)
conn.execute("DELETE FROM metrics_daily")
conn.commit()
conn.close()
ms.backfill()
y = read_row(YESTERDAY)
check("full backfill writes joins-derived members_total",
y["members_total"] == 1, y["members_total"]) # one join on 2026-11-01
check("full backfill still writes full-day usage", y["spend_usd"] == 29.0604)
print("6. provenance: a day with tokens but no measured factor reports estimated, not measured")
ms.upsert_usage(DAY_BEFORE, {"spend_usd": 1.0, "requests": 5, "out_tokens": 1000,
"energy_wh": 0.5, "co2e_g": 0.125,
"tokens_measured": 0, "tokens_estimated": 1000,
"factor_revision": "x"})
y = read_row(DAY_BEFORE)
check("split persisted", y["tokens_measured"] == 0 and y["tokens_estimated"] == 1000)
print()
if FAILED:
print(f"FAILED: {len(FAILED)} check(s): {FAILED}")
sys.exit(1)
print("ALL CHECKS PASSED")
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Regression test: 'oc-incognito' — an OC payer whose OC profile hides its email.
WHY THIS EXISTS
mmoya@mmoya.org sat in MANUAL_MEMBERS because OC hides the address on their
profile (incognito-5ad60182, email null since 2023), so email matching can never
find them. But "manual" means hand-provisioned, and the sweep SKIPS manual
members entirely — so a paying subscriber had no lapse logic, no dues tracking
and no order attribution. Two different facts were sharing one word.
An oc-incognito member needs no exemption from reconciliation: the partition
already matches OC orders by the PAYER'S SLUG, and members.slug holds exactly
that slug for these people. What they need is to stop being skipped.
The invariants pinned here:
* an explicit source beats MANUAL_MEMBERS membership — that is the whole
point; mmoya must not read as manual just because their address is listed;
* only 'manual' is exempt (lapse guard, reconciliation skip, shortfall
credits). 'oc-incognito' is a payer and gets payer treatment;
* an unreadable or unexpected source falls back to 'oc' — the direction that
keeps reconciling someone rather than quietly exempting them;
* the source column is optional (every existing row is NULL, meaning
"not stated"), so this ships without a data migration.
"""
import os
import pathlib
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "source-fixture.db")
import app.main as m # noqa: E402
m.DB_PATH = os.environ["DB_PATH"]
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
MMOYA = "mmoya@mmoya.org"
OTHER = "someone@example.org"
conn = m.get_db()
# The column arrives with get_db()'s own migration — asserted, not created here,
# because "the migration ran" is part of what this test is for.
check_cols = {r[1] for r in conn.execute("PRAGMA table_info(members)")}
assert "source" in check_cols, "get_db() must migrate in members.source"
conn.execute("INSERT OR REPLACE INTO members (email, slug, active) VALUES (?,?,1)",
(MMOYA, "incognito-5ad60182"))
conn.execute("INSERT OR REPLACE INTO members (email, slug, active) VALUES (?,?,1)",
(OTHER, "guest-abc123"))
conn.commit()
conn.close()
m.MANUAL_MEMBERS = {MMOYA, "founder@example.org"}
print("1. the fallback: a listed address with no source of its own is manual")
check(m.member_source(MMOYA) == "manual",
"an address in MANUAL_MEMBERS and nothing else reads manual (before the flip)")
check(m.is_manual_member(MMOYA) is True, "…and is exempt as such")
print("2. an explicit source BEATS the manual list — this is the mmoya case")
check(m.set_member_source(MMOYA, "oc-incognito") is True, "the source is written")
check(m.member_source(MMOYA) == "oc-incognito",
f"mmoya reads oc-incognito even while listed in MANUAL_MEMBERS (got {m.member_source(MMOYA)!r})")
check(m.is_manual_member(MMOYA) is False,
"and is therefore NOT exempt: a paying member gets payer treatment")
print("3. everyone else is unchanged")
check(m.member_source(OTHER) == "oc", "an unlisted member is oc (the default)")
check(m.member_source("founder@example.org") == "manual", "an unlisted-in-DB manual address stays manual")
check(m.member_source("nobody@nowhere.test") == "oc", "an address with no row at all is oc, not manual")
print("4. a bad source value never silently exempts anyone")
conn = m.get_db()
conn.execute("UPDATE members SET source = 'banana' WHERE lower(email) = ?", (OTHER,))
conn.commit(); conn.close()
check(m.member_source(OTHER) == "oc",
f"an unrecognised source falls back to oc — the direction that keeps reconciling (got {m.member_source(OTHER)!r})")
try:
m.set_member_source(OTHER, "banana")
check(False, "set_member_source must reject an unknown source")
except ValueError:
check(True, "set_member_source rejects an unknown source")
print("5. the three decisions that used to key on MANUAL_MEMBERS now key on the source")
src = (ROOT / "app" / "main.py").read_text()
recon = src[src.index("async def reconcile_allowances"):]
recon = recon[:recon.index("def ", recon.index("for row in rows"))]
check('member_source(email, conn) == "manual"' in recon,
"the reconciliation skips only source == manual")
check('member_source(email, conn) == "oc-incognito"' in recon and "oc_slug = slug" in recon,
"an oc-incognito member takes the OC slug from their own row — the index cannot give it "
"(it drops anyone without an email), and without a slug the reconciler skips them as "
"'cannot verify payment'")
check("in MANUAL_MEMBERS" not in recon,
"and no longer keys on the raw list (an oc-incognito member must not be skipped)")
check("not is_manual_member(email)" in src,
"the sweep's deactivation guard uses the source too")
check("is_manual_member(email) or m.get(\"org_slug\")" in src,
"shortfall credits exempt manual + org-backed, nothing else")
check('"source": member_source(email)' in src,
"the panel payload carries the source (so it can stop saying 'manual')")
print("6. the column is optional — existing rows carry NULL and still work")
conn = m.get_db()
conn.execute("UPDATE members SET source = NULL WHERE lower(email) = ?", (MMOYA,))
conn.commit(); conn.close()
m.MANUAL_MEMBERS = {"founder@example.org"} # the address leaves the list
check(m.member_source(MMOYA) == "oc",
"once mmoya leaves MANUAL_MEMBERS with no source set, they read oc — which is why the "
"source is set BEFORE the address is removed from the env")
print()
if FAILS:
print(f"oc-incognito: {len(FAILS)} FAILURE(S)")
sys.exit(1)
print("oc-incognito: OK — an explicit source wins, only manual is exempt, bad values fail safe")
+170
View File
@@ -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)
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Regression tests for org-backed anchor days.
Runnable:
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_org_anchors.py
* from the repo root, on a host that has the app's dependencies
WHY THIS EXISTS
The allowance reconcile SKIPS rows with `org_slug` (dues are paid by an OC
Organization, not an individual order), so org-backed members never got an
`anchor_day` — and close_credit_cycles skipped them forever, restoring their
credit packs every month. The fix infers the anchor from the ORGANIZATION's
OC membership createdAt. Covered:
- anchor = org join day, clamped to 28
- the team reset is pinned to the next occurrence
- idempotent: a second pass touches nothing
- an org with no OC membership record is reported, never guessed
"""
import asyncio
import os
import sys
import tempfile
from datetime import datetime, timezone
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="organchor-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
import app.main as m # noqa: E402
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
pins = []
async def fake_org_joins():
return {
"cosmos": datetime(2026, 10, 15, 23, 52, tzinfo=timezone.utc),
"late": datetime(2026, 1, 31, 12, 0, tzinfo=timezone.utc),
}
async def fake_team_id(email):
return f"team:{email}"
async def fake_pin(team_id, reset_at):
pins.append((team_id, reset_at.isoformat()))
m.fetch_org_join_days = fake_org_joins
m.litellm_team_id_for_email = fake_team_id
m.litellm_pin_reset_date = fake_pin
conn = m.get_db()
m._ensure_allowance_tables(conn) # creates allowance_log and adds anchor_day
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
"VALUES ('tech@cosmos.coop', '', 1, 'member', 'cosmos')")
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
"VALUES ('ops@late.org', '', 1, 'member', 'late')")
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, org_slug) "
"VALUES ('x@unknown.org', '', 1, 'member', 'unknown-org')")
conn.execute(
"INSERT INTO members (email, key_token, active, account_type, org_slug, anchor_day) "
"VALUES ('already@set.org', '', 1, 'member', 'cosmos', 7)")
conn.commit()
conn.close()
first = asyncio.run(m.reconcile_org_anchors())
anchors = {r["email"]: r["anchor_day"] for r in first["anchored"]}
check("org join day 15 -> anchor 15", anchors.get("tech@cosmos.coop"), 15)
check("org join day 31 -> clamped to 28", anchors.get("ops@late.org"), 28)
check("an org with no OC record is reported, not guessed",
[u["email"] for u in first["unresolved"]], ["x@unknown.org"])
check("an already-anchored row is untouched", "already@set.org" not in anchors, True)
reset = dict((t, r) for t, r in pins)
check("reset pinned to the next occurrence of the anchor day (Dec 15)",
reset.get("team:tech@cosmos.coop", "")[:10], "2026-12-15")
second = asyncio.run(m.reconcile_org_anchors())
check("second pass leaves only the unresolved org to report", second["checked"], 1)
check("second pass writes no anchors", second["anchored"], [])
check("the unresolved org is reported again, not silently dropped",
[u["email"] for u in second["unresolved"]], ["x@unknown.org"])
row = m.get_db().execute(
"SELECT anchor_day FROM members WHERE email = 'tech@cosmos.coop'").fetchone()
check("anchor persisted", row[0], 15)
print()
if failures:
print(f"{failures} FAILURE(S)")
sys.exit(1)
print("all checks passed")
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Regression tests for app.main._payment_verdict (allowance payment assessment).
Self-contained and runnable:
* from the repo root: python3 tests/test_payment_verdict.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_payment_verdict.py
(the container has the app's own dependencies; the host usually does not)
Covers the FREQUENCY-AWARE decision:
- ACTIVE YEARLY whose coverage window includes the cycle -> paid (renew)
[the regression this file exists for]
- ACTIVE YEARLY whose year has lapsed -> not paid
- ACTIVE MONTHLY -> paid
- PROCESSING -> paid (paid-pending; never a reminder)
- ONETIME-only -> not paid (credit, not an allowance cycle)
- an ONETIME payment does NOT mask an unpaid monthly member
- ERROR MONTHLY with the last charge before the cycle -> not paid (mark-meyer's
exact order, asserted to keep his current, correct outcome)
- CANCELLED MONTHLY with an old charge -> not paid
Does NOT cover (deliberate): the OC network fetch, the members table / anchor-day
storage, email sending, the report/send modes, or deactivation. It tests the pure
decision function only. The yearly case is SYNTHETIC: the collective has no yearly
orders today, so this guards the branch without implying any member has one.
"""
import os
import sys
from datetime import datetime, timezone
# Locate the app package: explicit env, the deployed path, or the repo root.
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import _payment_verdict # noqa: E402
NOW = datetime(2026, 11, 4, 12, 0, tzinfo=timezone.utc)
CYCLE = datetime(2026, 10, 26, 0, 0, tzinfo=timezone.utc) # mark-meyer join-day 26
def order(freq, status, last=None, next_=None):
return {"frequency": freq, "status": status,
"lastChargedAt": last, "nextChargeDate": next_}
# (name, orders, expected_paid, evidence_must_contain)
CASES = [
("active yearly covers this cycle (last charge 2026-09-26, next 2027-09-01)",
[order("YEARLY", "ACTIVE", "2026-09-26T18:00:00.000Z", "2027-09-01T00:00:00.000Z")],
True, "yearly"),
("active yearly whose year has lapsed",
[order("YEARLY", "ACTIVE", "2024-01-01T00:00:00.000Z", "2025-01-01T00:00:00.000Z")],
False, "before this cycle"),
("active monthly",
[order("MONTHLY", "ACTIVE", "2026-11-02T18:00:00.000Z", "2026-12-01T00:00:00.000Z")],
True, "live recurring contribution"),
("processing monthly is paid-pending",
[order("MONTHLY", "PROCESSING", "2026-09-16T19:03:08.000Z", "2026-11-01T00:00:00.000Z")],
True, "live recurring contribution"),
("onetime-only is not an allowance cycle",
[order("ONETIME", "PAID", "2026-11-01T00:00:00.000Z", None)],
False, "no recurring"),
("onetime does not mask an unpaid monthly",
[order("ONETIME", "PAID", "2026-11-02T00:00:00.000Z", None),
order("MONTHLY", "ERROR", "2026-09-26T18:05:00.000Z", "2026-11-06T00:00:00.000Z")],
False, "before this cycle"),
("mark-meyer's exact order: monthly ERROR, last charge 2026-09-26",
[order("MONTHLY", "ERROR", "2026-09-26T18:05:00.000Z", "2026-11-06T00:00:00.000Z")],
False, "last charge 2026-09-26 is before this cycle"),
("cancelled monthly with old charge",
[order("MONTHLY", "CANCELLED", "2026-08-01T11:05:08.000Z", None)],
False, "before this cycle"),
("monthly charged within the cycle (7-day slack)",
[order("MONTHLY", "ERROR", "2026-10-28T00:00:00.000Z", None)],
True, "within the current cycle"),
("no orders at all",
[],
False, "no recurring"),
]
failures = 0
for name, orders, expect_paid, expect_text in CASES:
paid, evidence = _payment_verdict(orders, CYCLE, now=NOW)
ok = (paid == expect_paid) and (expect_text in evidence)
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}\n"
f" paid={paid} (expected {expect_paid}) evidence={evidence!r}")
print(f"\n{len(CASES) - failures}/{len(CASES)} passed")
sys.exit(1 if failures else 0)
+265
View File
@@ -0,0 +1,265 @@
#!/usr/bin/env python3
"""Regression tests for M5 (atomic held-credit grant) + M6 (Cloudron user
pagination) — audit 2026-11-05.
Runnable:
* from the repo root: python3 tests/test_portal_hardening.py
* inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_portal_hardening.py
Covered:
M5 — grant_held_credits
- matched holds (by email AND by slug) flip + credit in one transaction
- a re-run moves no money (held:<id> reference exists-check)
- a hold whose ledger row already exists is reconciled, never re-credited
M6 — cloudron_fetch_all_users (async) / _sync
- pages past the first: >100 users returned in full (the old code silently
truncated at 100)
- page-1 failure -> None / raise (callers keep failing loudly)
- later-page failure -> keep what was read
- the hard page cap holds even if the API never runs short
"""
import asyncio
import os
import sqlite3
import sys
import tempfile
_TEST_DB = os.path.join(tempfile.mkdtemp(prefix="hardening-test-"), "members.db")
os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported
for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code",
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))):
if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")):
sys.path.insert(0, _cand)
break
from app.main import ( # noqa: E402
cloudron_fetch_all_users, cloudron_fetch_all_users_sync, get_credit_balance,
get_db, grant_held_credits,
)
failures = 0
def check(name, got, want):
global failures
ok = got == want
if not ok:
failures += 1
print(f"[{'PASS' if ok else 'FAIL'}] {name}")
if not ok:
print(f" got {got!r}\n want {want!r}")
# ---------------------------------------------------------------- M5 ---------
conn = get_db()
conn.execute("INSERT INTO members (email, key_token, slug, active) "
"VALUES ('newmember@example.com', '', 'newmember', 1)")
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('newmember', 'someone-else@example.com', 'W', 10.0, 'oc:newmember:or_1', 'held')")
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference, status) "
"VALUES ('newmember', NULL, 'X', 5.0, 'oc:other:or_2', 'held')")
conn.commit()
# Mixed-case email on purpose: the grant must normalize it (the balance
# UPDATE/SELECT join on the member row and silently miss otherwise).
granted = grant_held_credits(conn, "NewMember@Example.com", "newmember")
check("matched holds sum (including the non-member slug hold)", granted, 15.0)
check("balance credited", get_credit_balance("newmember@example.com"), 15.0)
statuses = dict(conn.execute("SELECT id, status FROM held_credits").fetchall())
check("both holds flipped in the same pass", set(statuses.values()), {"granted"})
refs = [r[0] for r in conn.execute("SELECT reference FROM credit_ledger ORDER BY id").fetchall()]
check("one ledger row per hold, held:<id> shape", refs, ["held:1", "held:2"])
granted2 = grant_held_credits(conn, "newmember@example.com", "newmember")
check("re-run grants nothing (reference exists-check)", granted2, 0.0)
refs = [r[0] for r in conn.execute("SELECT reference FROM credit_ledger ORDER BY id").fetchall()]
check("re-run wrote no extra ledger rows", refs, ["held:1", "held:2"])
check("re-run left the balance alone", get_credit_balance("newmember@example.com"), 15.0)
# Crash-recovery shape: a hold flipped but its ledger row lost… inverse — a
# ledger row that exists while the hold reads 'held' (a crash between the two
# commits of the OLD code) must reconcile the status and move no money.
conn.execute("UPDATE held_credits SET status='held', resolved_at=NULL WHERE id = 2")
conn.commit()
granted3 = grant_held_credits(conn, "newmember@example.com", "newmember")
check("already-credited hold reconciles without re-crediting", granted3, 0.0)
check("its status is reconciled to granted",
dict(conn.execute("SELECT id, status FROM held_credits").fetchall()), {1: "granted", 2: "granted"})
check("balance still 15 after the reconciliation pass",
get_credit_balance("newmember@example.com"), 15.0)
_conn2 = get_db() # separate handle to prove committed state, not in-transaction state
n = _conn2.execute("SELECT COUNT(*) FROM credit_ledger").fetchone()[0]
check("committed state equals in-call state", n, 2)
_conn2.close()
conn.close()
# ---------------------------------------------------------------- M6 ---------
class FakeResponse:
def __init__(self, status_code, payload):
self.status_code = status_code
self._payload = payload
def json(self):
return self._payload
class FakeAsyncClient:
def __init__(self, pages):
self.pages = list(pages) # one entry per expected page
self.calls = []
async def get(self, url, params=None, headers=None):
self.calls.append(dict(params or {}))
if not self.pages:
return FakeResponse(200, {"users": []})
item = self.pages.pop(0)
if isinstance(item, int):
return FakeResponse(item, {})
return FakeResponse(200, {"users": item})
users_120 = [{"id": f"u{i}", "email": f"m{i}@example.com"} for i in range(120)]
page1, page2 = users_120[:100], users_120[100:]
fc = FakeAsyncClient([page1, page2])
got = asyncio.run(cloudron_fetch_all_users(fc))
check("110+ users: walked past the first page", len(got), 120)
check("per_page=100 on every page", {c.get("per_page") for c in fc.calls}, {100})
check("pages requested in order", [c.get("page") for c in fc.calls], [1, 2])
fc = FakeAsyncClient([500])
check("page-1 failure -> None (caller fails loudly)",
asyncio.run(cloudron_fetch_all_users(fc)), None)
fc = FakeAsyncClient([page1, 500, page2])
got = asyncio.run(cloudron_fetch_all_users(fc))
check("later-page failure keeps what was read", len(got), 100)
class EndlessFullPagesClient:
"""A fake API that never runs short — the hard cap must stop the walk."""
def __init__(self):
self.calls = 0
async def get(self, url, params=None, headers=None):
self.calls += 1
return FakeResponse(200, {"users": users_120[:100]})
fc = EndlessFullPagesClient()
got = asyncio.run(cloudron_fetch_all_users(fc))
check("hard cap: stops at 50 pages (5000 users)", (len(got), fc.calls), (5000, 50))
# --- sync walker (monkeypatch urllib at the call site's own module) ---------
import urllib.request
_real_urlopen = urllib.request.urlopen
_seen = {"n": 0}
def fake_urlopen(req, timeout=None):
_seen["n"] += 1
if _seen["n"] == 1:
raise RuntimeError("page 1 simulated failure")
class R:
def __enter__(self):
return self
def __exit__(self, *a):
return False
def read(self):
return b'{"users": []}'
return R()
urllib.request.urlopen = fake_urlopen
try:
try:
cloudron_fetch_all_users_sync()
check("sync walker: page-1 failure raises", False, True)
except RuntimeError:
check("sync walker: page-1 failure raises", True, True)
finally:
urllib.request.urlopen = _real_urlopen
_real_urlopen = urllib.request.urlopen
_state = {"pages": [users_120[:100], users_120[100:]], "urls": []}
def fake_urlopen2(req, timeout=None):
_state["urls"].append(req.full_url)
page = _state["pages"].pop(0) if _state["pages"] else []
import io
body = ('{"users": %s}' % __import__("json").dumps(page)).encode()
return io.BytesIO(body)
urllib.request.urlopen = fake_urlopen2
try:
got = cloudron_fetch_all_users_sync()
check("sync walker pages past the first page too", len(got), 120)
check("sync walker issued a page=2 request",
any("page=2" in u for u in _state["urls"]), True)
finally:
urllib.request.urlopen = _real_urlopen
# ------------------------------------------------------- M1: log redaction ---
# The webhook token and member emails must not survive into portal logs. The
# guard must FIRE: feed a record with both a token and an email and read back
# the formatted line.
import logging # noqa: E402
from app.main import _EMAIL_RE, _RedactWebhookPath # noqa: E402
flt = _RedactWebhookPath()
rec = logging.LogRecord("t", logging.INFO, "p", 1,
"Credit pack: +%s for %s (balance %s)", (20.0, "member@example.org", 30.0), None)
flt.filter(rec)
check("email in %-args redacted", rec.getMessage(), "Credit pack: +20.0 for <email> (balance 30.0)")
check("argument tuple preserved", isinstance(rec.args, tuple), True)
rec = logging.LogRecord("t", logging.INFO, "p", 1,
"Provisioned member hidden@example.org ok", (), None)
flt.filter(rec)
check("email embedded via f-string (msg) redacted", rec.getMessage(), "Provisioned member <email> ok")
rec = logging.LogRecord("t", logging.INFO, "p", 1, "Loomio invites: %s",
(["a@example.org", "b@example.org"],), None)
flt.filter(rec)
check("list args redacted, list type kept",
(rec.getMessage(), type(rec.args[0]).__name__), ("Loomio invites: ['<email>', '<email>']", "list"))
rec = logging.LogRecord("t", logging.INFO, "p", 1,
'POST /webhook/opencollective/sekret123?x=1 HTTP/1.1', (), None)
filt_result = flt.filter(rec)
check("webhook token redacted, filter returns True",
(rec.getMessage(), filt_result), ("POST /webhook/opencollective/<redacted>?x=1 HTTP/1.1", True))
rec = logging.LogRecord("t", logging.INFO, "p", 1,
"Credit pack for member@example.org via /webhook/opencollective/tok9", (), None)
flt.filter(rec)
check("token and email redacted in one line",
"<email>" in rec.getMessage() and "<redacted>" in rec.getMessage()
and "member@example.org" not in rec.getMessage() and "tok9" not in rec.getMessage(), True)
rec = logging.LogRecord("t", logging.INFO, "p", 1, "Matrix invite for @someuser:inference.coop", (), None)
flt.filter(rec)
check("MXIDs are not emails and stay readable",
rec.getMessage(), "Matrix invite for @someuser:inference.coop")
rec = logging.LogRecord("t", logging.INFO, "p", 1, "counter=%d", (7,), None)
flt.filter(rec)
check("non-string args untouched", rec.getMessage(), "counter=7")
rec = logging.LogRecord("t", logging.INFO, "p", 1, "boom", (), None)
rec.exc_text = "ValueError: No member account for lost@example.org"
flt.filter(rec)
check("already-formatted exception text redacted",
rec.exc_text, "ValueError: No member account for <email>")
check("regex matches a real-shaped address",
bool(_EMAIL_RE.search("contact info@a.b-stuff.coop today")), True)
print(f"\n{'FAILED' if failures else 'OK'} — {failures} failure(s)")
sys.exit(1 if failures else 0)
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Regression test: a first-time contributor's order must not be dropped in silence.
WHY THIS EXISTS
On 2026-11-13 21:59:43 OC delivered `order.processed` for a live $5/month
membership (Conor W, conor.canaday@gmail.com, order or_eU8gRkrPCvFsaYHrgiCfz).
The portal answered 200 and did nothing: the membership branch resolves the
payer with
members = await fetch_members()
member = next((m for m in members if m["slug"] == slug), None)
and for a FIRST-TIME contributor the payer's OC account is not in the
collective's members list yet — OC reports them as guest-…/incognito-…. So
`member` was None, the whole branch fell through, and because the payload had
arrived successfully there was no error to record either. No account, no
welcome email, no credit, no log line. The sweep's unmapped-backers check
found it hours later, which is the wrong place to find it.
The fix resolves the payer from the order's account slug (`Individual.email`,
which OC exposes for an ordinary guest checkout), and when even that yields no
email it says so at ERROR level. A payment we cannot attribute is news, never
a shrug.
The "silent no-op" shape is the actual defect here: an `if` with no `else` on a
money path, where the absence of an action leaves no trace.
"""
import asyncio
import os
import pathlib
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "payer-fixture.db")
import app.main as m # noqa: E402
m.DB_PATH = os.environ["DB_PATH"]
m.OC_PERSONAL_TOKEN = "test-token"
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
REAL_POST = m._oc_graphql_post
class FakeResponse:
"""Mirror httpx.Response: the REAL _oc_graphql_post returns a response, not
parsed JSON. An earlier stub returned a dict, the test passed, and the first
live call died with 'Response object has no attribute get' — a stub that does
not match the real return shape certifies nothing."""
def __init__(self, payload):
self._payload = payload
def json(self):
return self._payload
LAST_HEADERS = {}
def fake_post(payload):
"""Stand in for OC's GraphQL endpoint (the response wrapper, not the JSON)."""
async def _post(client, json_body, headers=None, attempts=2):
LAST_HEADERS.clear()
LAST_HEADERS.update(headers or {})
return FakeResponse(payload)
return _post
print("1. an ordinary guest checkout resolves to the payer's email")
m._oc_graphql_post = fake_post({"data": {"account": {
"__typename": "Individual", "id": "acc_x", "name": "Conor W",
"slug": "guest-71e9d110", "email": "Conor.Canaday@Gmail.com", "isIncognito": False}}})
acct = asyncio.run(m.fetch_account_by_slug("guest-71e9d110"))
check(acct and acct["email"] == "conor.canaday@gmail.com",
f"the email is returned and normalised (got {acct and acct.get('email')!r})")
check(acct and acct["name"] == "Conor W", "the name comes back too, for the welcome email")
check(LAST_HEADERS.get("Personal-Token") == "test-token",
"the lookup AUTHENTICATES: without the personal token OC answers the unauthenticated view and hides every email "
f"(headers sent: {sorted(LAST_HEADERS)})")
print("2. an incognito profile yields NO email — and says so rather than guessing")
m._oc_graphql_post = fake_post({"data": {"account": {
"__typename": "Individual", "id": "acc_y", "name": "Incognito",
"slug": "incognito-5ad60182", "email": None, "isIncognito": True}}})
acct = asyncio.run(m.fetch_account_by_slug("incognito-5ad60182"))
check(acct is not None and acct.get("email") is None,
"incognito: the account is returned, the email is None (a slug is not an address)")
print("3. failures and edge cases never raise — the caller must be able to report")
m._oc_graphql_post = fake_post({"data": {"account": None}})
check(asyncio.run(m.fetch_account_by_slug("guest-nope")) is None,
"an account OC does not know returns None")
m._oc_graphql_post = fake_post({})
check(asyncio.run(m.fetch_account_by_slug("guest-nope")) is None,
"an empty payload returns None")
def boom(client, json_body, headers=None, attempts=2):
raise RuntimeError("OC read timed out")
m._oc_graphql_post = boom
check(asyncio.run(m.fetch_account_by_slug("guest-x")) is None,
"a failing lookup returns None instead of dying mid-webhook")
check(asyncio.run(m.fetch_account_by_slug("")) is None, "an empty slug is not looked up")
m.OC_PERSONAL_TOKEN = ""
check(asyncio.run(m.fetch_account_by_slug("guest-x")) is None,
"with no OC token configured there is no lookup to make")
m.OC_PERSONAL_TOKEN = "test-token"
print("4. the webhook branch: the fix is present, and its silent-fallthrough shape is gone")
src = (ROOT / "app" / "main.py").read_text()
branch = src[src.index('if "membership" in verified_tier.lower()'):]
branch = branch[:branch.index("elif slug and first_payment")]
check("fetch_account_by_slug(slug)" in branch,
"the branch resolves an unknown payer by account email")
check("logger.error(" in branch and "NOBODY was provisioned or credited" in branch,
"an unresolvable payer is logged at ERROR — not swallowed")
check(branch.count("if member:") == 1 and "logger.warning(" in branch,
"a resolved-by-email payer is announced in the log")
m._oc_graphql_post = REAL_POST
print()
if FAILS:
print(f"resolve payer: {len(FAILS)} FAILURE(S)")
sys.exit(1)
print("resolve payer: OK — first-time payers resolve, unresolvable ones are loud")
+393
View File
@@ -0,0 +1,393 @@
#!/usr/bin/env python3
"""Regression test: the service-invite sync (per-room invites + frequent tick).
WHY THIS EXISTS
A new member got a Loomio account and a Matrix account but could see NOTHING:
no forum group, no Space. Two separate defects produced that, and a third
made it take hours.
1. PER-ROOM GATE (the visibility bug). sync_matrix_space() gated each member
on the SPACE's membership: anyone already joined/invited to the Space was
skipped for EVERY room. So a member whose invite pass was interrupted, or
who predates a room added to MATRIX_INVITE_ROOMS later, never received
that room's invite — and a restricted child room is invisible until you
are invited to it.
2. RATE LIMITS ENDED NOTHING. A 429 slept for retry_after_ms (minutes) inside
the pass, so a scheduled run could outlive its own tick. A rate limit must
END the pass; the next run resumes (every invite is idempotent).
3. THE DEDUPE RECORD DRIFTED. A member sitting in the Loomio group with no
members.loomio_invited_at stamp (added by an earlier sync generation, or
by hand) reads as "never invited" — the guard is only as good as the rows
it happens to have. The sync now heals the record from the live roster.
4. NOTHING WATCHED ACTIVATION. Provisioning skips an unactivated account by
design, and activation happens later with nobody watching, so the 3x/day
sweep was the pickup. /admin/service-sync is the frequent tick that closes
that window; it must be a no-op (one SELECT) in the steady state.
Network is STUBBED throughout; assertions are on what we SENT and on our own
recorded state.
Runnable: python3 tests/test_service_invites.py (from the repo root)
"""
import os
import sys
import tempfile
import asyncio
import httpx
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["MATRIX_BOT_TOKEN"] = "test-bot-token"
os.environ["MATRIX_SPACE_ID"] = "!space:inference.coop"
os.environ["MATRIX_HOMESERVER"] = "https://matrix.inference.coop"
os.environ["MATRIX_INVITE_ROOMS"] = "!space:inference.coop,!general:inference.coop,!design:inference.coop"
os.environ["LOOMIO_API_KEY"] = "test-user-key"
os.environ["LOOMIO_B3_KEY"] = "test-server-key"
os.environ["LOOMIO_GROUP_ID"] = "1"
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m # noqa: E402
# The app module and this test share the SAME httpx module object, so stubbing
# the client below replaces it process-wide. Keep a handle on the real class for
# the ASGI call at the end.
REAL_ASYNC_CLIENT = httpx.AsyncClient
m.DB_PATH = os.environ["DB_PATH"]
m.MATRIX_BOT_TOKEN = "test-bot-token"
m.MATRIX_SPACE_ID = "!space:inference.coop"
m.MATRIX_HOMESERVER = "https://matrix.inference.coop"
m.MATRIX_INVITE_ROOMS = [
"!space:inference.coop", "!general:inference.coop", "!design:inference.coop"
]
m.MATRIX_EXTRA_ROOMS = []
m.LOOMIO_ALWAYS_KEEP = []
m.ADMIN_TOKEN = "test-admin-token"
m.ADMIN_TOKEN_LEGACY = ""
m.WEBHOOK_TOKEN = ""
ROOMS = ["!space:inference.coop", "!general:inference.coop", "!design:inference.coop"]
USERS = {"a@x.org": "amember", "b@x.org": "bmember", "c@x.org": "cmember"}
ROOM_JOINED = {} # room -> set(mxid)
ROOM_INVITED = {} # room -> set(mxid)
UNREADABLE = set() # rooms whose joined_members 500s
invites_sent = [] # (room, mxid)
INVITE_429_FOR = set() # mxids whose invite comes back 429
INVITE_TIMEOUT_FOR = set() # mxids whose invite POST raises httpx.ReadTimeout
TIMEOUT_ATTEMPTS = [] # (room, mxid) for every POST that timed out
POSTS = [] # Loomio POST payloads
ROSTER = {} # Loomio roster: email -> membership id
class FakeResp:
def __init__(self, status=200, payload=None, text=None):
self.status_code = status
self._payload = payload or {}
self.text = text if text is not None else str(payload or {})
def raise_for_status(self):
if self.status_code >= 400:
raise RuntimeError(f"HTTP {self.status_code}")
def json(self):
return self._payload
class FakeClient:
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, url, headers=None, params=None):
if "/api/v1/users" in url:
return FakeResp(200, {"users": [
{"email": e, "username": u, "inviteAccepted": True}
for e, u in USERS.items()
]})
for room in ROOMS:
if f"/rooms/{room}/joined_members" in url:
if room in UNREADABLE:
return FakeResp(500, {"error": "boom"})
return FakeResp(200, {"joined": {m: {} for m in ROOM_JOINED.get(room, set())}})
if f"/rooms/{room}/members" in url:
return FakeResp(200, {"chunk": [
{"state_key": mx} for mx in ROOM_INVITED.get(room, set())
]})
if "/api/b3/memberships" in url:
rows = [{"id": i, "user_email": e} for e, i in ROSTER.items()]
offset = (params or {}).get("offset", 0)
limit = (params or {}).get("limit", 50)
return FakeResp(200, {"memberships": rows[offset:offset + limit]})
return FakeResp(404, {})
async def post(self, url, headers=None, json=None):
if "/invite" in url:
mxid = (json or {}).get("user_id")
if mxid in INVITE_TIMEOUT_FOR:
TIMEOUT_ATTEMPTS.append((url, mxid))
raise httpx.ReadTimeout("timed out")
if mxid in INVITE_429_FOR:
return FakeResp(429, {"retry_after_ms": 300000},
text='{"errcode":"M_LIMIT_EXCEEDED"}')
for room in ROOMS:
if f"/rooms/{room}/invite" in url:
invites_sent.append((room, mxid))
ROOM_INVITED.setdefault(room, set()).add(mxid)
return FakeResp(200, {})
return FakeResp(200, {})
if "/api/b2/memberships" in url:
POSTS.append(json or {})
return FakeResp(200, {"added_emails": (json or {}).get("emails", [])})
return FakeResp(200, {})
async def put(self, *a, **k):
return FakeResp(200, {})
async def delete(self, *a, **k):
return FakeResp(200, {})
async def patch(self, *a, **k):
return FakeResp(200, {})
results = []
def check(name, ok):
results.append((name, ok))
def reset():
global invites_sent
invites_sent = []
POSTS.clear()
TIMEOUT_ATTEMPTS.clear()
async def main():
global ROOM_JOINED, ROOM_INVITED, UNREADABLE, INVITE_429_FOR, ROSTER
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
for email in USERS:
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES (?, 1)", (email,))
conn.execute("INSERT OR REPLACE INTO members (email, active, account_type) VALUES (?, 1, 'guest')",
("guest@x.org",))
conn.commit()
conn.close()
m.httpx.AsyncClient = FakeClient
async def _active():
return list(USERS.keys())
m.get_active_member_emails = _active
# --- 1. PER-ROOM GATE -------------------------------------------------
# a@ is already in every room. b@ has the Space + General but is MISSING
# Design — the exact state an interrupted pass leaves behind.
ROOM_JOINED = {"!space:inference.coop": {"@amember:inference.coop"},
"!general:inference.coop": {"@amember:inference.coop"},
"!design:inference.coop": {"@amember:inference.coop"}}
ROOM_INVITED = {"!space:inference.coop": {"@bmember:inference.coop"},
"!general:inference.coop": {"@bmember:inference.coop"},
"!design:inference.coop": set()}
USERS["c@x.org"] = "cmember"
ROOM_JOINED["!space:inference.coop"].add("@cmember:inference.coop")
ROOM_INVITED["!space:inference.coop"].add("@cmember:inference.coop")
ROOM_JOINED["!general:inference.coop"].add("@cmember:inference.coop")
ROOM_INVITED["!general:inference.coop"].add("@cmember:inference.coop")
ROOM_JOINED["!design:inference.coop"].add("@cmember:inference.coop")
ROOM_INVITED["!design:inference.coop"].add("@cmember:inference.coop")
reset()
r = await m.sync_matrix_space()
check("per-room: only the MISSING room is invited, by room id",
invites_sent == [("!design:inference.coop", "@bmember:inference.coop")])
check("per-room: an account already in every room is not re-invited",
not any(mx == "@amember:inference.coop" for _, mx in invites_sent))
check("per-room: two members can be pending on different rooms",
not any(mx == "@cmember:inference.coop" for _, mx in invites_sent))
check("return shape: the result carries invited + rate_limited + transport_skipped",
set(r) == {"invited", "rate_limited", "transport_skipped"} and r["rate_limited"] is False)
# --- 2. IDEMPOTENCE: a second pass sends nothing ----------------------
reset()
await m.sync_matrix_space()
check("idempotent: a second pass sends no invites", invites_sent == [])
# --- 3. RATE LIMIT ENDS THE PASS (no sleeping inside a scheduled tick) -
# d@ is missing all three rooms; the FIRST invite 429s.
USERS["d@x.org"] = "dmember"
m.get_db().close()
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES ('d@x.org', 1)")
conn.commit()
conn.close()
async def active_with_d():
return ["d@x.org", "a@x.org"]
m.get_active_member_emails = active_with_d
INVITE_429_FOR = {"@dmember:inference.coop"}
reset()
r = await m.sync_matrix_space()
check("rate limit: the pass reports it was rate limited", r["rate_limited"] is True)
check("rate limit: it does NOT retry in a loop inside the pass",
invites_sent == [])
INVITE_429_FOR = set()
m.get_active_member_emails = _active
# A resumed pass DOES send the invites the limited one could not.
reset()
r = await m.sync_matrix_space()
check("rate limit: the next pass resumes and invites the missed rooms",
len(invites_sent) == 3 and {room for room, _ in invites_sent} == set(ROOMS))
# --- 4. A ROOM WE CANNOT READ IS LEFT ALONE ---------------------------
# e@ is only missing Design, and Design's membership cannot be read.
USERS["e@x.org"] = "emember"
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, active) VALUES ('e@x.org', 1)")
conn.commit()
conn.close()
async def active_with_e():
return ["e@x.org"]
m.get_active_member_emails = active_with_e
ROOM_JOINED = {r_: set() for r_ in ROOMS}
ROOM_INVITED = {"!space:inference.coop": {"@emember:inference.coop"},
"!general:inference.coop": {"@emember:inference.coop"},
"!design:inference.coop": set()}
UNREADABLE = {"!design:inference.coop"}
reset()
await m.sync_matrix_space()
check("unreadable room: never invited into a room whose members we could not read",
invites_sent == [])
UNREADABLE = set()
m.get_active_member_emails = _active
# --- 5. LOOMIO RECORD SELF-HEAL --------------------------------------
# b@ is sitting in the group with NO stamp: the guard would call them
# "never invited". The sync must heal the record from the roster, and must
# not send their address anywhere while doing it.
conn = m.get_db()
conn.execute("UPDATE members SET loomio_invited_at = NULL")
conn.commit()
conn.close()
ROSTER = {"b@x.org": 55}
reset()
await m.sync_loomio_memberships()
sent = sorted((POSTS[0].get("emails") if POSTS else []) or [])
check("heal: a present member with no stamp is stamped as invited",
m.get_loomio_invited_at("b@x.org") is not None)
check("heal: healing never re-sends a member already in the group",
"b@x.org" not in sent)
check("heal: an unstamped member who is NOT present is still invited",
sent == ["a@x.org", "c@x.org", "d@x.org", "e@x.org"])
# --- 6. THE FREQUENT TICK'S WAKE-UP CONDITION -------------------------
conn = m.get_db()
conn.execute("UPDATE members SET loomio_invited_at = NULL WHERE email = 'e@x.org'")
conn.commit()
conn.close()
pending = m._service_sync_pending()
check("pending: a member still awaiting their invite is counted", pending == ["e@x.org"])
check("pending: an invited member is NOT counted", "a@x.org" not in pending)
check("pending: guests are never counted", "guest@x.org" not in pending)
m.mark_loomio_invited("e@x.org")
check("pending: empty once every member is stamped", m._service_sync_pending() == [])
# --- 7. ONE MEMBER'S TRANSPORT TIMEOUT MUST NOT KILL THE PASS ---------
# A ReadTimeout on ONE invite used to abort the whole sync: every member
# after the timed-out one silently got nothing, and the log line carried an
# empty message. Two members need invites; the FIRST times out.
global INVITE_TIMEOUT_FOR
conn = m.get_db()
for email, stamp in (("t@x.org", "2026-01-01 00:00:00"), ("u@x.org", "2026-01-01 00:00:00")):
conn.execute("INSERT OR REPLACE INTO members (email, active, loomio_invited_at) VALUES (?, 1, ?)",
(email, stamp))
conn.commit()
conn.close()
USERS["t@x.org"] = "tmember"
USERS["u@x.org"] = "umember"
async def active_with_tu():
return ["t@x.org", "u@x.org"]
m.get_active_member_emails = active_with_tu
ROOM_JOINED = {r_: set() for r_ in ROOMS}
ROOM_INVITED = {r_: set() for r_ in ROOMS}
INVITE_TIMEOUT_FOR = {"@tmember:inference.coop"}
reset()
r = await m.sync_matrix_space()
check("timeout: a transport timeout does not raise out of the pass", isinstance(r, dict))
check("timeout: the member AFTER the timed-out one is still invited",
{room for room, _ in invites_sent} == set(ROOMS)
and all(mx == "@umember:inference.coop" for _, mx in invites_sent))
check("timeout: the timed-out member is not counted as invited", r["invited"] == 1)
check("timeout: a timed-out member is attempted ONCE, not once per room",
len(TIMEOUT_ATTEMPTS) == 1)
check("timeout: the pass reports the member whose rooms it skipped",
r.get("transport_skipped") == 1)
# The next pass retries the timed-out member (invites are idempotent).
INVITE_TIMEOUT_FOR = set()
reset()
await m.sync_matrix_space()
check("timeout: the next pass sends the timed-out member's invites",
len(invites_sent) == 3 and all(mx == "@tmember:inference.coop" for _, mx in invites_sent))
# Clean up so the endpoint checks see a steady state.
conn = m.get_db()
conn.execute("DELETE FROM members WHERE email IN ('t@x.org', 'u@x.org')")
conn.commit()
conn.close()
INVITE_TIMEOUT_FOR = set()
m.get_active_member_emails = _active
ROOM_JOINED = {r_: set() for r_ in ROOMS}
ROOM_INVITED = {r_: set() for r_ in ROOMS}
asyncio.run(main())
# --- 7. THE ENDPOINT (real ASGI call, so the wiring is exercised) ----------
async def endpoint_checks():
transport = httpx.ASGITransport(app=m.app)
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
r = await c.post("/admin/service-sync")
check(f"endpoint: rejects a caller with no admin token (got {r.status_code})",
r.status_code == 403)
r = await c.post("/admin/service-sync", headers={"X-Admin-Token": "wrong"})
check(f"endpoint: rejects a wrong admin token (got {r.status_code})",
r.status_code == 403)
r = await c.post("/admin/service-sync", headers={"X-Admin-Token": "test-admin-token"})
check(f"endpoint: accepts the admin token (got {r.status_code})", r.status_code == 200)
body = r.json()
check(f"endpoint: is IDLE (one SELECT) when nobody is awaiting an invite (got {body})",
body.get("status") == "idle")
# Make one member await an invite again and prove the tick RUNS.
conn = m.get_db()
conn.execute("UPDATE members SET loomio_invited_at = NULL WHERE email = 'a@x.org'")
conn.commit()
conn.close()
r = await c.post("/admin/service-sync", headers={"X-Admin-Token": "test-admin-token"})
body = r.json()
check(f"endpoint: RUNS while a member is awaiting invites (got {body})",
body.get("status") == "ran" and body.get("pending") == 1)
check(f"endpoint: runs BOTH syncs (got {body})",
body.get("loomio") == "ok" and "matrix" in body)
asyncio.run(endpoint_checks())
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)
+33
View File
@@ -0,0 +1,33 @@
import asyncio, os, sys, tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "settle.db")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
m.DB_PATH = os.environ["DB_PATH"]
def seed():
conn = m.get_db()
for email, slug, active, credits in (
("active@example.org", "active-slug", 1, 0.0),
("inactive@example.org", "inactive-slug", 0, 0.0),
):
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance) VALUES (?,?,?,?)",
(email, slug, active, credits))
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
("active-slug", "active@example.org", "A", 10.0, "oc:active-slug:xyz"))
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
("inactive-slug", "inactive@example.org", "I", 5.0, "oc:inactive-slug:xyz"))
conn.commit(); conn.close()
def credits(email):
conn = m.get_db(); v = conn.execute("SELECT credit_balance FROM members WHERE email=?", (email,)).fetchone()[0]; conn.close(); return v
seed()
r1 = asyncio.run(m.settle_held_credits(send=False))
print(" run1:", r1["held"], "held |", len(r1["granted"]), "granted |", len(r1["unresolved"]), "unresolved")
assert credits("active@example.org") == 10.0, "active member's hold must be credited"
assert credits("inactive@example.org") == 0.0, "inactive member must NOT be credited"
assert len(r1["granted"]) == 1 and len(r1["unresolved"]) == 1
r2 = asyncio.run(m.settle_held_credits(send=False))
assert credits("active@example.org") == 10.0, "re-run must not double-apply"
assert len(r2["granted"]) == 0, "second run grants nothing"
print("SETTLE HELD CREDITS OK: grants to active, holds for inactive, idempotent")
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env python3
"""Regression test: the spend-consistency check (portal aggregate vs LiteLLM's API).
WHY THIS EXISTS
On 2026-11-05 the portal's aggregation of all-time spend failed SOFT: its copy of
the gateway's LiteLLM DB credential had gone stale, so the query returned nothing,
every surface showed $0, and nothing looked wrong — the portal WAS the thing that
was wrong. The guard ran as a daily script on the bot's host. It now runs in the
portal's sweep.
The first TWO live runs also taught the shape of the comparison, and both lessons
are pinned here:
* window. LiteLLM's per-day view reaches back a fixed number of days (31 on
2026-11-13) while our table holds everything, so comparing our ALL-TIME figure
against it reported $107.63 of "drift" that was only the missing window. Compare
the days BOTH sides cover.
* like-for-like source. `/global/spend/keys` reports each key's spend over the
key's own budget cycle (`total_spend` — and reading `spend` returned $0 for all
306 keys), so it is NOT an all-time figure. The per-day teams view is comparable,
and comparing day by day localises drift instead of hiding it in a sum.
Runnable: python3 tests/test_spend_check.py (from the repo root)
"""
import os
import sys
import types
import asyncio
import tempfile
import httpx
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.ADMIN_TOKEN = "test-admin-token"
m.ADMIN_TOKEN_LEGACY = ""
m.LITELLM_MASTER_KEY = "test-master-key" # the parser test calls the real function
SENT = []
# main() replaces the module attribute with a stub; keep the REAL implementation so
# the parser itself can be exercised.
REAL_API_DAILY_SPEND = m.litellm_api_daily_spend
def fake_send(to, subject, body, *a, **k):
SENT.append({"to": to, "subject": subject, "body": body})
# --- stubs ----------------------------------------------------------------- #
DAYS = {"2026-11-10": 10.0, "2026-11-11": 20.0, "2026-11-12": 30.0}
API_DAYS = dict(DAYS)
PORTAL_DAYS = dict(DAYS)
PORTAL_ROWS = 1000
FAIL_PORTAL = False
FAIL_API = False
def fake_portal_days():
if FAIL_PORTAL:
raise RuntimeError("psycopg2: connection refused")
return dict(PORTAL_DAYS), round(sum(PORTAL_DAYS.values()), 6), PORTAL_ROWS
async def fake_api_days():
if FAIL_API:
raise RuntimeError("LiteLLM spend API: HTTP 401")
return dict(API_DAYS)
results = []
def check(name, ok):
results.append((name, bool(ok)))
async def main():
global FAIL_PORTAL, FAIL_API, PORTAL_DAYS, PORTAL_ROWS, API_DAYS
m.litellm_spend_by_day = fake_portal_days
m.litellm_api_daily_spend = fake_api_days
m.send_email = fake_send
m.get_db().close() # create + migrate the fixture schema
def marker():
conn = m.get_db()
row = conn.execute("SELECT value FROM portal_state WHERE key = ?",
(m.SPEND_CHECK_MARKER,)).fetchone()
conn.close()
return row[0] if row else None
def reset():
global PORTAL_DAYS, PORTAL_ROWS, API_DAYS
PORTAL_DAYS, PORTAL_ROWS, API_DAYS = dict(DAYS), 1000, dict(DAYS)
# --- agreement over the shared window: silent ---
reset()
SENT.clear()
r = await m.check_spend_consistency()
check(f"agreement is ok (got {r.get('status')})", r.get("status") == "ok")
check(f"agreement reports the shared window (got {r})",
r.get("window") == "2026-11-10..2026-11-12" and r.get("days_compared") == 3
and r.get("portal_window") == 60.0 and r.get("api_window") == 60.0)
check(f"agreement sends NO email (got {len(SENT)})", len(SENT) == 0)
check(f"agreement clears the marker (got {marker()!r})", not marker())
# --- days only ONE side has are NOT drift ---
PORTAL_DAYS = {"2026-09-04": 99.0, **DAYS} # 69-day history vs a 31-day view
SENT.clear()
r = await m.check_spend_consistency()
check(f"a longer portal history is not reported as drift (got {r.get('status')}, "
f"all-time {r.get('portal_all_time')}, delta {r.get('delta')})",
r.get("status") == "ok" and r.get("portal_all_time") == 159.0
and r.get("delta") == 0.0 and len(SENT) == 0)
reset()
# --- the 2026-11-05 signature: portal empty while LiteLLM is real ---
PORTAL_DAYS, PORTAL_ROWS = {}, 0
SENT.clear()
r = await m.check_spend_consistency()
check(f"an EMPTY portal aggregate against real spend FAILS (got {r.get('status')})",
r.get("status") == "failed" and "silent-clean signature" in (r.get("reason") or ""))
check(f"info@ is told once (got {len(SENT)})",
len(SENT) == 1 and SENT[0]["to"] == "info@inference.coop"
and "credential" in SENT[0]["body"])
r2 = await m.check_spend_consistency()
check(f"the SAME failure is not re-mailed (got {len(SENT)} emails)",
r2.get("reported") is False and len(SENT) == 1)
# --- recovery is clean again, and a recurrence speaks ---
PORTAL_DAYS, PORTAL_ROWS = dict(DAYS), 1000
r = await m.check_spend_consistency()
check(f"recovery is clean (got {r.get('status')})", r.get("status") == "ok")
check(f"recovery clears the marker (got {marker()!r})", not marker())
PORTAL_DAYS, PORTAL_ROWS = {}, 0
SENT.clear()
r = await m.check_spend_consistency()
check(f"a recurrence mails again (got {r.get('status')}, {len(SENT)} emails)",
r.get("status") == "failed" and len(SENT) == 1)
reset()
await m.check_spend_consistency() # back to clean
# --- a DAY that drifts beyond the per-day tolerance is named ---
API_DAYS = {"2026-11-10": 10.0, "2026-11-11": 20.0, "2026-11-12": 44.0}
SENT.clear()
r = await m.check_spend_consistency()
check(f"a drifting day FAILS and is named (got {r.get('status')}, {r.get('drifting_days')})",
r.get("status") == "failed" and bool(r.get("drifting_days"))
and r["drifting_days"][0]["date"] == "2026-11-12"
and "2026-11-12" in (r.get("reason") or ""))
check(f"the notice lists the worst day (got {len(SENT)})",
len(SENT) == 1 and "2026-11-12" in SENT[0]["body"])
reset()
await m.check_spend_consistency()
# --- cents-level rounding is NOT drift ---
API_DAYS = {"2026-11-10": 10.02, "2026-11-11": 19.98, "2026-11-12": 30.01}
SENT.clear()
r = await m.check_spend_consistency()
check(f"cent-level rounding passes (got {r.get('status')}, delta {r.get('delta')})",
r.get("status") == "ok" and len(SENT) == 0)
reset()
# --- no shared window: cannot compare, must NOT read as clean ---
API_DAYS = {"2026-10-01": 5.0}
r = await m.check_spend_consistency()
check(f"no shared window is skipped, not clean (got {r})",
r.get("status") == "skipped" and r.get("reason") == "no_overlapping_window")
reset()
# --- a read that cannot be made is UNKNOWN ---
FAIL_PORTAL = True
SENT.clear()
r = await m.check_spend_consistency()
check(f"an unreadable portal side is skipped (got {r})",
r.get("status") == "skipped" and r.get("reason") == "portal_read_failed"
and len(SENT) == 0)
FAIL_PORTAL = False
FAIL_API = True
r = await m.check_spend_consistency()
check(f"an unreadable LiteLLM side is skipped (got {r})",
r.get("status") == "skipped" and r.get("reason") == "litellm_api_failed")
FAIL_API = False
# --- notify=False never mails and never consumes ---
conn = m.get_db()
conn.execute("DELETE FROM portal_state")
conn.commit()
conn.close()
PORTAL_DAYS, PORTAL_ROWS = {}, 0
SENT.clear()
r = await m.check_spend_consistency(notify=False)
check(f"notify=False reports nothing (got {r.get('reported')}, {len(SENT)} emails)",
r.get("status") == "failed" and r.get("reported") is False and len(SENT) == 0)
r = await m.check_spend_consistency()
check(f"...and a later notifying run still speaks (got {len(SENT)} emails)",
r.get("reported") is True and len(SENT) == 1)
reset()
# --- the parser: the API's shape is per-day, per-team ---
class _Resp:
status_code = 200
def json(self):
return {"daily_spend": [
{"date": "2026-11-12", "member:a@x.org": 1.5, "member:b@x.org": 2.25},
{"date": "2026-11-13", "member:a@x.org": 0.5},
{"date": "", "member:a@x.org": 9.0}, # no date -> ignored
{"member:a@x.org": 7.0}, # no date -> ignored
]}
class _FakeClient:
def __init__(self, *a, **k):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
async def get(self, *a, **k):
return _Resp()
real_httpx = m.httpx
m.httpx = types.SimpleNamespace(AsyncClient=_FakeClient)
try:
days = await REAL_API_DAILY_SPEND()
finally:
m.httpx = real_httpx
check(f"the parser sums each day's teams (got {days})",
days == {"2026-11-12": 3.75, "2026-11-13": 0.5})
# --- the endpoint ---
SENT.clear()
transport = httpx.ASGITransport(app=m.app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
r = await c.post("/admin/spend-check")
check(f"endpoint needs the admin token (got {r.status_code})",
r.status_code in (401, 403))
r = await c.post("/admin/spend-check", headers={"X-Admin-Token": "test-admin-token"})
body = r.json()
check(f"endpoint reports the comparison (got {body.get('status')})",
r.status_code == 200 and body.get("status") == "ok"
and body.get("api_window") == 60.0)
check(f"endpoint: a clean result mails nothing (got {len(SENT)})", len(SENT) == 0)
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)
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""Regression test: paid OC contributors with no portal row (the unmapped-backer net).
WHY THIS EXISTS
A contributor pays the collective and never gets an account, because our sweep
cannot SEE them: fetch_members() drops every member node with no email, and an
OC Organization never exposes one at all. The mmoya case (2026-10/11) was found
weeks late, by the member asking. The net ran as a script on the bot's host,
driving `cloudron exec` from outside; it now lives in the portal, where both
sides of the comparison already are.
WHAT IS PINNED DOWN HERE
* the member definition matches fetch_members()'s (ADMIN, or Membership/legacy
tier — a Credit-pack-only BACKER is the held-credits flow, not a member),
* the three classes of finding are told apart (org / visible email / hidden
email) because each needs a DIFFERENT action from a human,
* a member node with no account object is attributed through same-day current
orders, and stays silent when every same-day payer is already mapped,
* info@ is told ONLY when there are findings, and only when the SET changes —
it runs three times a day, and a stuck finding must not mail every time,
* a fetch failure reports `skipped`, never a clean bill of health.
Runnable: python3 tests/test_unmapped_backers.py (from the repo root)
"""
import os
import sys
import asyncio
import tempfile
import httpx
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.ADMIN_TOKEN = "test-admin-token"
m.ADMIN_TOKEN_LEGACY = ""
SENT = []
def fake_send(to, subject, body, *a, **k):
SENT.append({"to": to, "subject": subject, "body": body})
FAIL_NODES = False
NODES: list = []
ORDERS: list = []
async def fake_nodes():
if FAIL_NODES:
raise RuntimeError("OC member fetch blew up")
return list(NODES)
async def fake_orders(per_page=100, max_pages=3):
return list(ORDERS)
def node(role, tier, slug=None, email=None, atype="INDIVIDUAL", name=None,
created="2026-11-01T00:00:00Z", account=True):
return {"role": role, "tier": ({"name": tier} if tier else None),
"createdAt": created,
"account": ({"name": name or (slug or "?"), "slug": slug, "type": atype,
"email": email} if account else None)}
def order(slug, status="ACTIVE", day="2026-11-01", amount=15):
return {"id": f"or_{slug}_{day}", "status": status, "createdAt": f"{day}T10:00:00Z",
"frequency": "MONTHLY", "amount": {"value": amount},
"totalAmount": {"value": amount}, "fromAccount": {"slug": slug, "name": slug}}
results = []
def check(name, ok):
results.append((name, bool(ok)))
def seed():
conn = m.get_db()
conn.execute("DELETE FROM members")
conn.execute("DELETE FROM portal_state")
for email, slug, org in (("alice@x.org", "alice", None),
("admin@x.org", "adminco", None),
("contact@beta.example", "beta-contact", "betaorg")):
conn.execute("INSERT INTO members (email, slug, org_slug, active, account_type, "
"credit_balance) VALUES (?, ?, ?, 1, 'member', 0)", (email, slug, org))
conn.commit()
conn.close()
async def main():
global FAIL_NODES
m.fetch_all_member_nodes = fake_nodes
m.fetch_collective_orders = fake_orders
m.send_email = fake_send
seed()
NODES[:] = [
# mapped by email -> not a finding
node("BACKER", "Membership", "alice", "alice@x.org", name="Alice"),
# mapped ADMIN -> not a finding
node("ADMIN", "Membership", "adminco", "admin@x.org", name="Co-op"),
# NOT a member: a credit-pack-only BACKER takes the held-credits path
node("BACKER", "Credit pack", "packbuyer", "pack@x.org", name="Pack Buyer"),
# NOT a member: a plain DONATION (no tier, joined after the legacy cutoff).
# OC grants BACKER role for any one-time contribution; a donation must stay
# silent instead of mailing info@ about a "missing account".
node("BACKER", None, "donor", "donor@x.org", name="Donor",
created="2026-11-21T15:10:00Z"),
# FINDING: a LEGACY no-tier BACKER (before the tier system) IS a member
node("BACKER", None, "legacy", "legacy@x.org", name="Legacy",
created="2026-01-01T00:00:00Z"),
# not a member role
node("MEMBER", "Membership", "roleonly", "role@x.org", name="Role Only"),
# FINDING: visible email -> the sweep should have provisioned this
node("BACKER", "Membership", "vic", "vic@x.org", name="Visible Vic"),
# FINDING: email hidden even from the admin view
node("BACKER", "Membership", "han", None, name="Hidden Han"),
# a MAPPED Organization (its org_slug is on a portal row) -> not a finding
node("BACKER", "Membership", "betaorg", None, atype="ORGANIZATION", name="Beta Org"),
# FINDING: an Organization OC never exposes an email for
node("BACKER", "Membership", "gammaorg", None, atype="ORGANIZATION", name="Gamma Org"),
# null-account node on a day whose only payer is MAPPED -> silent
node("BACKER", "Membership", account=False, created="2026-11-01T00:00:00Z"),
# null-account node on a day with an UNMAPPED payer -> finding
node("BACKER", "Membership", account=False, created="2026-11-02T00:00:00Z"),
# null-account node with NO date -> NOT a finding: there is nothing to
# attribute it against, and reporting it is how a phantom appears (the
# members query did not select createdAt, so every such node looked like an
# uncredited payer on the day "").
{"role": "BACKER", "tier": {"name": "Membership"}, "createdAt": None, "account": None},
]
ORDERS[:] = [
order("alice", day="2026-11-01"),
order("ghost", day="2026-11-02"),
order("vic", day="2026-11-03", amount=25),
]
SENT.clear()
res = await m.reconcile_unmapped_backers()
check(f"the check runs (got {res.get('status')})", res.get("status") == "ok")
classes = sorted(res.get("classes") or [])
check(f"five findings in four classes (got {res.get('findings')} {classes})",
res.get("findings") == 5 and classes == ["hidden", "null-account", "org", "visible"])
check("a node with no createdAt is NOT reported (nothing to attribute it against)",
sum(1 for f in res["detail"] if f["class"] == "null-account") == 1)
slugs = sorted(f["slug"] or "(null-account)" for f in res["detail"])
check(f"exactly the unmapped member-ish nodes are findings (got {slugs})",
slugs == ["(null-account)", "gammaorg", "han", "legacy", "vic"])
check("a Credit-pack-only BACKER is not a member finding",
not any(f["slug"] == "packbuyer" for f in res["detail"]))
check("a post-cutoff no-tier BACKER (a plain donation) is not a finding",
not any(f["slug"] == "donor" for f in res["detail"]))
check("a LEGACY no-tier BACKER is still a member finding",
any(f["slug"] == "legacy" for f in res["detail"]))
check("a MEMBER-role node is not a member finding",
not any(f["slug"] == "roleonly" for f in res["detail"]))
vis = {f["slug"]: f["email_visibility"] for f in res["detail"]}
check("the VISIBLE case tells the operator the sweep should have caught it",
"VISIBLE" in vis.get("vic", "") and "sweep" in
next(f["action"] for f in res["detail"] if f["slug"] == "vic"))
check("the ORG case points at /admin/org-link",
"/admin/org-link" in next(f["action"] for f in res["detail"] if f["slug"] == "gammaorg"))
check("the HIDDEN case says the email must be fetched out-of-band",
"out-of-band" in next(f["action"] for f in res["detail"] if f["slug"] == "han"))
check(f"findings carry the payer's dues (got {next(f['dues'] for f in res['detail'] if f['slug'] == 'vic')})",
"$25 MONTHLY ACTIVE" in next(f["dues"] for f in res["detail"] if f["slug"] == "vic"))
check(f"the null-account finding names the unmapped same-day payer (got "
f"{next(f['dues'] for f in res['detail'] if f['class'] == 'null-account')})",
"ghost" in next(f["dues"] for f in res["detail"] if f["class"] == "null-account"))
check(f"info@ is told once, with every class in the body (got {len(SENT)})",
len(SENT) == 1 and SENT[0]["to"] == "info@inference.coop"
and "org-link" in SENT[0]["body"] and "out-of-band" in SENT[0]["body"])
check("it says the notice covers what is new, not every sweep",
"not every sweep" in SENT[0]["body"])
# Same set again: a report, but NO second email.
res2 = await m.reconcile_unmapped_backers()
check(f"the same finding set is not re-emailed (got {len(SENT)} emails)",
res2.get("findings") == 5 and res2.get("reported") is False and len(SENT) == 1)
# The set CHANGES (one finding resolved): mail again.
NODES[:] = [n for n in NODES
if ((n.get("account") or {}) or {}).get("slug") != "han"]
res3 = await m.reconcile_unmapped_backers()
# A set that SHRINKS (one finding resolved) must NOT re-mail the survivors: a
# person already told about a finding is not told again just because the list
# got shorter. Only genuinely NEW keys speak.
check(f"a smaller set re-mails nobody (got {res3.get('findings')} findings, "
f"{res3.get('new')} new, {len(SENT)} emails)",
res3.get("findings") == 4 and res3.get("new") == 0 and len(SENT) == 1)
# Fully clear: silent, and the marker is cleared so a recurrence speaks up.
NODES[:] = [node("BACKER", "Membership", "alice", "alice@x.org", name="Alice")]
res4 = await m.reconcile_unmapped_backers()
check(f"a clean run says nothing (got {res4.get('findings')}, {len(SENT)} emails)",
res4.get("findings") == 0 and res4.get("reported") is False and len(SENT) == 1)
conn = m.get_db()
marker = conn.execute("SELECT value FROM portal_state WHERE key = ?",
(m.UNMAPPED_BACKERS_MARKER,)).fetchone()
conn.close()
check(f"the marker is cleared on a clean run (got {marker})", not (marker and marker[0]))
NODES[:] = [node("BACKER", "Membership", "vic", "vic@x.org", name="Visible Vic")]
res5 = await m.reconcile_unmapped_backers()
check(f"a finding after a clean run speaks up again (got {len(SENT)} emails)",
res5.get("findings") == 1 and res5.get("new") == 1 and len(SENT) == 2)
# Notify can be suppressed (on-demand checks must not mail).
NODES[:] = [node("BACKER", "Membership", "newguy", "new@x.org", name="New Guy")]
res6 = await m.reconcile_unmapped_backers(notify=False)
check(f"notify=False suppresses the mail (got {res6.get('findings')} findings, {len(SENT)} emails)",
res6.get("findings") == 1 and res6.get("reported") is False and len(SENT) == 2)
# ...and a look must not CONSUME the alert: the next notifying run still speaks.
res6b = await m.reconcile_unmapped_backers()
check(f"a silent look does not swallow the alert (got {res6b.get('new')} new, {len(SENT)} emails)",
res6b.get("reported") is True and len(SENT) == 3)
# A failed read is UNKNOWN, not silence.
FAIL_NODES = True
res7 = await m.reconcile_unmapped_backers()
check(f"a failed member fetch is skipped, not clean (got {res7})",
res7.get("status") == "skipped" and res7.get("reason") == "member_fetch_failed")
FAIL_NODES = False
# An order-fetch failure must not lose the finding.
async def boom_orders(per_page=100, max_pages=3):
raise RuntimeError("orders unavailable")
m.fetch_collective_orders = boom_orders
res8 = await m.reconcile_unmapped_backers()
check(f"a failed ORDER fetch still reports the finding (got {res8.get('findings')})",
res8.get("findings") == 1)
check("...and says so in the dues line",
"no order found" in res8["detail"][0]["dues"])
m.fetch_collective_orders = fake_orders
# --- the endpoint ---
# A fresh finding set, so the endpoint run has something NEW to report
# (the marker is per-set: the same set would rightly stay quiet).
NODES[:] = [node("BACKER", "Membership", "endpointcase", "ep@x.org", name="EP")]
SENT.clear()
transport = httpx.ASGITransport(app=m.app)
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
r = await c.post("/admin/unmapped-check")
check(f"endpoint: needs the admin token (got {r.status_code})", r.status_code in (401, 403))
r = await c.post("/admin/unmapped-check", headers={"X-Admin-Token": "test-admin-token"})
body = r.json()
check(f"endpoint: runs the check (got {body.get('findings')} findings)",
r.status_code == 200 and body.get("findings") == 1)
check(f"endpoint: the run mails once for the new set (got {len(SENT)})", len(SENT) == 1)
r = await c.post("/admin/unmapped-check?notify=0",
headers={"X-Admin-Token": "test-admin-token"})
check(f"endpoint: ?notify=0 suppresses the mail (got {len(SENT)} emails)",
r.status_code == 200 and len(SENT) == 1)
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)
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Regression test: an Open Collective webhook must never fail as a bare 500.
WHY THIS EXISTS
On 2026-11-13 a member's $50 credit-pack purchase arrived as an
`order.processed` delivery. The handler called fetch_members() to turn the OC
slug into an email, `fetch_all_member_nodes` used a bare httpx.AsyncClient()
(httpx's DEFAULT 5-second timeout), OC's GraphQL answered slower than that,
and `httpx.ReadTimeout` escaped the handler as an unhandled ASGI exception:
* the delivery returned 500, so nothing retried it usefully,
* no credits were granted — the member paid and got nothing for 40 minutes,
* the log carried a stack trace instead of anything naming the member or
the order, so the purchase could not be reconciled from the log alone.
The guards proven here, on a FIXTURE db with the network stubbed:
AUTH
1. A wrong URL token is still a 401 — the new error net must not swallow
the one status that means "the webhook URL and WEBHOOK_TOKEN disagree".
NO BARE 500
2. A transport failure while resolving the purchase answers 503 (retryable)
and the handler does not raise out of the ASGI app.
3. The same is true for a failure raised anywhere else in the handler.
MONEY
4. A resolvable purchase grants credits ONCE, with the per-order reference
`oc:<slug>:<idV2>`.
5. Re-delivering the identical payload returns `already_credited` and moves
no money — this is what makes OC's retries safe.
TRANSPORT
6. `_oc_graphql_post` retries once on a transport error and returns the
response; if both attempts fail it RAISES (callers keep their
fail-safes — a partial member list must never look complete).
Runnable: python3 tests/test_webhook_resilience.py (from the repo root)
"""
import asyncio
import os
import sys
import tempfile
import httpx
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "fixture.db")
os.environ["WEBHOOK_TOKEN"] = "test-webhook-token"
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m # noqa: E402
# The app module shares this httpx object, so stubbing it later would replace
# httpx.AsyncClient process-wide — keep a handle on the real class.
REAL_ASYNC_CLIENT = httpx.AsyncClient
m.DB_PATH = os.environ["DB_PATH"]
TOKEN = "test-webhook-token"
MEMBER_SLUG = "nightrose"
MEMBER_EMAIL = "nightrose@example.org"
ORDER_ID = "or_testOrderId123"
PAYLOAD = {
"type": "order.processed",
"data": {
"fromCollective": {"slug": MEMBER_SLUG, "name": "NightRose"},
"order": {
"idV2": ORDER_ID,
"description": "Financial contribution to Inference Cooperative (Credit pack)",
"totalAmount": 5000,
},
"amount": 5000,
"firstPayment": False,
},
}
results = []
def check(name, ok):
results.append((name, ok))
SENT = []
def fake_send(to, subject, body, *a, **k):
SENT.append({"to": to, "subject": subject, "body": body})
# --- stubs ----------------------------------------------------------------- #
async def fetch_members_ok():
return [{"email": MEMBER_EMAIL, "name": "NightRose", "slug": MEMBER_SLUG,
"role": "BACKER"}]
async def fetch_members_timeout():
raise httpx.ReadTimeout("simulated OC read timeout")
async def order_amount_ok(_order_id_v2=None):
return 5000
async def order_details_ok(_order_id_v2=None):
"""Verified OC order for the credit-pack fixture (2026-11-19 hardening)."""
return {
"id": "or_testOrderId123",
"status": "PAID",
"frequency": "ONETIME",
"amount": {"valueInCents": 5000},
"platformTipAmount": {"valueInCents": 0},
"fromAccount": {"slug": MEMBER_SLUG},
"toAccount": {"slug": m.OC_COLLECTIVE_SLUG},
"tier": {"name": "Credit pack"},
}
async def budget_noop(_email):
return 0.0
async def main():
m.get_db().close() # create + migrate the fixture schema
conn = m.get_db()
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance) "
"VALUES (?, ?, 1, 0)", (MEMBER_EMAIL, MEMBER_SLUG))
conn.commit()
conn.close()
transport = httpx.ASGITransport(app=m.app)
url = f"/webhook/opencollective/{TOKEN}"
m.sync_team_budget_from_balance = budget_noop # no LiteLLM calls in a test
m.get_order_amount = order_amount_ok
m.get_order_details = order_details_ok
async with REAL_ASYNC_CLIENT(transport=transport, base_url="http://test") as c:
# --- 1. AUTH: a wrong token is still a 401. ---
r = await c.post("/webhook/opencollective/wrong-token", json=PAYLOAD)
check(f"auth: a wrong webhook token is 401 (got {r.status_code})", r.status_code == 401)
# --- 2. NO BARE 500 when the OC lookup times out. ---
m.fetch_members = fetch_members_timeout
r = await c.post(url, json=PAYLOAD)
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
check(f"timeout: the delivery answers 503, not 500 (got {r.status_code})",
r.status_code == 503)
check(f"timeout: the response asks for a retry (got {body})",
body.get("retry") is True)
check("timeout: an unexpected failure never raises out of the app "
"(httpx.ReadTimeout was caught by the handler net)",
r.status_code != 500)
# --- 2b. The SYSTEM records the failures it refuses. ---
# The money-critical alert used to be a log scraper on the operator's own
# machine, reading a buffer with hours of memory — whole hours were missing
# from it during the 2026-11-13 investigation. The portal handles every
# delivery, so the portal is what must notice and say.
conn = m.get_db()
rows = [dict(zip(("id", "at", "status", "event_type", "detail"), r)) for r in
conn.execute("SELECT id, at, status, event_type, detail FROM webhook_failures "
"ORDER BY id")]
conn.close()
check(f"record: the refused 401 delivery is recorded by the portal (got {rows})",
any(r["status"] == 401 for r in rows))
check(f"record: the 503 is recorded with its event type (got {rows})",
any(r["status"] == 503 and r["event_type"] == "order.processed" for r in rows))
check("record: the 503 row names the exception that caused it",
any(r["status"] == 503 and "ReadTimeout" in (r["detail"] or "") for r in rows))
SENT.clear()
m.send_email = fake_send
rep = m.webhook_failure_report()
check(f"report: new failures are summarised (got {rep.get('new_failures')} rows)",
rep.get("status") == "reported" and rep.get("new_failures") == len(rows))
check(f"report: info@ is told, naming both kinds of failure (got {SENT})",
len(SENT) == 1 and SENT[0]["to"] == "info@inference.coop"
and "401" in SENT[0]["body"] and "503" in SENT[0]["body"]
and "WEBHOOK_TOKEN" in SENT[0]["body"])
rep2 = m.webhook_failure_report()
check(f"report: the SAME batch is not re-reported (got {rep2})",
rep2.get("new_failures") == 0 and len(SENT) == 1)
await c.post("/webhook/opencollective/wrong-token", json=PAYLOAD)
rep3 = m.webhook_failure_report()
check(f"report: a LATER failure is reported again (got {rep3.get('new_failures')})",
rep3.get("new_failures") == 1 and len(SENT) == 2)
# --- 3. MONEY: a resolvable purchase credits exactly once. ---
m.fetch_members = fetch_members_ok
r = await c.post(url, json=PAYLOAD)
body = r.json()
check(f"grant: a resolvable credit pack grants credits (got {body})",
r.status_code == 200 and body.get("status") == "credits_added"
and body.get("credits_added") == 50.0)
check("grant: the balance reflects the purchase",
m.get_credit_balance(MEMBER_EMAIL) == 50.0)
ref = m.credit_pack_reference(MEMBER_SLUG, {"idV2": ORDER_ID})
check("grant: the ledger row is keyed on the OC order (idempotence key)",
ref == f"oc:{ORDER_ID}" and m.credit_reference_exists(ref))
# --- 4. Re-delivery moves no money. ---
r = await c.post(url, json=PAYLOAD)
body = r.json()
check(f"redelivery: the identical payload answers already_credited (got {body})",
r.status_code == 200 and body.get("status") == "already_credited"
and body.get("credits_added") == 0.0)
check("redelivery: the balance is unchanged",
m.get_credit_balance(MEMBER_EMAIL) == 50.0)
# --- 5. TRANSPORT: retry-once, then raise. ---
calls = []
class FlakyClient:
def __init__(self, fail_times):
self.fail_times = fail_times
async def post(self, *a, **k):
calls.append(1)
if len(calls) <= self.fail_times:
raise httpx.ReadTimeout("simulated timeout")
return "RESPONSE"
sentinel = await m._oc_graphql_post(FlakyClient(1), {"query": "x"})
check(f"transport: one transient failure is retried and succeeds (got {sentinel!r})",
sentinel == "RESPONSE" and len(calls) == 2)
calls.clear()
err = None
try:
await m._oc_graphql_post(FlakyClient(2), {"query": "x"})
except Exception as e: # noqa: BLE001
err = e
check("transport: a persistent failure still RAISES to the caller",
isinstance(err, httpx.ReadTimeout))
# --- 6. The client used for the member walk has a real timeout. ---
src = open(os.path.join(os.path.dirname(os.path.dirname(
os.path.abspath(__file__))), "app", "main.py"), encoding="utf-8").read()
check("timeout: fetch_all_member_nodes does NOT use httpx's 5s default",
"async with httpx.AsyncClient(timeout=30.0) as client:" in src)
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)