Pace the mailmind client: 20 pages in 0.58 s trip mailmind's rate limit, read as mailmind-auth #35

Closed
opened 2026-11-02 02:09:08 +00:00 by piers · 4 comments
Owner

Problem

On the live gate instance the mailmind Source fails every pass with code=mailmind-auth, although the evidence token is valid: a hand-made tools/list and mail_changes call with the same token answer 200, and the token file hashes match on both pods.

Traced inside the sync container with the app's own MailmindSource._fetch (statuses only):

  • the client issued 20 mail_changes pages in 0.58 s (about 34 requests per second), then the next request answered 401 and _fetch raised mailmind-auth;
  • mailmind's verifier is a token bucket per token (rate_per_second = 5.0, rate_burst = 20 on this instance, which are the defaults); when the bucket is empty verify_token returns None, so FastMCP answers 401 invalid_token.

A first full pass over a real mailbox needs many mail_changes pages (30:PAGE_LIMIT = 100) and then one mail_evidence call per distinct correspondent, so without pacing it can never finish. Every pass restarts from the same cursor because self.state is only written after success, so the instance never catches up.

Fix

In MailmindSource._fetch:

  1. Pace the calls: a client-side limiter below the server's default (4 requests per second, burst 10), configurable on MailmindSourceConfig (rate_per_second, default 4.0).
  2. Retry on a rate-limit answer with backoff: honour Retry-After on 429; also treat a 401 that follows at least one successful authenticated call in the same session as a rate limit (mailmind today answers 401 for an empty bucket; dev/mail-mind-mcp has the sibling issue to answer 429), retry up to 5 times with exponential backoff from 0.5 s. A 401 on the first call stays mailmind-auth.
  3. Persist progress: advance self.state["cursor"] after each accepted mail_changes page so a pass that fails midway resumes rather than restarts. Evidence calls remain per address and are retried under the same rules.

Acceptance

  • A unit test with a fake server that answers 401 after N calls shows the pass completes with backoff and that the first-call 401 still raises mailmind-auth.
  • A unit test asserts the limiter keeps the request rate at or below the configured value over a page burst.
  • A unit test shows the cursor advances per page and a resumed pass does not refetch accepted pages.
  • Live on the gate instance: source=mail kind=mailmind status=ok with non-zero fetched (recorded on #10).

Primary files

  • src/people_mind_mcp/sources/mailmind.py
  • src/people_mind_mcp/config.py (MailmindSourceConfig.rate_per_second)
  • tests/test_mailmind.py

Blocked by

None. Independent of #34 (different file).

## Problem On the live gate instance the mailmind Source fails every pass with `code=mailmind-auth`, although the evidence token is valid: a hand-made `tools/list` and `mail_changes` call with the same token answer 200, and the token file hashes match on both pods. Traced inside the sync container with the app's own `MailmindSource._fetch` (statuses only): - the client issued 20 `mail_changes` pages in 0.58 s (about 34 requests per second), then the next request answered 401 and `_fetch` raised `mailmind-auth`; - mailmind's verifier is a token bucket per token (`rate_per_second = 5.0`, `rate_burst = 20` on this instance, which are the defaults); when the bucket is empty `verify_token` returns `None`, so FastMCP answers `401 invalid_token`. A first full pass over a real mailbox needs many `mail_changes` pages (`30:PAGE_LIMIT = 100`) and then one `mail_evidence` call per distinct correspondent, so without pacing it can never finish. Every pass restarts from the same cursor because `self.state` is only written after success, so the instance never catches up. ## Fix In `MailmindSource._fetch`: 1. Pace the calls: a client-side limiter below the server's default (4 requests per second, burst 10), configurable on `MailmindSourceConfig` (`rate_per_second`, default 4.0). 2. Retry on a rate-limit answer with backoff: honour `Retry-After` on 429; also treat a 401 that follows at least one successful authenticated call in the same session as a rate limit (mailmind today answers 401 for an empty bucket; dev/mail-mind-mcp has the sibling issue to answer 429), retry up to 5 times with exponential backoff from 0.5 s. A 401 on the first call stays `mailmind-auth`. 3. Persist progress: advance `self.state["cursor"]` after each accepted `mail_changes` page so a pass that fails midway resumes rather than restarts. Evidence calls remain per address and are retried under the same rules. ## Acceptance - A unit test with a fake server that answers 401 after N calls shows the pass completes with backoff and that the first-call 401 still raises `mailmind-auth`. - A unit test asserts the limiter keeps the request rate at or below the configured value over a page burst. - A unit test shows the cursor advances per page and a resumed pass does not refetch accepted pages. - Live on the gate instance: `source=mail kind=mailmind status=ok` with non-zero `fetched` (recorded on #10). ## Primary files - `src/people_mind_mcp/sources/mailmind.py` - `src/people_mind_mcp/config.py` (`MailmindSourceConfig.rate_per_second`) - `tests/test_mailmind.py` ## Blocked by None. Independent of #34 (different file).
Author
Owner

Sibling on the server side: dev/mail-mind-mcp#126 (answer 429 with Retry-After instead of 401 invalid_token). This client fix does not wait for it; the 401-after-success rule covers today's server.

Sibling on the server side: dev/mail-mind-mcp#126 (answer 429 with Retry-After instead of 401 invalid_token). This client fix does not wait for it; the 401-after-success rule covers today's server.
Collaborator

⏸ SVD architect gate: dev/people-mind-mcp#35 pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s

Status: CLEAN after 0 rework round(s) · 0 blocking defect(s) · 0 lens(es) INCONCLUSIVE (could not run) · 0 lens(es) DEGRADED (deterministic denial) · complexity substrate · dispatch effort high

Run: 20261102T022451Z-fdf8516c

Held because: CLEAN but 5 open risk(s) (3 verification · 2 decision) — HOLD-ALL parks everything. The risks, verbatim:

Open risks:

  1. D1: Fix 3 as worded (move self.state['cursor'] forward per page) is thrown away on failure, because sync.run_pass saves state only on success (sync.py:30-49). Saving only the cursor would lose the accepted pages' interactions. Question: accept the checkpoint lean (cursor plus pending interactions, saved by a guarded, opt-in run_pass failure-path write, which adds sync.py beyond the issue's file list)? Or cut fix 3 back to in-pass resume only (no sync.py change) and file cross-pass resume separately? [decision]
  2. D2: Exhausted retries reuse the existing codes (401 gives mailmind-auth, 429 gives mailmind-unavailable). Question: is that acceptable, or should a distinct mailmind-rate-limited code be added so people_sources tells a throttled pass from a revoked token? [decision]
  3. V1: Live acceptance after merge and deploy on the gate instance. The latest sync line must read source=mail kind=mailmind with no error and fetched>0, and SELECT error FROM sync_log WHERE source='mail' ORDER BY finished DESC LIMIT 1 must return NULL. Record it on #10. [verification]
  4. V2: Checkpoint size. After any interrupted pass on the gate instance, check SELECT length(state) FROM source_state WHERE source='mail'. If it is tens of MB, trim or batch the pending set. [verification]
  5. V3: The lean assumes a mid-session 401/429 surfaces from async with Client(...) as a bare httpx.HTTPStatusError. The live trace supports this, since it produced mailmind-auth rather than mailmind-unavailable. Test 2 on the local serve() stack must prove it. If fastmcp 3.4.11 wraps it in an ExceptionGroup, _retry_delay must unwrap it. [verification]

Change: Add MailmindSourceConfig.rate_per_second (Field(default=4.0, gt=0), mirroring ApiConfig.rate_per_second at config.py:83). In mailmind.py, add an async _Pacer token bucket (burst constant RATE_BURST=10) that mirrors the refill math of RateLimiter.allow at auth.py:77-90 but waits instead of refusing, with module-level _clock/_sleep so tests can drive virtual time. Acquire a token before every call_tool and before every Client open. Wrap _fetch's async with Client(...) in an attempt loop that keeps cursor, pending interactions and finished evidence records across attempts, because a 401 or 429 tears down the MCP session (mcp streamable_http _handle_post_request runs raise_for_status inside a task-group child), so each retry opens a new Client. _retry_delay rules: on a 429, wait for Retry-After as delta-seconds, capped at 60 s, falling back to 0.52^n; treat a 401 after at least one successful _call in this pass as a rate limit with 0.52^n backoff; a first-call 401 or a 403 gives mailmind-auth; allow 5 retries per request, with the counter reset on each success. Cross-pass resume: MailmindSource.resumable=True; after each accepted page, self.state={cursor, pending, full?}; on success, self.state={cursor} only. sync.run_pass's failure transaction (sync.py:59-76) saves source.state only when records() itself raised (fetched_ok guard), the source is resumable, and the state differs from what was loaded, so a rolled-back ingest never saves a cursor that has run ahead of the interactions. Architect decision D1: confirm the sync.py extension, or cut back to in-pass resume.

Files: src/people_mind_mcp/sources/mailmind.py · src/people_mind_mcp/config.py · src/people_mind_mcp/sync.py · tests/test_mailmind.py

Decision: accept the 5 open risk(s) above and dispatch this spec (svd:go), or park (svd:skip) / re-spec (svd:respec)?

Your call (when this issue is held at the gate via svd:hold):

  • add label svd:go — approve; Half-B dispatch accepts exactly this spec (open risks accepted)
  • add label svd:fire beside svd:go — approve AND authorise the Half-B fire from the phone; never on its own
  • add label svd:skip — park it; dispatch refuses it and the issue stays for a human
  • add label svd:respec — discard this spec; the next Half-A run re-produces it with this record as prior-attempt context

Spec: /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s.md

### ⏸ SVD architect gate: dev/people-mind-mcp#35 pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s **Status:** CLEAN after 0 rework round(s) · 0 blocking defect(s) · 0 lens(es) INCONCLUSIVE (could not run) · 0 lens(es) DEGRADED (deterministic denial) · complexity `substrate` · dispatch effort `high` **Run:** `20261102T022451Z-fdf8516c` **Held because:** CLEAN but 5 open risk(s) (3 verification · 2 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. D1: Fix 3 as worded (move self.state['cursor'] forward per page) is thrown away on failure, because sync.run_pass saves state only on success (sync.py:30-49). Saving only the cursor would lose the accepted pages' interactions. Question: accept the checkpoint lean (cursor plus pending interactions, saved by a guarded, opt-in run_pass failure-path write, which adds sync.py beyond the issue's file list)? Or cut fix 3 back to in-pass resume only (no sync.py change) and file cross-pass resume separately? [decision] 2. D2: Exhausted retries reuse the existing codes (401 gives mailmind-auth, 429 gives mailmind-unavailable). Question: is that acceptable, or should a distinct mailmind-rate-limited code be added so people_sources tells a throttled pass from a revoked token? [decision] 3. V1: Live acceptance after merge and deploy on the gate instance. The latest sync line must read source=mail kind=mailmind with no error and fetched>0, and `SELECT error FROM sync_log WHERE source='mail' ORDER BY finished DESC LIMIT 1` must return NULL. Record it on #10. [verification] 4. V2: Checkpoint size. After any interrupted pass on the gate instance, check `SELECT length(state) FROM source_state WHERE source='mail'`. If it is tens of MB, trim or batch the pending set. [verification] 5. V3: The lean assumes a mid-session 401/429 surfaces from `async with Client(...)` as a bare httpx.HTTPStatusError. The live trace supports this, since it produced mailmind-auth rather than mailmind-unavailable. Test 2 on the local serve() stack must prove it. If fastmcp 3.4.11 wraps it in an ExceptionGroup, _retry_delay must unwrap it. [verification] **Change:** Add MailmindSourceConfig.rate_per_second (Field(default=4.0, gt=0), mirroring ApiConfig.rate_per_second at config.py:83). In mailmind.py, add an async _Pacer token bucket (burst constant RATE_BURST=10) that mirrors the refill math of RateLimiter.allow at auth.py:77-90 but waits instead of refusing, with module-level _clock/_sleep so tests can drive virtual time. Acquire a token before every call_tool and before every Client open. Wrap _fetch's `async with Client(...)` in an attempt loop that keeps cursor, pending interactions and finished evidence records across attempts, because a 401 or 429 tears down the MCP session (mcp streamable_http _handle_post_request runs raise_for_status inside a task-group child), so each retry opens a new Client. _retry_delay rules: on a 429, wait for Retry-After as delta-seconds, capped at 60 s, falling back to 0.5*2^n; treat a 401 after at least one successful _call in this pass as a rate limit with 0.5*2^n backoff; a first-call 401 or a 403 gives mailmind-auth; allow 5 retries per request, with the counter reset on each success. Cross-pass resume: MailmindSource.resumable=True; after each accepted page, self.state={cursor, pending, full?}; on success, self.state={cursor} only. sync.run_pass's failure transaction (sync.py:59-76) saves source.state only when records() itself raised (fetched_ok guard), the source is resumable, and the state differs from what was loaded, so a rolled-back ingest never saves a cursor that has run ahead of the interactions. Architect decision D1: confirm the sync.py extension, or cut back to in-pass resume. **Files:** `src/people_mind_mcp/sources/mailmind.py` · `src/people_mind_mcp/config.py` · `src/people_mind_mcp/sync.py` · `tests/test_mailmind.py` **Decision:** accept the 5 open risk(s) above and dispatch this spec (`svd:go`), or park (`svd:skip`) / re-spec (`svd:respec`)? **Your call** (when this issue is held at the gate via `svd:hold`): - add label `svd:go` — approve; Half-B dispatch accepts exactly this spec (open risks accepted) - add label `svd:fire` **beside** `svd:go` — approve AND authorise the Half-B fire from the phone; never on its own - add label `svd:skip` — park it; dispatch refuses it and the issue stays for a human - add label `svd:respec` — discard this spec; the next Half-A run re-produces it with this record as prior-attempt context <sub>Spec: `/Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s.md`</sub>
Author
Owner

Architect gate (Half-A CLEAN)

Spec: specs/2026-11-02-pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s.md (exhaust worktree, gate adjustments appended).

D1 ruled: in-pass resume only. sync.py leaves the write set; the resumable attribute, the failure-path state write and the two checkpoint tests are dropped. Within one pass the cursor and pending interactions survive rate-limit retries, so a retried pass never refetches an accepted page. Persisted state shape unchanged. Cross-pass checkpointing is #36 (needs-triage) with the spec's worked design.

D2 ruled: no new error code. Exhausted retries keep mailmind-auth (401) and mailmind-unavailable (429). dev/mail-mind-mcp#126 makes throttling an explicit 429 server-side.

Kept from the lean: rate_per_second default 4.0, RATE_BURST 10, MAX_RETRIES 5, BACKOFF_BASE 0.5, RETRY_AFTER_MAX 60, async pacer, attempt loop reopening the client on HTTPStatusError, first-call 401/403 stays mailmind-auth. V3 (ExceptionGroup unwrap on the local serve() stack) is a dispatch obligation.

Host baseline at 2224edd: neighbours (test_mailmind test_config_cli test_carddav test_vcard_sync) 143 passed.

Riders: basetemp on every pytest command, python3 -m pytest, no nested .git, no .agents/.codex/.git paths written.

Operator: paste svd:go to release Half-B (batched with #34).

## Architect gate (Half-A CLEAN) Spec: `specs/2026-11-02-pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s.md` (exhaust worktree, gate adjustments appended). **D1 ruled: in-pass resume only.** `sync.py` leaves the write set; the `resumable` attribute, the failure-path state write and the two checkpoint tests are dropped. Within one pass the cursor and pending interactions survive rate-limit retries, so a retried pass never refetches an accepted page. Persisted state shape unchanged. Cross-pass checkpointing is #36 (needs-triage) with the spec's worked design. **D2 ruled: no new error code.** Exhausted retries keep `mailmind-auth` (401) and `mailmind-unavailable` (429). dev/mail-mind-mcp#126 makes throttling an explicit 429 server-side. **Kept from the lean:** `rate_per_second` default 4.0, `RATE_BURST` 10, `MAX_RETRIES` 5, `BACKOFF_BASE` 0.5, `RETRY_AFTER_MAX` 60, async pacer, attempt loop reopening the client on `HTTPStatusError`, first-call 401/403 stays `mailmind-auth`. V3 (ExceptionGroup unwrap on the local `serve()` stack) is a dispatch obligation. **Host baseline at 2224edd:** neighbours (`test_mailmind test_config_cli test_carddav test_vcard_sync`) 143 passed. **Riders:** basetemp on every pytest command, `python3 -m pytest`, no nested `.git`, no `.agents`/`.codex`/`.git` paths written. Operator: paste `svd:go` to release Half-B (batched with #34).
Collaborator

spec-verify-dispatch Half B for dev/people-mind-mcp#35 pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s completed integration verify.

  • PR: #38
  • Branch: feat/svd-dev-people-mind-mcp-35-pace-the-mailmind-client-20-p-3cf65163
  • Commit: c27d5f6bcb
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: True
  • Checks: PR #38 head c27d5f6: no remote checks reported (absent CI). Local full suite: 288 passed, 9 skipped. No blockers.
  • Warning: No remote CI: the Forgejo commit statuses endpoint for c27d5f6 returns an empty list, so no required checks exist.
  • Warning: Worktree has no venv. The system python lacks phonenumbers, so tests ran with the main checkout's .venv interpreter and PYTHONPATH=src to load the worktree sources.
  • Warning: Subagent deviation: the cross-pass checkpoint design supersedes Agent Adjustments D1's in-pass-only ruling. Deferred issue #36 needs architect reconciliation.
  • Warning: Live gate check (mailmind status=ok with non-zero fetched, recorded on #10) is post-merge and was not performed.
  • Rework: 1 round(s), outcome converged
  • Decision: review the PR and merge? (codex-svd ship --run-id 20261102T035837Z-3cf65163 --confirm-merge)
spec-verify-dispatch Half B for dev/people-mind-mcp#35 pace-the-mailmind-client-20-pages-in-0-58-s-trip-mailmind-s completed integration verify. - PR: https://git.groupthink.asia/dev/people-mind-mcp/pulls/38 - Branch: feat/svd-dev-people-mind-mcp-35-pace-the-mailmind-client-20-p-3cf65163 - Commit: c27d5f6bcb32e6bf98118bfd6bc6773ef441c779 - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: True - Checks: PR #38 head c27d5f6: no remote checks reported (absent CI). Local full suite: 288 passed, 9 skipped. No blockers. - Warning: No remote CI: the Forgejo commit statuses endpoint for c27d5f6 returns an empty list, so no required checks exist. - Warning: Worktree has no venv. The system python lacks phonenumbers, so tests ran with the main checkout's .venv interpreter and PYTHONPATH=src to load the worktree sources. - Warning: Subagent deviation: the cross-pass checkpoint design supersedes Agent Adjustments D1's in-pass-only ruling. Deferred issue #36 needs architect reconciliation. - Warning: Live gate check (mailmind status=ok with non-zero fetched, recorded on #10) is post-merge and was not performed. - Rework: 1 round(s), outcome converged - Decision: review the PR and merge? (`codex-svd ship --run-id 20261102T035837Z-3cf65163 --confirm-merge`)
piers closed this issue 2026-11-02 04:19:03 +00:00
Sign in to join this conversation.
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
dev/people-mind-mcp#35
No description provided.