/healthz runs the full status() scan in the event loop and fails its 1 s probe on a large mirror #90

Closed
opened 2026-11-01 06:21:59 +00:00 by svc-agent-writer · 3 comments

Problem

/healthz is the liveness and readiness probe in the k8s base, with the default 1 s timeout. It calls _current_lag(), which calls store.status(). That method runs seven queries under the store lock, synchronously, inside the event loop:

  • messages LEFT JOIN embeddings GROUP BY account, a full scan.
  • attachment_text JOIN messages, new in 0.6.0.
  • messages WHERE has_attachments = 1 AND NOT EXISTS (attachment_text …), new in 0.6.0.
  • Four smaller queries on mailboxes, sync_log and changes.

The probe needs only last_ok_sync, which is one sync_log aggregate.

Evidence (2026-11-01)

  • A large instance mirrors an IMAP account and runs a JMAP backfill. The mirror is 2.08 GB with a 0.99 GB WAL. /healthz took more than 60 s, measured in-pod. Liveness killed the api 31 times on 0.5.0 over about 5 h, and kept killing it on 0.6.0. The instance served nothing during that time.
  • A small instance has a 619 MB mirror, a 170 MB WAL and no backfill. /healthz takes about 0.55 s, already more than half the probe timeout.
  • While the api waits, the sync container is at about 1 CPU embedding. One 32-message embed batch took 44 s, where 6.5 s is normal.

The estate works around this with TCP probes on the large instance. The small instance keeps the HTTP probes.

Asks

  1. /healthz reads only what it reports: one SELECT account, MAX(finished) FROM sync_log WHERE error IS NULL GROUP BY account, or an in-memory value. It must not call status().
  2. Run the remaining status() work off the event loop, for example with anyio.to_thread, so a slow mail_status cannot stall other requests on the same api process.
  3. Moved to #91: why the WAL grows during a backfill.
  4. Consider an index or a counter for the per-account aggregates in status(), so mail_status stays cheap as a mirror grows.

Acceptance

  • /healthz returns in under 100 ms on a 2 GB mirror while a backfill writes.
  • A regression test shows /healthz does not touch messages, embeddings or attachment_text.
## Problem `/healthz` is the liveness and readiness probe in the k8s base, with the default 1 s timeout. It calls `_current_lag()`, which calls `store.status()`. That method runs seven queries under the store lock, synchronously, inside the event loop: - `messages LEFT JOIN embeddings GROUP BY account`, a full scan. - `attachment_text JOIN messages`, new in 0.6.0. - `messages WHERE has_attachments = 1 AND NOT EXISTS (attachment_text …)`, new in 0.6.0. - Four smaller queries on `mailboxes`, `sync_log` and `changes`. The probe needs only `last_ok_sync`, which is one `sync_log` aggregate. ## Evidence (2026-11-01) - A large instance mirrors an IMAP account and runs a JMAP backfill. The mirror is 2.08 GB with a 0.99 GB WAL. `/healthz` took more than 60 s, measured in-pod. Liveness killed the api 31 times on 0.5.0 over about 5 h, and kept killing it on 0.6.0. The instance served nothing during that time. - A small instance has a 619 MB mirror, a 170 MB WAL and no backfill. `/healthz` takes about 0.55 s, already more than half the probe timeout. - While the api waits, the `sync` container is at about 1 CPU embedding. One 32-message embed batch took 44 s, where 6.5 s is normal. The estate works around this with TCP probes on the large instance. The small instance keeps the HTTP probes. ## Asks 1. `/healthz` reads only what it reports: one `SELECT account, MAX(finished) FROM sync_log WHERE error IS NULL GROUP BY account`, or an in-memory value. It must not call `status()`. 2. Run the remaining `status()` work off the event loop, for example with `anyio.to_thread`, so a slow `mail_status` cannot stall other requests on the same api process. 3. Moved to #91: why the WAL grows during a backfill. 4. Consider an index or a counter for the per-account aggregates in `status()`, so `mail_status` stays cheap as a mirror grows. ## Acceptance - `/healthz` returns in under 100 ms on a 2 GB mirror while a backfill writes. - A regression test shows `/healthz` does not touch `messages`, `embeddings` or `attachment_text`.
Author
Member

This was generated by AI during triage.

Agent Brief

Category: bug
Summary: /healthz and /healthz/sync read only the last successful sync per account, off the event loop, and never call Store.status().

Scope after the split (operator, 2026-11-01). This issue holds asks 1 and 2. Ask 3, the WAL growth, is #91. Ask 4 is out of scope here; see below.

Verified at triage:

  • healthz and healthz_sync are async def and call _current_lag(), which calls the synchronous Store.status() (server.py:951-967). That runs seven queries under the reader's one RLock (store.py:422, store.py:1609-1640), inside the event loop.
  • On a synthetic store of 200k messages (845 MB, warm cache, no writer), status() took a median of 239 ms. The sync_log aggregate alone took under 0.1 ms.
  • FastMCP 3.4.11 already runs sync tools in a thread pool (fastmcp/tools/function_tool.py:457). So mail_status does not block the event loop. It does hold the store lock, so other tools' reads wait behind it. Ask 2 in the body reads as: keep the health routes off the loop and off status().

Already decided (keep it):

  • /healthz reports the lag and does not judge it. A stale mirror is still worth reading (server.py:958-959).
  • Health output carries no account ids, addresses or counts (server.py:926). The response bodies stay exactly as today: ok lag_seconds=N, and for /healthz/sync, ok|stale lag_seconds=N max_lag_seconds=M with 200 or 503.

Current behavior: each probe runs the full status() scan of messages, embeddings and attachment_text in the event loop. On a large mirror during a backfill, the probe passed its 1 s timeout, and liveness restarted the api again and again.

Desired behavior:

  • A new Store.last_ok_sync() -> dict[str, str] runs only SELECT account, MAX(finished) AS finished FROM sync_log WHERE error IS NULL GROUP BY account, under the lock as other readers do. status() reuses it for its last_ok_sync key, so the query is spelled once.
  • _current_lag() calls last_ok_sync(), not status().
  • Both health routes run the lag read in a worker thread (anyio.to_thread.run_sync, or FastMCP's call_sync_fn_in_threadpool), so the event loop never runs a store query.
  • mail_status is unchanged.

Key interfaces:

  • Store.last_ok_sync() (new), Store.status() (reuses it).
  • server._current_lag(), healthz, healthz_sync.
  • sync_lag_seconds() is unchanged; its tests stay as they are.

Acceptance criteria:

  • A regression test proves the health routes touch no table except sync_log. One way: sqlite3.Connection.set_authorizer or set_trace_callback on the reader's connection during a /healthz and a /healthz/sync request. The test fails if any statement reads messages, embeddings or attachment_text.
  • A test proves the health routes do not run the store query on the event-loop thread, for example by recording threading.get_ident() inside last_ok_sync and comparing it with the loop's thread.
  • tests/test_server.py::test_health_routes_need_no_token_and_carry_no_mail_data and test_health_sync_answers_503_when_an_account_never_synced pass unchanged. The second one monkeypatches _current_lag, so keep that name.
  • On a synthetic store of 200k messages, /healthz answers in under 100 ms. Record the number in the PR.
  • make check passes.

Out of scope:

  • The WAL growth during a backfill: #91.
  • Making mail_status itself cheaper (ask 4). The options are a covering index, a short TTL cache in the api, or trigger-kept counters, which need a schema v8 step. That is a later decision.
  • The k8s probe settings. The base keeps HTTP probes on /healthz.
> *This was generated by AI during triage.* ## Agent Brief **Category:** bug **Summary:** `/healthz` and `/healthz/sync` read only the last successful sync per account, off the event loop, and never call `Store.status()`. **Scope after the split (operator, 2026-11-01).** This issue holds asks 1 and 2. Ask 3, the WAL growth, is #91. Ask 4 is out of scope here; see below. **Verified at triage:** - `healthz` and `healthz_sync` are `async def` and call `_current_lag()`, which calls the synchronous `Store.status()` (`server.py:951-967`). That runs seven queries under the reader's one `RLock` (`store.py:422`, `store.py:1609-1640`), inside the event loop. - On a synthetic store of 200k messages (845 MB, warm cache, no writer), `status()` took a median of 239 ms. The `sync_log` aggregate alone took under 0.1 ms. - FastMCP 3.4.11 already runs sync tools in a thread pool (`fastmcp/tools/function_tool.py:457`). So `mail_status` does not block the event loop. It does hold the store lock, so other tools' reads wait behind it. Ask 2 in the body reads as: keep the health routes off the loop and off `status()`. **Already decided (keep it):** - `/healthz` reports the lag and does not judge it. A stale mirror is still worth reading (`server.py:958-959`). - Health output carries no account ids, addresses or counts (`server.py:926`). The response bodies stay exactly as today: `ok lag_seconds=N`, and for `/healthz/sync`, `ok|stale lag_seconds=N max_lag_seconds=M` with 200 or 503. **Current behavior:** each probe runs the full `status()` scan of `messages`, `embeddings` and `attachment_text` in the event loop. On a large mirror during a backfill, the probe passed its 1 s timeout, and liveness restarted the api again and again. **Desired behavior:** - A new `Store.last_ok_sync() -> dict[str, str]` runs only `SELECT account, MAX(finished) AS finished FROM sync_log WHERE error IS NULL GROUP BY account`, under the lock as other readers do. `status()` reuses it for its `last_ok_sync` key, so the query is spelled once. - `_current_lag()` calls `last_ok_sync()`, not `status()`. - Both health routes run the lag read in a worker thread (`anyio.to_thread.run_sync`, or FastMCP's `call_sync_fn_in_threadpool`), so the event loop never runs a store query. - `mail_status` is unchanged. **Key interfaces:** - `Store.last_ok_sync()` (new), `Store.status()` (reuses it). - `server._current_lag()`, `healthz`, `healthz_sync`. - `sync_lag_seconds()` is unchanged; its tests stay as they are. **Acceptance criteria:** - [ ] A regression test proves the health routes touch no table except `sync_log`. One way: `sqlite3.Connection.set_authorizer` or `set_trace_callback` on the reader's connection during a `/healthz` and a `/healthz/sync` request. The test fails if any statement reads `messages`, `embeddings` or `attachment_text`. - [ ] A test proves the health routes do not run the store query on the event-loop thread, for example by recording `threading.get_ident()` inside `last_ok_sync` and comparing it with the loop's thread. - [ ] `tests/test_server.py::test_health_routes_need_no_token_and_carry_no_mail_data` and `test_health_sync_answers_503_when_an_account_never_synced` pass unchanged. The second one monkeypatches `_current_lag`, so keep that name. - [ ] On a synthetic store of 200k messages, `/healthz` answers in under 100 ms. Record the number in the PR. - [ ] `make check` passes. **Out of scope:** - The WAL growth during a backfill: #91. - Making `mail_status` itself cheaper (ask 4). The options are a covering index, a short TTL cache in the api, or trigger-kept counters, which need a schema v8 step. That is a later decision. - The k8s probe settings. The base keeps HTTP probes on `/healthz`.
Collaborator

⏸ SVD architect gate: dev/imap-mailmind-mcp#90 healthz-runs-the-full-status-scan-in-the-event-loop-and-fail

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 standard · dispatch effort medium

Run: 20261101T074016Z-a3a1d3cb

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

Open risks:

  1. Should the health read avoid Store._lock? The brief says last_ok_sync runs 'under the lock as other readers do', and the spec follows that. But status() holds the same RLock for its whole seven-query scan: 239 ms at 200k messages, and over 60 s on the large instance. A /healthz that arrives during a mail_status call still waits in its worker thread and can still pass the 1 s probe. Accept this for #90 and track the contention under ask 4? Or give last_ok_sync its own short-lived read-only connection without the lock, which changes the brief's scope? Recommendation: accept as written and file the contention against ask 4. [decision]
  2. The body's criterion, '/healthz < 100 ms on a 2 GB mirror while a backfill writes', can only be proven live. After deploy on the large instance, run in-pod for i in $(seq 20); do curl -s -o /dev/null -w '%{time_total}\n' -H 'Host: localhost' http://127.0.0.1:8420/healthz; done and expect every sample under 0.1 s while no mail_status call is running. Switching that instance back from TCP to HTTP probes is estate work and out of scope. [verification]
  3. The 200k-message synthetic /healthz timing (brief criterion: under 100 ms) was not measured at spec time. Dispatch must build the store in a scratch script, time 20 GETs and record the median and max in the PR. If the environment cannot build 200k rows, the PR must state the size it did measure. [verification]

Change: Add Store.last_ok_sync() -> dict[str, str] directly above status() (store.py:1735). Model it on the single-query readers at store.py:1668-1684: take with self._lock:, run only SELECT account, MAX(finished) AS finished FROM sync_log WHERE error IS NULL GROUP BY account, and build the dict outside the lock. Inside status()'s lock block, replace the last_runs query (store.py:1743-1745) with last_ok = self.last_ok_sync(); the RLock makes this re-entry safe. Leave every other status() key unchanged. In server.py, import starlette.concurrency.run_in_threadpool, which is already a direct starlette dependency, so nothing is added. Change _current_lag (server.py:1004-1006) to call s.store.last_ok_sync() instead of status(). In healthz and healthz_sync (server.py:1009-1023), call await run_in_threadpool(_current_lag) inside the coroutine body. Keep the module-global lookup there so the existing monkeypatch of _current_lag still applies. Response bodies and status codes do not change.

Files: src/imap_mailmind_mcp/store.py · src/imap_mailmind_mcp/server.py · tests/test_store.py · tests/test_server.py

Decision: accept the 3 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-01-healthz-runs-the-full-status-scan-in-the-event-loop-and-fail.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-01-healthz-runs-the-full-status-scan-in-the-event-loop-and-fail.md

### ⏸ SVD architect gate: dev/imap-mailmind-mcp#90 healthz-runs-the-full-status-scan-in-the-event-loop-and-fail **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 `standard` · dispatch effort `medium` **Run:** `20261101T074016Z-a3a1d3cb` **Held because:** CLEAN but 3 open risk(s) (2 verification · 1 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. Should the health read avoid Store._lock? The brief says last_ok_sync runs 'under the lock as other readers do', and the spec follows that. But status() holds the same RLock for its whole seven-query scan: 239 ms at 200k messages, and over 60 s on the large instance. A /healthz that arrives during a mail_status call still waits in its worker thread and can still pass the 1 s probe. Accept this for #90 and track the contention under ask 4? Or give last_ok_sync its own short-lived read-only connection without the lock, which changes the brief's scope? Recommendation: accept as written and file the contention against ask 4. [decision] 2. The body's criterion, '/healthz < 100 ms on a 2 GB mirror while a backfill writes', can only be proven live. After deploy on the large instance, run in-pod `for i in $(seq 20); do curl -s -o /dev/null -w '%{time_total}\n' -H 'Host: localhost' http://127.0.0.1:8420/healthz; done` and expect every sample under 0.1 s while no mail_status call is running. Switching that instance back from TCP to HTTP probes is estate work and out of scope. [verification] 3. The 200k-message synthetic /healthz timing (brief criterion: under 100 ms) was not measured at spec time. Dispatch must build the store in a scratch script, time 20 GETs and record the median and max in the PR. If the environment cannot build 200k rows, the PR must state the size it did measure. [verification] **Change:** Add Store.last_ok_sync() -> dict[str, str] directly above status() (store.py:1735). Model it on the single-query readers at store.py:1668-1684: take `with self._lock:`, run only `SELECT account, MAX(finished) AS finished FROM sync_log WHERE error IS NULL GROUP BY account`, and build the dict outside the lock. Inside status()'s lock block, replace the last_runs query (store.py:1743-1745) with `last_ok = self.last_ok_sync()`; the RLock makes this re-entry safe. Leave every other status() key unchanged. In server.py, import starlette.concurrency.run_in_threadpool, which is already a direct starlette dependency, so nothing is added. Change _current_lag (server.py:1004-1006) to call s.store.last_ok_sync() instead of status(). In healthz and healthz_sync (server.py:1009-1023), call `await run_in_threadpool(_current_lag)` inside the coroutine body. Keep the module-global lookup there so the existing monkeypatch of _current_lag still applies. Response bodies and status codes do not change. **Files:** `src/imap_mailmind_mcp/store.py` · `src/imap_mailmind_mcp/server.py` · `tests/test_store.py` · `tests/test_server.py` **Decision:** accept the 3 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-01-healthz-runs-the-full-status-scan-in-the-event-loop-and-fail.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-01-healthz-runs-the-full-status-scan-in-the-event-loop-and-fail.md`</sub>
Collaborator

spec-verify-dispatch Half B for dev/imap-mailmind-mcp#90 healthz-runs-the-full-status-scan-in-the-event-loop-and-fail completed integration verify.

  • PR: dev/imap-mailmind-mcp#95
  • Branch: feat/svd-dev-imap-mailmind-mcp-90-healthz-runs-the-full-statu-5ee6851d
  • Commit: fd0e51e4b5
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: True
  • Check commit statuses on PR head: absent
  • Checks: PR #95 @ fd0e51e: no Forgejo commit statuses (absent, no CI in repo). Local: ruff clean, mypy strict clean on src, 342 passed, 4 skipped. Ready for merge; not merged.
  • Warning: No remote CI statuses exist on the PR head; the verdict rests on local runs only.
  • Warning: Bare python3 -m pytest cannot import the package (no install). I ran collection and tests through uv run python -m pytest instead.
  • Warning: The PR commit trailer reads Co-Authored-By: gpt-6.1-sol, not the standard trailer. Not a code defect.
  • Warning: Spec Open Risk 2 (live check of 20 in-pod GETs on the large instance) remains a post-deploy verification, outside this unit.
  • Warning: no CI for commit statuses on PR head: Forgejo returned no commit statuses for fd0e51e; the repo has no .woodpecker CI (CLAUDE.md: CI files are added by the architect). — reported as absent, not blocking (gh#633)
  • Decision: review the PR and merge? (codex-svd ship --run-id 20261101T075718Z-5ee6851d --confirm-merge)
spec-verify-dispatch Half B for dev/imap-mailmind-mcp#90 healthz-runs-the-full-status-scan-in-the-event-loop-and-fail completed integration verify. - PR: https://git.groupthink.asia/dev/imap-mailmind-mcp/pulls/95 - Branch: feat/svd-dev-imap-mailmind-mcp-90-healthz-runs-the-full-statu-5ee6851d - Commit: fd0e51e4b56b805a03d450652deed2a83ec682f3 - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: True - Check commit statuses on PR head: absent - Checks: PR #95 @ fd0e51e: no Forgejo commit statuses (absent, no CI in repo). Local: ruff clean, mypy strict clean on src, 342 passed, 4 skipped. Ready for merge; not merged. - Warning: No remote CI statuses exist on the PR head; the verdict rests on local runs only. - Warning: Bare python3 -m pytest cannot import the package (no install). I ran collection and tests through uv run python -m pytest instead. - Warning: The PR commit trailer reads Co-Authored-By: gpt-6.1-sol, not the standard trailer. Not a code defect. - Warning: Spec Open Risk 2 (live check of 20 in-pod GETs on the large instance) remains a post-deploy verification, outside this unit. - Warning: no CI for commit statuses on PR head: Forgejo returned no commit statuses for fd0e51e; the repo has no .woodpecker CI (CLAUDE.md: CI files are added by the architect). — reported as absent, not blocking (gh#633) - Decision: review the PR and merge? (`codex-svd ship --run-id 20261101T075718Z-5ee6851d --confirm-merge`)
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/mail-mind-mcp#90
No description provided.