mail_evidence costs about 2 s of a full core per call: the Sent query scans every Sent message with instr() #136

Closed
opened 2026-11-02 07:08:23 +00:00 by piers · 3 comments
Owner

Problem

One mail_evidence call costs about 2 seconds of a full CPU core in the api container on the live piers instance. The People Mind cold pass calls it once per Handle that is not the Owner. On the live mailbox that is 5,505 calls, so the first pass takes about 3 hours. The People Mind client pacer allows 4 calls per second and never engages.

Measurement (2026-11-02, mailmind 0.10.2 on starbase-syd, People Mind 0.1.0-rc.4)

Measurement Value
Gap between consecutive CallToolRequest lines in the api log median 1.93 s, p90 2.05 s, n=95 over 3 min
api container CPU during the pass 998m
sync container CPU at the same time 192m
People Mind sync container CPU 41m
Calls per pass on this mailbox 5,505 Handles over 152,331 events

The caller runs one MCP session and one call at a time, so the gap is the server's time per call.

Cause

Store.evidence() in src/mail_mind_mcp/store.py (0.10.2, from line 1886) runs three statements per call. Two cannot use an index:

  1. sent: FROM messages m LEFT JOIN mailboxes b ... WHERE b.role = 'sent' AND (instr(lower(m.to_addrs), ?) > 0 OR instr(lower(m.cc_addrs), ?) > 0). instr over a lowered column scans every Sent message on every call. The parsed-cell check in Python then filters the matches.
  2. by_role and newest use messages_from (account, from_addr) for the address, but the shown clause is a correlated NOT EXISTS over messages c per candidate row.

The schema has messages_from, messages_date, messages_msgid and messages_copies. It has no table or index that maps a recipient address to a message.

Options

  1. A recipients (account, address, message_id) table filled on ingest from the parsed To and Cc cells, with an index on (account, address). The sent query becomes an index lookup and the Python re-check goes away.
  2. A per-address summary table refreshed by the sync worker: received count per role, first and last dates, sent count. mail_evidence reads one row and runs only the newest query.
  3. A batch form of mail_evidence that takes up to N addresses per call. This cuts round trips but not the scan, so it is a complement, not the fix.

Acceptance

  • mail_evidence p50 under 100 ms on the live piers store with the Sent mailbox at its current size.
  • A People Mind cold pass over this mailbox completes in under 15 minutes.
  • The closed field list of ADR 0008 §2 is unchanged. No new field leaves the host.

Relation

  • dev/people-mind-mcp#36 records the client-side consequence: the Evidence phase is the unprotected 3 hour part of a cold pass.
  • dev/mail-mind-mcp#126 (429 on the server) is independent; the pacer never engages at this rate.

Filed under: operator word "accept" sha256:c125d0397b60

## Problem One `mail_evidence` call costs about 2 seconds of a full CPU core in the `api` container on the live piers instance. The People Mind cold pass calls it once per Handle that is not the Owner. On the live mailbox that is 5,505 calls, so the first pass takes about 3 hours. The People Mind client pacer allows 4 calls per second and never engages. ## Measurement (2026-11-02, mailmind 0.10.2 on starbase-syd, People Mind 0.1.0-rc.4) | Measurement | Value | |---|---| | Gap between consecutive `CallToolRequest` lines in the `api` log | median 1.93 s, p90 2.05 s, n=95 over 3 min | | `api` container CPU during the pass | 998m | | `sync` container CPU at the same time | 192m | | People Mind `sync` container CPU | 41m | | Calls per pass on this mailbox | 5,505 Handles over 152,331 events | The caller runs one MCP session and one call at a time, so the gap is the server's time per call. ## Cause `Store.evidence()` in `src/mail_mind_mcp/store.py` (0.10.2, from line 1886) runs three statements per call. Two cannot use an index: 1. `sent`: `FROM messages m LEFT JOIN mailboxes b ... WHERE b.role = 'sent' AND (instr(lower(m.to_addrs), ?) > 0 OR instr(lower(m.cc_addrs), ?) > 0)`. `instr` over a lowered column scans every Sent message on every call. The parsed-cell check in Python then filters the matches. 2. `by_role` and `newest` use `messages_from (account, from_addr)` for the address, but the `shown` clause is a correlated `NOT EXISTS` over `messages c` per candidate row. The schema has `messages_from`, `messages_date`, `messages_msgid` and `messages_copies`. It has no table or index that maps a recipient address to a message. ## Options 1. A `recipients (account, address, message_id)` table filled on ingest from the parsed To and Cc cells, with an index on `(account, address)`. The `sent` query becomes an index lookup and the Python re-check goes away. 2. A per-address summary table refreshed by the sync worker: received count per role, first and last dates, sent count. `mail_evidence` reads one row and runs only the `newest` query. 3. A batch form of `mail_evidence` that takes up to N addresses per call. This cuts round trips but not the scan, so it is a complement, not the fix. ## Acceptance - `mail_evidence` p50 under 100 ms on the live piers store with the Sent mailbox at its current size. - A People Mind cold pass over this mailbox completes in under 15 minutes. - The closed field list of ADR 0008 §2 is unchanged. No new field leaves the host. ## Relation - dev/people-mind-mcp#36 records the client-side consequence: the Evidence phase is the unprotected 3 hour part of a cold pass. - dev/mail-mind-mcp#126 (429 on the server) is independent; the pacer never engages at this rate. Filed under: operator word "accept" sha256:c125d0397b60

This was generated by AI during triage.

Agent Brief

Category: bug
Summary: The default mail_evidence call scans the whole messages table, because messages_from (account, from_addr) cannot serve a lookup with no account. Add an index that can.

Current behavior:

Verified on main at 28839b9 against a synthetic store of 180k messages (150k inbox, 30k Sent). mail_evidence passes account=None and exclude_sent=True by default (server.py:667).

  • by_role (store.py:1927) plans as SCAN m, a full table read. The messages_from index leads with account, and the query gives none.
  • newest plans as SCAN m USING INDEX messages_from, a walk of the whole index.
  • The exclude_sent subquery (_SELF_SENDERS AND s.from_addr = ?, store.py:419 and 1914) scans every Sent and Drafts row in each statement.
  • Nothing in the code runs ANALYZE, so SQLite has no statistics and no skip-scan. The live store plans the same way.

Timings (median of 5): 123 ms as is, 37 ms with exclude_sent=False, and 13 ms with one index on messages(from_addr). Live rows average about 13 KB (a 2 GB store), so each full read costs far more there. That fits the measured 2 s per call.

Correction to the issue text: the instr() sent statement is not the main cost. It reads only Sent rows through the (account, mailbox) index, 11 ms for 30k Sent rows here. #138 moves it onto a recipients table.

Desired behavior:

  • One index that serves an exact from_addr lookup with or without an account, for example messages (from_addr, account).
  • by_role, newest and the exclude_sent subquery all search that index. The mail_people and people paths keep working, and use it where the planner picks it.
  • The index lands in a schema migration in the writer. SCHEMA_VERSION goes up by one. Store(reader=True) never creates it and refuses an older schema, as today (store.py:561-568).
  • mail_evidence output is unchanged for every input (ADR 0008 §2).

Key interfaces:

  • The schema index list (store.py:112-116), SCHEMA_VERSION (store.py:31) and the migration path.
  • Store.evidence (store.py:1898): no query text change is expected. Change it only if the planner needs help, and say why in the PR.

Acceptance criteria:

  • A test runs EXPLAIN QUERY PLAN on the by_role and newest statements and the exclude_sent subquery with account=None. Each shows a SEARCH using the new index, and none shows SCAN m or SCAN s.
  • The same test with an account given still uses an index.
  • An existing v11 store opens in the writer, migrates, and has the index. A reader on an unmigrated store raises the existing clear error.
  • Every existing mail_evidence, mail_people and people test passes unchanged.
  • The PR records the median Store.evidence time before and after on a synthetic store of at least 150k messages with a Sent mailbox. The image ships SQLite 3.40.1 (#96), so run it in the image, head and base alternating in one container.
  • make check passes. Tests run as uv run python3 -m pytest.

Out of scope:

  • The recipients table and the sent statement (#138).
  • A batch form of mail_evidence, or any new field.
  • Running ANALYZE or PRAGMA optimize.

Order: #136 lands before #138 and #108, because each of them also raises SCHEMA_VERSION.

Operator check after deploy: time mail_evidence on the live piers store. The target is p50 under 100 ms, and a People Mind cold pass under 15 minutes. If the target is missed, the remaining cost is the sent scan, which #138 removes.

> *This was generated by AI during triage.* ## Agent Brief **Category:** bug **Summary:** The default `mail_evidence` call scans the whole `messages` table, because `messages_from (account, from_addr)` cannot serve a lookup with no account. Add an index that can. **Current behavior:** Verified on `main` at `28839b9` against a synthetic store of 180k messages (150k inbox, 30k Sent). `mail_evidence` passes `account=None` and `exclude_sent=True` by default (`server.py:667`). - `by_role` (`store.py:1927`) plans as `SCAN m`, a full table read. The `messages_from` index leads with `account`, and the query gives none. - `newest` plans as `SCAN m USING INDEX messages_from`, a walk of the whole index. - The `exclude_sent` subquery (`_SELF_SENDERS AND s.from_addr = ?`, `store.py:419` and `1914`) scans every Sent and Drafts row in each statement. - Nothing in the code runs `ANALYZE`, so SQLite has no statistics and no skip-scan. The live store plans the same way. Timings (median of 5): 123 ms as is, 37 ms with `exclude_sent=False`, and 13 ms with one index on `messages(from_addr)`. Live rows average about 13 KB (a 2 GB store), so each full read costs far more there. That fits the measured 2 s per call. Correction to the issue text: the `instr()` `sent` statement is not the main cost. It reads only Sent rows through the `(account, mailbox)` index, 11 ms for 30k Sent rows here. #138 moves it onto a recipients table. **Desired behavior:** - One index that serves an exact `from_addr` lookup with or without an account, for example `messages (from_addr, account)`. - `by_role`, `newest` and the `exclude_sent` subquery all search that index. The `mail_people` and `people` paths keep working, and use it where the planner picks it. - The index lands in a schema migration in the writer. `SCHEMA_VERSION` goes up by one. `Store(reader=True)` never creates it and refuses an older schema, as today (`store.py:561-568`). - `mail_evidence` output is unchanged for every input (ADR 0008 §2). **Key interfaces:** - The schema index list (`store.py:112-116`), `SCHEMA_VERSION` (`store.py:31`) and the migration path. - `Store.evidence` (`store.py:1898`): no query text change is expected. Change it only if the planner needs help, and say why in the PR. **Acceptance criteria:** - [ ] A test runs `EXPLAIN QUERY PLAN` on the `by_role` and `newest` statements and the `exclude_sent` subquery with `account=None`. Each shows a `SEARCH` using the new index, and none shows `SCAN m` or `SCAN s`. - [ ] The same test with an account given still uses an index. - [ ] An existing v11 store opens in the writer, migrates, and has the index. A reader on an unmigrated store raises the existing clear error. - [ ] Every existing `mail_evidence`, `mail_people` and `people` test passes unchanged. - [ ] The PR records the median `Store.evidence` time before and after on a synthetic store of at least 150k messages with a Sent mailbox. The image ships SQLite 3.40.1 (#96), so run it in the image, head and base alternating in one container. - [ ] `make check` passes. Tests run as `uv run python3 -m pytest`. **Out of scope:** - The recipients table and the `sent` statement (#138). - A batch form of `mail_evidence`, or any new field. - Running `ANALYZE` or `PRAGMA optimize`. **Order:** #136 lands before #138 and #108, because each of them also raises `SCHEMA_VERSION`. **Operator check after deploy:** time `mail_evidence` on the live piers store. The target is p50 under 100 ms, and a People Mind cold pass under 15 minutes. If the target is missed, the remaining cost is the `sent` scan, which #138 removes.
Collaborator

⏸ SVD architect gate: dev/mail-mind-mcp#136 mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se

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: 20261102T074145Z-e10bc52e

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

Open risks:

  1. Should Store.people group by +m.from_addr when account is None? The brief says people paths should use the new index 'where the planner picks it'. The planner picks a full messages_sender index walk, which made account-less people() 1.4-1.5x slower on the host (605 -> 927 ms for both statements). The hint restores the base plan (405 -> 290 ms per statement) with identical rows. Recommendation: keep it, scoped to account=None, with the plan test as its guard. If rejected, drop spec section 3 and its test, and record the people() regression in the PR. [decision]
  2. The live targets are provable only after deploy. Operator check: time mail_evidence on the live piers store (p50 < 100 ms for the default account-less call) and one People Mind cold pass (< 15 min). An account-scoped call stays around 300 ms because the sent statement walks the account via messages_received; that is #138's scope, not absorbed here. If the account-less p50 misses 100 ms, #138 is next. [verification]
  3. The plan strings were proven on host SQLite 3.53.3; the image ships 3.40.1. Check: the in-image bench_evidence.py run prints the account=None by_role plan, which must read 'SEARCH m USING INDEX messages_sender (from_addr=?)'. Record it in the PR. If 3.40.1 plans differently, halt to the architect rather than adding planner hints to evidence. [verification]

Change: Add CREATE INDEX IF NOT EXISTS messages_sender ON messages (from_addr, account, message_id); to the _TABLES index list after messages_copies (store.py:116). Writer opens run it via executescript(_SCHEMA) at store.py:525, so an existing v11 store gains it. Bump SCHEMA_VERSION 11→12 (store.py:31); the reader wait/refuse at :554-569 is unchanged. Use 3 columns, not the brief's 2-column example: measured on the host, (from_addr, account) makes account-scoped evidence quadratic (452 ms → 21.4 s for a 3,000-message sender), because the correlated _same_message copy lookup switches off messages_msgid. With message_id third, that lookup is a 3-equality search. Store.evidence query text is unchanged. In Store.people (store.py:1887), GROUP BY +m.from_addr only when account is None, because the new index otherwise turns the unscoped table scan into a slower index walk (605→927 ms). Mirror the 096208f schema-v11 bump: the RecordingConnection + EXPLAIN QUERY PLAN tests (tests/test_embed_scans.py:84-104) and the v10 migration/reader-refusal test (:154-170). Bump every == 11 / schema v11 test literal. Add scripts/bench_evidence.py mirroring scripts/bench_embed.py, and README/CLAUDE.md notes.

Files: src/mail_mind_mcp/store.py · tests/test_evidence.py · tests/test_embed_scans.py · tests/test_store.py · tests/test_copy_collapse.py · tests/test_attachment_vectors.py · tests/test_attachments.py · scripts/bench_evidence.py · README.md · CLAUDE.md

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-02-mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se.md

### ⏸ SVD architect gate: dev/mail-mind-mcp#136 mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se **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:** `20261102T074145Z-e10bc52e` **Held because:** CLEAN but 3 open risk(s) (2 verification · 1 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. Should Store.people group by +m.from_addr when account is None? The brief says people paths should use the new index 'where the planner picks it'. The planner picks a full messages_sender index walk, which made account-less people() 1.4-1.5x slower on the host (605 -> 927 ms for both statements). The hint restores the base plan (405 -> 290 ms per statement) with identical rows. Recommendation: keep it, scoped to account=None, with the plan test as its guard. If rejected, drop spec section 3 and its test, and record the people() regression in the PR. [decision] 2. The live targets are provable only after deploy. Operator check: time mail_evidence on the live piers store (p50 < 100 ms for the default account-less call) and one People Mind cold pass (< 15 min). An account-scoped call stays around 300 ms because the sent statement walks the account via messages_received; that is #138's scope, not absorbed here. If the account-less p50 misses 100 ms, #138 is next. [verification] 3. The plan strings were proven on host SQLite 3.53.3; the image ships 3.40.1. Check: the in-image bench_evidence.py run prints the account=None by_role plan, which must read 'SEARCH m USING INDEX messages_sender (from_addr=?)'. Record it in the PR. If 3.40.1 plans differently, halt to the architect rather than adding planner hints to evidence. [verification] **Change:** Add `CREATE INDEX IF NOT EXISTS messages_sender ON messages (from_addr, account, message_id);` to the `_TABLES` index list after messages_copies (store.py:116). Writer opens run it via executescript(_SCHEMA) at store.py:525, so an existing v11 store gains it. Bump SCHEMA_VERSION 11→12 (store.py:31); the reader wait/refuse at :554-569 is unchanged. Use 3 columns, not the brief's 2-column example: measured on the host, (from_addr, account) makes account-scoped evidence quadratic (452 ms → 21.4 s for a 3,000-message sender), because the correlated _same_message copy lookup switches off messages_msgid. With message_id third, that lookup is a 3-equality search. Store.evidence query text is unchanged. In Store.people (store.py:1887), GROUP BY `+m.from_addr` only when account is None, because the new index otherwise turns the unscoped table scan into a slower index walk (605→927 ms). Mirror the 096208f schema-v11 bump: the RecordingConnection + EXPLAIN QUERY PLAN tests (tests/test_embed_scans.py:84-104) and the v10 migration/reader-refusal test (:154-170). Bump every `== 11` / `schema v11` test literal. Add scripts/bench_evidence.py mirroring scripts/bench_embed.py, and README/CLAUDE.md notes. **Files:** `src/mail_mind_mcp/store.py` · `tests/test_evidence.py` · `tests/test_embed_scans.py` · `tests/test_store.py` · `tests/test_copy_collapse.py` · `tests/test_attachment_vectors.py` · `tests/test_attachments.py` · `scripts/bench_evidence.py` · `README.md` · `CLAUDE.md` **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-02-mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se.md`</sub>
Collaborator

spec-verify-dispatch Half B for dev/mail-mind-mcp#136 mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se completed integration verify.

  • PR: #139
  • Branch: feat/svd-dev-mail-mind-mcp-136-mail-evidence-costs-about-2-s-dc251286
  • Commit: 8f80b5243b
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: True
  • Checks: Remote checks: none reported on PR #139 head 8f80b52 (empty Forgejo status list). Local: 839 passed, 8 skipped, 0 failed. No blockers.
  • Warning: The Forgejo commit-status list for PR head 8f80b52 is empty, so no remote CI context reported. CLAUDE.md says CI files are added by the architect.
  • Warning: Image benchmark (SQLite 3.40.1): the account-less people() timing was 1.5-6.1% slower with the approved +m.from_addr hint (595.9 -> 603.9 ms alternating; 588.5 ms without the hint). The spec expected 'no slower'. Non-blocking; the spec approved the hint.
  • Warning: self-review (planner comment overclaimed speed) was fixed in the diff; no follow-up needed.
  • Warning: Local run was the full non-integration suite (839 passed, 8 skipped). make check lint, mypy and audit were not re-run by this stage.
  • Decision: review the PR and merge? (codex-svd ship --run-id 20261102T081440Z-dc251286 --confirm-merge)
spec-verify-dispatch Half B for dev/mail-mind-mcp#136 mail-evidence-costs-about-2-s-of-a-full-core-per-call-the-se completed integration verify. - PR: https://git.groupthink.asia/dev/mail-mind-mcp/pulls/139 - Branch: feat/svd-dev-mail-mind-mcp-136-mail-evidence-costs-about-2-s-dc251286 - Commit: 8f80b5243b6912ba0281679e1b33dd405d293ba3 - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: True - Checks: Remote checks: none reported on PR #139 head 8f80b52 (empty Forgejo status list). Local: 839 passed, 8 skipped, 0 failed. No blockers. - Warning: The Forgejo commit-status list for PR head 8f80b52 is empty, so no remote CI context reported. CLAUDE.md says CI files are added by the architect. - Warning: Image benchmark (SQLite 3.40.1): the account-less people() timing was 1.5-6.1% slower with the approved +m.from_addr hint (595.9 -> 603.9 ms alternating; 588.5 ms without the hint). The spec expected 'no slower'. Non-blocking; the spec approved the hint. - Warning: self-review (planner comment overclaimed speed) was fixed in the diff; no follow-up needed. - Warning: Local run was the full non-integration suite (839 passed, 8 skipped). `make check` lint, mypy and audit were not re-run by this stage. - Decision: review the PR and merge? (`codex-svd ship --run-id 20261102T081440Z-dc251286 --confirm-merge`)
svc-agent-writer 2026-11-02 08:33:20 +00:00
  • closed this issue
  • removed the
    svd:go
    label
Sign in to join this conversation.
No milestone
No project
No assignees
3 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#136
No description provided.