Add a recipients table: an exact recipient filter on mail_search, and mail_evidence Sent lookups by index #138

Closed
opened 2026-11-02 07:29:13 +00:00 by svc-agent-writer · 2 comments

This was generated by AI during triage.

Raised during the triage of #136 on 2026-11-02. A recipients table makes recipient lookups exact and indexed. This issue builds it, adds the recipient filter, and moves the mail_evidence Sent query onto it.

Agent Brief

Category: enhancement
Summary: A recipients table filled by the sync worker, a recipient filter on mail_search, and the mail_evidence Sent query moved onto that table

Current behavior:

  • mail_search filters on sender, but not on a recipient. "What did I send to X" or "mail where X was on Cc" can only use the full-text query. FTS indexes to_addrs (store.py:40-59), but it matches tokens, not exact addresses, and it never sees cc_addrs.
  • Store.evidence finds Sent messages that name an address with instr(lower(m.to_addrs), ?) and instr(lower(m.cc_addrs), ?) over every Sent row, then re-checks the parsed cells in Python (store.py:1932-1953). The cost grows with the Sent mailbox.
  • No table or index maps a recipient address to a message.

Desired behavior:

  • A table recipients (message_id, account, address, kind). message_id is messages.id, and kind is to or cc. It has one row per parsed address per message, using the #129 rule (evidence.address: lowercase, an @, no whitespace). An address that does not parse gets no row. Bcc is not stored, as today.
  • An index whose first column is address, so a lookup with no account uses it. The messages_from (account, from_addr) index cannot serve an account-free lookup, which is the #136 defect, so do not repeat that shape.
  • Store.upsert_messages (store.py:697) fills the table. Both sources write through it (ingest.py:234, jmap.py:621). When an upsert changes to_addrs or cc_addrs, the rows for that message are replaced.
  • An AFTER DELETE ON messages trigger removes a message's rows, so every delete path is covered (delete_uids, delete_sources and any other). The store does not enable PRAGMA foreign_keys, so a foreign key alone would not do this.
  • A schema migration creates the table and fills it from the stored to_addrs and cc_addrs in the writer, in batches. The parse runs in Python, so the SQL and Python rules cannot drift. Store(reader=True) never writes it and refuses an older schema, as today (store.py:561-568).
  • SearchParams gains recipient: str | None. The filter matches when the address is in the message's To or Cc. The match is exact, and the argument is lowercased. mail_search takes recipient, and its description and the README row say that it matches To or Cc exactly and never Bcc. mail_count (#111) reuses SearchParams, so it gets the filter with no further work.
  • Store.evidence reads its Sent rows through recipients. The instr scan and the Python re-check go away. The copy-key dedupe stays. The mail_evidence output is unchanged for every input: same fields and same values (ADR 0008 §2).
  • Logs keep counts only: the migration logs how many rows it filled, never an address.

Key interfaces:

  • Store.upsert_messages, the schema, SCHEMA_VERSION and the migration list.
  • SearchParams and Store._filters (store.py:1518).
  • mail_search signature and docstring.
  • Store.evidence: the sent statement only.

Acceptance criteria:

  • A message to a@example.test with Cc b@example.test gives two rows, to and cc. A To cell holding first last@example.test gives no row.
  • Re-upserting the message with a new To list replaces its rows. Deleting it through delete_uids or delete_sources removes them.
  • An existing v-current store migrates, and the table then holds the same rows that ingest would have written.
  • mail_search(recipient="b@example.test") returns the message above. recipient="example.test" returns nothing, because the match is exact.
  • EXPLAIN QUERY PLAN for the recipient filter and for the evidence Sent statement, with no account given, shows a search using the new index, not a scan. Assert this in a test.
  • mail_evidence output is byte-for-byte unchanged on the existing evidence test cases, including a longer address that contains the queried one (xa@example.test against a@example.test).
  • make check passes. Tests run as uv run python3 -m pytest.

Primary files:

  • src/mail_mind_mcp/store.py
  • src/mail_mind_mcp/server.py (mail_search only)
  • README.md (the mail_search row)
  • tests/test_recipients.py (new)
  • tests/test_store.py, tests/test_evidence.py (only where an existing case needs the new schema)

Out of scope:

  • A sent-to count in mail_people. The operator rated it "might be useful" on 2026-11-02. It would be a second consumer of this table, and it needs an ADR 0008 amendment, because mail_people's fields are in the evidence scope. Not filed.
  • Bcc, display names, and any change to mail_read or the mail_changes envelope.
  • The from_addr index for by_role and newest (#136).

Blocked by

  • #136 (both change SCHEMA_VERSION; #136 is the smaller change and lands first)

Filed under: operator word "1 yes" sha256:c592151fdf13

> *This was generated by AI during triage.* Raised during the triage of #136 on 2026-11-02. A recipients table makes recipient lookups exact and indexed. This issue builds it, adds the recipient filter, and moves the `mail_evidence` Sent query onto it. ## Agent Brief **Category:** enhancement **Summary:** A `recipients` table filled by the sync worker, a `recipient` filter on `mail_search`, and the `mail_evidence` Sent query moved onto that table **Current behavior:** - `mail_search` filters on `sender`, but not on a recipient. "What did I send to X" or "mail where X was on Cc" can only use the full-text query. FTS indexes `to_addrs` (`store.py:40-59`), but it matches tokens, not exact addresses, and it never sees `cc_addrs`. - `Store.evidence` finds Sent messages that name an address with `instr(lower(m.to_addrs), ?)` and `instr(lower(m.cc_addrs), ?)` over every Sent row, then re-checks the parsed cells in Python (`store.py:1932-1953`). The cost grows with the Sent mailbox. - No table or index maps a recipient address to a message. **Desired behavior:** - A table `recipients (message_id, account, address, kind)`. `message_id` is `messages.id`, and `kind` is `to` or `cc`. It has one row per parsed address per message, using the #129 rule (`evidence.address`: lowercase, an `@`, no whitespace). An address that does not parse gets no row. Bcc is not stored, as today. - An index whose first column is `address`, so a lookup with no account uses it. The `messages_from (account, from_addr)` index cannot serve an account-free lookup, which is the #136 defect, so do not repeat that shape. - `Store.upsert_messages` (`store.py:697`) fills the table. Both sources write through it (`ingest.py:234`, `jmap.py:621`). When an upsert changes `to_addrs` or `cc_addrs`, the rows for that message are replaced. - An `AFTER DELETE ON messages` trigger removes a message's rows, so every delete path is covered (`delete_uids`, `delete_sources` and any other). The store does not enable `PRAGMA foreign_keys`, so a foreign key alone would not do this. - A schema migration creates the table and fills it from the stored `to_addrs` and `cc_addrs` in the writer, in batches. The parse runs in Python, so the SQL and Python rules cannot drift. `Store(reader=True)` never writes it and refuses an older schema, as today (`store.py:561-568`). - `SearchParams` gains `recipient: str | None`. The filter matches when the address is in the message's To or Cc. The match is exact, and the argument is lowercased. `mail_search` takes `recipient`, and its description and the README row say that it matches To or Cc exactly and never Bcc. `mail_count` (#111) reuses `SearchParams`, so it gets the filter with no further work. - `Store.evidence` reads its Sent rows through `recipients`. The `instr` scan and the Python re-check go away. The copy-key dedupe stays. The `mail_evidence` output is unchanged for every input: same fields and same values (ADR 0008 §2). - Logs keep counts only: the migration logs how many rows it filled, never an address. **Key interfaces:** - `Store.upsert_messages`, the schema, `SCHEMA_VERSION` and the migration list. - `SearchParams` and `Store._filters` (`store.py:1518`). - `mail_search` signature and docstring. - `Store.evidence`: the `sent` statement only. **Acceptance criteria:** - [ ] A message to `a@example.test` with Cc `b@example.test` gives two rows, `to` and `cc`. A To cell holding `first last@example.test` gives no row. - [ ] Re-upserting the message with a new To list replaces its rows. Deleting it through `delete_uids` or `delete_sources` removes them. - [ ] An existing v-current store migrates, and the table then holds the same rows that ingest would have written. - [ ] `mail_search(recipient="b@example.test")` returns the message above. `recipient="example.test"` returns nothing, because the match is exact. - [ ] `EXPLAIN QUERY PLAN` for the recipient filter and for the evidence Sent statement, with no account given, shows a search using the new index, not a scan. Assert this in a test. - [ ] `mail_evidence` output is byte-for-byte unchanged on the existing evidence test cases, including a longer address that contains the queried one (`xa@example.test` against `a@example.test`). - [ ] `make check` passes. Tests run as `uv run python3 -m pytest`. **Primary files:** - `src/mail_mind_mcp/store.py` - `src/mail_mind_mcp/server.py` (`mail_search` only) - `README.md` (the `mail_search` row) - `tests/test_recipients.py` (new) - `tests/test_store.py`, `tests/test_evidence.py` (only where an existing case needs the new schema) **Out of scope:** - A sent-to count in `mail_people`. The operator rated it "might be useful" on 2026-11-02. It would be a second consumer of this table, and it needs an ADR 0008 amendment, because `mail_people`'s fields are in the evidence scope. Not filed. - Bcc, display names, and any change to `mail_read` or the `mail_changes` envelope. - The `from_addr` index for `by_role` and `newest` (#136). ## Blocked by - #136 (both change `SCHEMA_VERSION`; #136 is the smaller change and lands first) Filed under: operator word "1 yes" sha256:c592151fdf13
Collaborator

⏸ SVD architect gate: dev/mail-mind-mcp#138 add-a-recipients-table-an-exact-recipient-filter-on-mail-sea

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: 20261102T085850Z-3ef3ee29

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

Open risks:

  1. Should mail_evidence's Sent count follow the parsed address alone (Option A, the lean) or also keep instr as a residual filter (Option B)? The old statement only parsed cells that instr(lower(cell), address) had matched. getaddresses collapses whitespace around '@', so a stored cell 'A <a @ example.test>' parses to a@example.test without containing it: the old code counts 0, the table counts 1 (proven by the sandbox test test_a_spaced_cell_the_parser_reads_now_counts_as_sent). Such cells come only from raw JMAP email or IMAP envelope values with whitespace (the #129 class). The brief asks for both 'output unchanged for every input' and 'the instr scan goes away'. Option A (recommended): accept it; it matches ADR 0008 §2 ('address in To or Cc') and makes mail_search(recipient=) and mail_evidence agree, and all existing tests plus the oracle stay byte-identical. Option B: append AND (instr(lower(m.to_addrs), ?) > 0 OR instr(lower(m.cc_addrs), ?) > 0) to the index-found rows (not a scan) for strict parity, and flip the pin test to sent == 0. [decision]
  2. The plan strings and timings are proven only on host SQLite 3.53.3; the image ships 3.40.1. Check: run uv run python scripts/bench_evidence.py in the image (at least 150k rows, base and head alternated in one container). Its 'sent account=None plan:' block must contain 'SEARCH r USING COVERING INDEX recipients_address (address=?)' and no 'SCAN m'; record it in the PR. If 3.40.1 plans differently, stop and report rather than adding planner hints. Live check after deploy: the first v13 sync start logs 'recipients filled for schema v13' once with a rows count, and the api container comes up within its 60 s schema wait. [verification]

Change: Follow the child-table + AFTER DELETE trigger shape of embeddings/attachment_text in store.py:215-253. Add recipients (message_id, account, address, kind) PRIMARY KEY (message_id, kind, address) WITHOUT ROWID, with recipients_address (address, message_id) and a messages_recipients_ad trigger. One module helper, _write_recipients(conn, row_id, account, to, cc), deletes the message's rows and then inserts evidence.addresses() per kind. It is called from upsert_messages (RETURNING id added to the upsert at store.py:709-752) and from a new batched Store._fill_recipients (keyset by id, one _tx per 2,000 rows, mirroring _write_embedding_copies at :955-966). The fill runs in the writer __init__ between _add_columns and the version upsert when _schema_version < 13, and logs rows only, like _migrate_fts at :2302-2317. SCHEMA_VERSION 12 → 13. SearchParams.recipient plus a _filters term {alias}.id IN (SELECT rcp.message_id FROM recipients rcp WHERE rcp.address = ?), lowercased, after the sender block at :1545-1548. mail_search gets a recipient argument after sender (server.py:238/296). Store.evidence's sent statement becomes ... AND m.id IN (SELECT r.message_id FROM recipients r WHERE r.address = ?); the instr scan and the addresses() re-check go, and the copy-key dedupe stays. Other edits: README row 47 and the v13 notes at :92/:238; bench_evidence.py rewinds meta to 12 after its raw inserts so the fill runs, and prints the sent plan; the 12→13 test literals; the test_evidence.py:119-125 prefix and skip update. The whole lean was run in the Half-A sandbox: same failure set as base, plus 6 new passes; mypy clean.

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

Decision: accept the 2 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-add-a-recipients-table-an-exact-recipient-filter-on-mail-sea.md — next: codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-add-a-recipients-table-an-exact-recipient-filter-on-mail-sea.md

### ⏸ SVD architect gate: dev/mail-mind-mcp#138 add-a-recipients-table-an-exact-recipient-filter-on-mail-sea **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:** `20261102T085850Z-3ef3ee29` **Held because:** CLEAN but 2 open risk(s) (1 verification · 1 decision) — HOLD-ALL parks everything. The risks, verbatim: **Open risks:** 1. Should mail_evidence's Sent count follow the parsed address alone (Option A, the lean) or also keep instr as a residual filter (Option B)? The old statement only parsed cells that instr(lower(cell), address) had matched. getaddresses collapses whitespace around '@', so a stored cell 'A <a @ example.test>' parses to a@example.test without containing it: the old code counts 0, the table counts 1 (proven by the sandbox test test_a_spaced_cell_the_parser_reads_now_counts_as_sent). Such cells come only from raw JMAP email or IMAP envelope values with whitespace (the #129 class). The brief asks for both 'output unchanged for every input' and 'the instr scan goes away'. Option A (recommended): accept it; it matches ADR 0008 §2 ('address in To or Cc') and makes mail_search(recipient=) and mail_evidence agree, and all existing tests plus the oracle stay byte-identical. Option B: append AND (instr(lower(m.to_addrs), ?) > 0 OR instr(lower(m.cc_addrs), ?) > 0) to the index-found rows (not a scan) for strict parity, and flip the pin test to sent == 0. [decision] 2. The plan strings and timings are proven only on host SQLite 3.53.3; the image ships 3.40.1. Check: run `uv run python scripts/bench_evidence.py` in the image (at least 150k rows, base and head alternated in one container). Its 'sent account=None plan:' block must contain 'SEARCH r USING COVERING INDEX recipients_address (address=?)' and no 'SCAN m'; record it in the PR. If 3.40.1 plans differently, stop and report rather than adding planner hints. Live check after deploy: the first v13 sync start logs 'recipients filled for schema v13' once with a rows count, and the api container comes up within its 60 s schema wait. [verification] **Change:** Follow the child-table + AFTER DELETE trigger shape of embeddings/attachment_text in store.py:215-253. Add `recipients (message_id, account, address, kind) PRIMARY KEY (message_id, kind, address) WITHOUT ROWID`, with `recipients_address (address, message_id)` and a `messages_recipients_ad` trigger. One module helper, `_write_recipients(conn, row_id, account, to, cc)`, deletes the message's rows and then inserts `evidence.addresses()` per kind. It is called from `upsert_messages` (`RETURNING id` added to the upsert at store.py:709-752) and from a new batched `Store._fill_recipients` (keyset by id, one `_tx` per 2,000 rows, mirroring `_write_embedding_copies` at :955-966). The fill runs in the writer `__init__` between `_add_columns` and the version upsert when `_schema_version < 13`, and logs `rows` only, like `_migrate_fts` at :2302-2317. `SCHEMA_VERSION` 12 → 13. `SearchParams.recipient` plus a `_filters` term `{alias}.id IN (SELECT rcp.message_id FROM recipients rcp WHERE rcp.address = ?)`, lowercased, after the sender block at :1545-1548. `mail_search` gets a `recipient` argument after `sender` (server.py:238/296). `Store.evidence`'s sent statement becomes `... AND m.id IN (SELECT r.message_id FROM recipients r WHERE r.address = ?)`; the instr scan and the `addresses()` re-check go, and the copy-key dedupe stays. Other edits: README row 47 and the v13 notes at :92/:238; `bench_evidence.py` rewinds meta to 12 after its raw inserts so the fill runs, and prints the sent plan; the 12→13 test literals; the `test_evidence.py:119-125` prefix and skip update. The whole lean was run in the Half-A sandbox: same failure set as base, plus 6 new passes; mypy clean. **Files:** `src/mail_mind_mcp/store.py` · `src/mail_mind_mcp/server.py` · `README.md` · `tests/test_recipients.py` · `tests/test_evidence.py` · `tests/test_store.py` · `tests/test_embed_scans.py` · `tests/test_copy_collapse.py` · `tests/test_attachment_vectors.py` · `tests/test_attachments.py` · `scripts/bench_evidence.py` **Decision:** accept the 2 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-add-a-recipients-table-an-exact-recipient-filter-on-mail-sea.md` — next: `codex-svd dispatch --args '<same-json>' --approved-spec-path /Users/piers/.local/state/exhaust/groupthink/specs/2026-11-02-add-a-recipients-table-an-exact-recipient-filter-on-mail-sea.md`</sub>
Collaborator

spec-verify-dispatch Half B for dev/mail-mind-mcp#138 add-a-recipients-table-an-exact-recipient-filter-on-mail-sea completed integration verify.

  • PR: #140
  • Branch: feat/svd-dev-mail-mind-mcp-138-add-a-recipients-table-an-exac-7362604b
  • Commit: 2cfa22773c
  • Build: none
  • Test: green
  • Reader audit clean: True
  • Spec fidelity: True
  • Ready for merge: True
  • Check forgejo commit statuses: absent
  • Checks: Remote: no Forgejo commit statuses on PR #140 head 2cfa227 (no CI in repo) - absent, non-blocking. Local: 846 passed, 8 skipped, 0 failed; ruff and mypy clean.
  • Warning: No remote CI on the PR head: the Forgejo statuses list is empty.
  • Warning: The image benchmark on SQLite 3.40.1 is not independently re-run here. Open Risk 2 stays proven only by the PR's printed Sent plan.
  • Warning: The commit trailer reads 'Co-Authored-By: gpt-6.1-sol noreply@openai.com'. The spec ruled Option A, so the PR body must record the output change for whitespace-in-address cells (the #129 class). Confirm the PR body does this.
  • Warning: Both self-review deviations were fixed (S608 suppression; Sent-role mailbox in the oracle test).
  • Warning: no CI for forgejo commit statuses: The PR head has no commit statuses. The repo has no CI (CLAUDE.md: CI files are added by the architect). No tracking pointer found. — reported as absent, not blocking (gh#633)
  • Decision: review the PR and merge? (codex-svd ship --run-id 20261102T093644Z-7362604b --confirm-merge)
spec-verify-dispatch Half B for dev/mail-mind-mcp#138 add-a-recipients-table-an-exact-recipient-filter-on-mail-sea completed integration verify. - PR: https://git.groupthink.asia/dev/mail-mind-mcp/pulls/140 - Branch: feat/svd-dev-mail-mind-mcp-138-add-a-recipients-table-an-exac-7362604b - Commit: 2cfa22773c4c69b2c77a069ff1a0dc8ff719c940 - Build: none - Test: green - Reader audit clean: True - Spec fidelity: True - Ready for merge: True - Check forgejo commit statuses: absent - Checks: Remote: no Forgejo commit statuses on PR #140 head 2cfa227 (no CI in repo) - absent, non-blocking. Local: 846 passed, 8 skipped, 0 failed; ruff and mypy clean. - Warning: No remote CI on the PR head: the Forgejo statuses list is empty. - Warning: The image benchmark on SQLite 3.40.1 is not independently re-run here. Open Risk 2 stays proven only by the PR's printed Sent plan. - Warning: The commit trailer reads 'Co-Authored-By: gpt-6.1-sol <noreply@openai.com>'. The spec ruled Option A, so the PR body must record the output change for whitespace-in-address cells (the #129 class). Confirm the PR body does this. - Warning: Both self-review deviations were fixed (S608 suppression; Sent-role mailbox in the oracle test). - Warning: no CI for forgejo commit statuses: The PR head has no commit statuses. The repo has no CI (CLAUDE.md: CI files are added by the architect). No tracking pointer found. — reported as absent, not blocking (gh#633) - Decision: review the PR and merge? (`codex-svd ship --run-id 20261102T093644Z-7362604b --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#138
No description provided.