mail_search(mailbox=...) scans every row on 0.10.3: #112 acceptance fails on a large store #142

Closed
opened 2026-11-02 11:38:14 +00:00 by svc-agent-writer · 4 comments

What happened

On 0.10.3, mail_search(mailbox=...) scans every message row. On a live store of about 249,000 messages and 34 mailboxes, mail_search(mailbox='inbox', limit=20) took 47 to 62 seconds in each of four runs. mail_search(role='inbox', limit=20) took 1.5 to 3.5 seconds in the same runs.

#112 asked for the mailbox filter to take about as long as the role filter. It does not, so #112's acceptance fails on a large store. A caller that filters by mailbox now waits close to a 60-second client timeout.

Cause

#137 (28839b9) changed the mailbox filter in store.py to this:

casefold(m.mailbox) = ? OR EXISTS (SELECT 1 FROM json_each(m.mailboxes) j WHERE casefold(j.value) = ?)

casefold is a Python function registered with create_function. No index can serve casefold(m.mailbox), so SQLite calls the Python function, plus json_each, once per row. In 0.10.1 the filter compared m.mailbox directly.

The role filter stays fast, because it joins mailboxes on (account, name).

Possible direction (not decided)

Fold the requested name against the small mailboxes table first; mailbox_names() already reads it. Then filter messages with m.mailbox IN (<exact names>), which an index can serve. Keep the json_each arm only for rows from sources with stable ids. A test can assert the query plan uses an index for mailbox=.

Evidence

  • Version 0.10.3, image sha256:f9cbf180…b6f9, schema v13.
  • Timings were measured in the api container on the local endpoint while the sync worker ran. Times are wall-clock per call.
  • mailbox=inbox: 62.28, 51.46, 46.94 and 47.25 s.
  • role=inbox: 3.53, 1.68, 1.52 and 1.51 s.

Acceptance criteria

  1. mail_search(mailbox=...) resolves the requested name case-insensitively against the mailboxes table first and filters messages with an indexable predicate (m.mailbox IN (<exact names>)), keeping a json_each(m.mailboxes) arm only where a row carries several mailboxes.
  2. Red/green: a store test with at least 50,000 synthetic rows asserts mail_search(mailbox='inbox') and mail_search(role='inbox') run within the same order of magnitude (or asserts the query plan uses the mailbox index); at the base the plan is a full scan with the per-row casefold call.
  3. #112's behaviour is kept: case-insensitive mailbox names and the warning for an unknown mailbox.
  4. Existing tests/test_store.py stays green.

Filed under: operator word "ready-for-agent" sha256:7990aa64d598

## What happened On 0.10.3, `mail_search(mailbox=...)` scans every message row. On a live store of about 249,000 messages and 34 mailboxes, `mail_search(mailbox='inbox', limit=20)` took 47 to 62 seconds in each of four runs. `mail_search(role='inbox', limit=20)` took 1.5 to 3.5 seconds in the same runs. #112 asked for the `mailbox` filter to take about as long as the `role` filter. It does not, so #112's acceptance fails on a large store. A caller that filters by `mailbox` now waits close to a 60-second client timeout. ## Cause #137 (`28839b9`) changed the `mailbox` filter in `store.py` to this: ```sql casefold(m.mailbox) = ? OR EXISTS (SELECT 1 FROM json_each(m.mailboxes) j WHERE casefold(j.value) = ?) ``` `casefold` is a Python function registered with `create_function`. No index can serve `casefold(m.mailbox)`, so SQLite calls the Python function, plus `json_each`, once per row. In 0.10.1 the filter compared `m.mailbox` directly. The `role` filter stays fast, because it joins `mailboxes` on `(account, name)`. ## Possible direction (not decided) Fold the requested name against the small `mailboxes` table first; `mailbox_names()` already reads it. Then filter `messages` with `m.mailbox IN (<exact names>)`, which an index can serve. Keep the `json_each` arm only for rows from sources with stable ids. A test can assert the query plan uses an index for `mailbox=`. ## Evidence - Version 0.10.3, image `sha256:f9cbf180…b6f9`, schema v13. - Timings were measured in the `api` container on the local endpoint while the sync worker ran. Times are wall-clock per call. - `mailbox=inbox`: 62.28, 51.46, 46.94 and 47.25 s. - `role=inbox`: 3.53, 1.68, 1.52 and 1.51 s. ## Acceptance criteria 1. `mail_search(mailbox=...)` resolves the requested name case-insensitively against the `mailboxes` table first and filters `messages` with an indexable predicate (`m.mailbox IN (<exact names>)`), keeping a `json_each(m.mailboxes)` arm only where a row carries several mailboxes. 2. Red/green: a store test with at least 50,000 synthetic rows asserts `mail_search(mailbox='inbox')` and `mail_search(role='inbox')` run within the same order of magnitude (or asserts the query plan uses the mailbox index); at the base the plan is a full scan with the per-row `casefold` call. 3. #112's behaviour is kept: case-insensitive mailbox names and the warning for an unknown mailbox. 4. Existing `tests/test_store.py` stays green. Filed under: operator word "ready-for-agent" sha256:7990aa64d598
Author
Member

This was generated by AI during triage.

Triaged 2026-11-03 (backlog wave 5, batch T-C2). Route: ready-for-agent (CONV-40 rule 2: src/mail_mind_mcp/store.py plus tests/test_store.py, direction given, red side measured in the body).

Premise re-verified at main after v0.10.5: store.py:1615–1621 still filters with casefold({alias}.mailbox) = ? OR EXISTS (SELECT 1 FROM json_each({alias}.mailboxes) …), the per-row Python call this issue measured; the 2026-11-02 commits on store.py (#137, #139, #140, #143, #145) did not change it. Body hygiene: acceptance criteria, Filed under: line.

Filed under: operator word "ready-for-agent" sha256:7990aa64d598

> *This was generated by AI during triage.* Triaged 2026-11-03 (backlog wave 5, batch T-C2). Route: `ready-for-agent` (CONV-40 rule 2: `src/mail_mind_mcp/store.py` plus `tests/test_store.py`, direction given, red side measured in the body). **Premise re-verified** at main after v0.10.5: `store.py:1615–1621` still filters with `casefold({alias}.mailbox) = ? OR EXISTS (SELECT 1 FROM json_each({alias}.mailboxes) …)`, the per-row Python call this issue measured; the 2026-11-02 commits on `store.py` (#137, #139, #140, #143, #145) did not change it. Body hygiene: acceptance criteria, `Filed under:` line. Filed under: operator word "ready-for-agent" sha256:7990aa64d598
Collaborator

⏸ SVD architect gate: dev/mail-mind-mcp#142 mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance

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: 20261103T005914Z-373020a9

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

Open risks:

  1. Schema bump: should messages_memberships ship as schema v15 (the lean, following #139 4d90734: 11 files, 8 of them one-line 14->15 test literals, and the api waits until the index exists)? Or without a bump (store.py, test_mailbox_search.py, test_store.py, README.md only; routes standard/medium; but a short post-deploy window where the api runs the new query before the writer builds the index, during which the multi-mailbox arm table-scans and is slower than base)? [decision]
  2. The prototype ran on SQLite 3.53.3 only; CI uses bookworm SQLite 3.40.1. Check: Woodpecker validation.yaml make check is green, and the plan assertions in test_mailbox_filter_reads_indexes_not_every_row pass on 3.40.1. If 3.40.1 names the indexes differently but still serves m from an index, widen the substring set as 873e646 did. Never drop the assertion; the casefold-count assertion is version-independent. [verification]
  3. Live first start on v15 builds messages_memberships over ~249k fat rows. Check on deploy: time the sync container from start until meta.schema_version=15, and watch whether api logs 'the mirror has no schema v15 yet' and restarts (SCHEMA_WAIT_SECONDS=60). Then re-run the issue's timing in the api container: mail_search(mailbox='inbox', limit=20) vs mail_search(role='inbox', limit=20), four runs each. Pass: mailbox times fall in the role range (1.5-3.5 s), not 47-62 s. [verification]
  4. Is it acceptable that a row's own mailbox now folds case-insensitively only through its mailboxes-table row? Without that row it matches exact case only. Production upserts the row every pass (ingest.py:198, jmap.py:555), so the window is an IMAP mailbox's first pass before its upsert, or a JMAP mailbox after forget_mailbox until its messages move. The multi-mailbox JSON arm still folds directly, so test_mail_count.py:102 passes unchanged. Lean: accept. [decision]
  5. The full suite was not run at spec time: the Half-A sandbox denied executing the repo .venv python, and imap_blade_mcp is absent for system python. The lean was verified only on a scratch copy of store.py with an imap_blade_mcp stub. Check: dispatch runs uv run python3 -m pytest -q -m "not integration" on the pristine base and again after the change; the failure set must be unchanged apart from the two new passing tests. [verification]

Change: Replace the mailbox term in Store._filters (store.py:1615-1621) with three arms. (1) The raw exact name: m.mailbox = ?. (2) (m.account, m.mailbox) IN (_FOLDED_MAILBOXES), where _FOLDED_MAILBOXES = SELECT x.account, x.name FROM mailboxes x WHERE casefold(x.name) = ?. (3) m.id IN (_SEVERAL_MAILBOXES), where _SEVERAL_MAILBOXES = SELECT y.id FROM messages y, json_each(y.mailboxes) j WHERE json_array_length(y.mailboxes) > 1 AND casefold(j.value) = ?. Prefix every arm with + when keyset=True. Define both constants in the _SELF_SENDERS shape (store.py:459-463), using the uncorrelated row-value IN pattern at store.py:2051-2053. Add CREATE INDEX IF NOT EXISTS messages_memberships ON messages (mailboxes) WHERE json_array_length(mailboxes) > 1 to _V5_INDEXES (store.py:2438-2443), not _TABLES. Bump SCHEMA_VERSION to 15, following #139 4d90734. Change the 14 literals to 15 across 8 test files, add DROP INDEX messages_memberships at tests/test_store.py:411, and add a v15 sentence to README.md:105 and :278. Leave count_groups' join (1849-1852) and server._unknown_mailbox unchanged. Add two tests to tests/test_mailbox_search.py: a 50k-row test asserting the plan and the casefold call count, and a v14->v15 reader-waits test. The prototype was verified in the sandbox: base 65,090 casefold calls with a SCAN m plan; fix 210 calls with covering-index plans; 0.019s vs role 0.016s on 50k rows with 6 KB bodies.

Files: src/mail_mind_mcp/store.py · tests/test_mailbox_search.py · tests/test_store.py · tests/test_embed_scans.py · tests/test_copy_collapse.py · tests/test_recipients.py · tests/test_evidence.py · tests/test_attachment_vectors.py · tests/test_utc_dates.py · tests/test_attachments.py · README.md

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-03-mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-03-mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance.md

### ⏸ SVD architect gate: dev/mail-mind-mcp#142 mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance **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:** `20261103T005914Z-373020a9` **Held because:** CLEAN but 5 open risk(s) (3 verification · 2 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. Schema bump: should messages_memberships ship as schema v15 (the lean, following #139 4d90734: 11 files, 8 of them one-line 14->15 test literals, and the api waits until the index exists)? Or without a bump (store.py, test_mailbox_search.py, test_store.py, README.md only; routes standard/medium; but a short post-deploy window where the api runs the new query before the writer builds the index, during which the multi-mailbox arm table-scans and is slower than base)? [decision] 2. The prototype ran on SQLite 3.53.3 only; CI uses bookworm SQLite 3.40.1. Check: Woodpecker validation.yaml make check is green, and the plan assertions in test_mailbox_filter_reads_indexes_not_every_row pass on 3.40.1. If 3.40.1 names the indexes differently but still serves m from an index, widen the substring set as 873e646 did. Never drop the assertion; the casefold-count assertion is version-independent. [verification] 3. Live first start on v15 builds messages_memberships over ~249k fat rows. Check on deploy: time the sync container from start until meta.schema_version=15, and watch whether api logs 'the mirror has no schema v15 yet' and restarts (SCHEMA_WAIT_SECONDS=60). Then re-run the issue's timing in the api container: mail_search(mailbox='inbox', limit=20) vs mail_search(role='inbox', limit=20), four runs each. Pass: mailbox times fall in the role range (1.5-3.5 s), not 47-62 s. [verification] 4. Is it acceptable that a row's own mailbox now folds case-insensitively only through its mailboxes-table row? Without that row it matches exact case only. Production upserts the row every pass (ingest.py:198, jmap.py:555), so the window is an IMAP mailbox's first pass before its upsert, or a JMAP mailbox after forget_mailbox until its messages move. The multi-mailbox JSON arm still folds directly, so test_mail_count.py:102 passes unchanged. Lean: accept. [decision] 5. The full suite was not run at spec time: the Half-A sandbox denied executing the repo .venv python, and imap_blade_mcp is absent for system python. The lean was verified only on a scratch copy of store.py with an imap_blade_mcp stub. Check: dispatch runs `uv run python3 -m pytest -q -m "not integration"` on the pristine base and again after the change; the failure set must be unchanged apart from the two new passing tests. [verification] **Change:** Replace the mailbox term in Store._filters (store.py:1615-1621) with three arms. (1) The raw exact name: m.mailbox = ?. (2) (m.account, m.mailbox) IN (_FOLDED_MAILBOXES), where _FOLDED_MAILBOXES = SELECT x.account, x.name FROM mailboxes x WHERE casefold(x.name) = ?. (3) m.id IN (_SEVERAL_MAILBOXES), where _SEVERAL_MAILBOXES = SELECT y.id FROM messages y, json_each(y.mailboxes) j WHERE json_array_length(y.mailboxes) > 1 AND casefold(j.value) = ?. Prefix every arm with + when keyset=True. Define both constants in the _SELF_SENDERS shape (store.py:459-463), using the uncorrelated row-value IN pattern at store.py:2051-2053. Add CREATE INDEX IF NOT EXISTS messages_memberships ON messages (mailboxes) WHERE json_array_length(mailboxes) > 1 to _V5_INDEXES (store.py:2438-2443), not _TABLES. Bump SCHEMA_VERSION to 15, following #139 4d90734. Change the 14 literals to 15 across 8 test files, add DROP INDEX messages_memberships at tests/test_store.py:411, and add a v15 sentence to README.md:105 and :278. Leave count_groups' join (1849-1852) and server._unknown_mailbox unchanged. Add two tests to tests/test_mailbox_search.py: a 50k-row test asserting the plan and the casefold call count, and a v14->v15 reader-waits test. The prototype was verified in the sandbox: base 65,090 casefold calls with a SCAN m plan; fix 210 calls with covering-index plans; 0.019s vs role 0.016s on 50k rows with 6 KB bodies. **Files:** `src/mail_mind_mcp/store.py` · `tests/test_mailbox_search.py` · `tests/test_store.py` · `tests/test_embed_scans.py` · `tests/test_copy_collapse.py` · `tests/test_recipients.py` · `tests/test_evidence.py` · `tests/test_attachment_vectors.py` · `tests/test_utc_dates.py` · `tests/test_attachments.py` · `README.md` **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-03-mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-03-mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance.md`</sub>
Collaborator

spec-verify-dispatch Half B for dev/mail-mind-mcp#142 mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance completed integration verify.

  • PR: #154
  • Branch: feat/svd-dev-mail-mind-mcp-142-mail-search-mailbox-scans-ever-2603f279
  • Commit: f866448b93
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: False
  • Check ci/woodpecker/pr/validation: pending https://ci.groupthink.asia/repos/72/pipeline/5/1
  • Checks: PR #154 head f866448: ci/woodpecker/pr/validation pending. Local full suite 1060 passed, 8 skipped; filtered suites 450 passed; ruff and mypy clean. One blocker: PR body says Closes #142, must be Refs.
  • Blocker: PR metadata: change the PR body line Closes #142 to Refs #142; the spec forbids Closes because the operator closes #142 after live timing on the 249k-row store.
  • Blocker cause: work for PR metadata: change the PR body line Closes #142 to Refs #142; the spec forbids Closes because the operator closes #142 after live timing on the 249k-row store.; no denial signature; evidence: PR #154 body: "Closes #142"; spec Agent Adjustments: "The PR refers to #142 with Refs, never Closes"
  • Warning: Validation used local SQLite 3.50.4. Bookworm SQLite 3.40.1 plan strings and live-store timing were not run; Woodpecker CI is still pending.
  • Warning: PR body carries a Co-Authored-By line naming gpt-6.1-sol; the repo convention is one Co-Authored-By trailer, which is present.
  • Warning: Spec has no scenario table; no scenario tracing needed. Spec-prescribed filtered suites collect and pass (450 tests).
  • Rework: 0 round(s), outcome metadata-hold
  • Escalation: PR metadata blocker(s) hold the run without code rework: PR metadata: change the PR body line Closes #142 to Refs #142; the spec forbids Closes because the operator closes #142 after live timing on the 249k-row store.; edit the PR title or body by hand, then re-run integrate or run the own-execution gate.
  • Decision: resolve the blockers above and rerun integrate, or park this PR for a human?
spec-verify-dispatch Half B for dev/mail-mind-mcp#142 mail-search-mailbox-scans-every-row-on-0-10-3-112-acceptance completed integration verify. - PR: https://git.groupthink.asia/dev/mail-mind-mcp/pulls/154 - Branch: feat/svd-dev-mail-mind-mcp-142-mail-search-mailbox-scans-ever-2603f279 - Commit: f866448b93d940bacbfc4fa81324e312ee3445e6 - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: False - Check ci/woodpecker/pr/validation: pending https://ci.groupthink.asia/repos/72/pipeline/5/1 - Checks: PR #154 head f866448: ci/woodpecker/pr/validation pending. Local full suite 1060 passed, 8 skipped; filtered suites 450 passed; ruff and mypy clean. One blocker: PR body says Closes #142, must be Refs. - Blocker: PR metadata: change the PR body line `Closes #142` to `Refs #142`; the spec forbids `Closes` because the operator closes #142 after live timing on the 249k-row store. - Blocker cause: work for PR metadata: change the PR body line `Closes #142` to `Refs #142`; the spec forbids `Closes` because the operator closes #142 after live timing on the 249k-row store.; no denial signature; evidence: PR #154 body: "Closes #142"; spec Agent Adjustments: "The PR refers to #142 with `Refs`, never `Closes`" - Warning: Validation used local SQLite 3.50.4. Bookworm SQLite 3.40.1 plan strings and live-store timing were not run; Woodpecker CI is still pending. - Warning: PR body carries a Co-Authored-By line naming gpt-6.1-sol; the repo convention is one Co-Authored-By trailer, which is present. - Warning: Spec has no scenario table; no scenario tracing needed. Spec-prescribed filtered suites collect and pass (450 tests). - Rework: 0 round(s), outcome metadata-hold - Escalation: PR metadata blocker(s) hold the run without code rework: PR metadata: change the PR body line `Closes #142` to `Refs #142`; the spec forbids `Closes` because the operator closes #142 after live timing on the 249k-row store.; edit the PR title or body by hand, then re-run integrate or run the own-execution gate. - Decision: resolve the blockers above and rerun integrate, or park this PR for a human?
Author
Member

Live verification passed (gate risk 3). The fix shipped in #154 (f83345a) and is in every release from v0.10.6.

  • Instance: mailmind-piers on starbase-syd, image 0.12.1 (sha256:fce38287…1264), schema v17, messages_memberships present, 249,117 messages.
  • Method: four mail_search(..., limit=20) calls per filter over the local endpoint in the api container, with the sync worker running. Times are wall-clock per call.
Filter Run 1 Run 2 Run 3 Run 4 Total
mailbox='inbox' 1.54 s 0.29 s 0.31 s 0.27 s 29,040
role='inbox' 0.22 s 0.20 s 0.24 s 0.25 s 29,040

On 0.10.3 the mailbox filter took 46.94 to 62.28 s. It now falls in the same range as the role filter, so #112's acceptance holds on a large store. The first mailbox run is a cold cache.

Closing.

Live verification passed (gate risk 3). The fix shipped in #154 (f83345a) and is in every release from v0.10.6. - Instance: `mailmind-piers` on starbase-syd, image 0.12.1 (sha256:fce38287…1264), schema v17, `messages_memberships` present, 249,117 messages. - Method: four `mail_search(..., limit=20)` calls per filter over the local endpoint in the api container, with the sync worker running. Times are wall-clock per call. | Filter | Run 1 | Run 2 | Run 3 | Run 4 | Total | | --- | --- | --- | --- | --- | --- | | `mailbox='inbox'` | 1.54 s | 0.29 s | 0.31 s | 0.27 s | 29,040 | | `role='inbox'` | 0.22 s | 0.20 s | 0.24 s | 0.25 s | 29,040 | On 0.10.3 the mailbox filter took 46.94 to 62.28 s. It now falls in the same range as the role filter, so #112's acceptance holds on a large store. The first mailbox run is a cold cache. Closing.
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#142
No description provided.