Extract attachment text in the sync worker, in a limited child process #82

Merged
svc-agent-writer merged 1 commit from feat/attachment-text into main 2026-11-01 02:55:39 +00:00

Closes #73. Decision: ADR 0007.

Summary

With [attachments] set, the sync worker extracts the text of each attachment after every pass. It stores the text, never the bytes. mail_search in keyword mode then matches a word that occurs only in an attachment.

run_pass (IMAP or JMAP source)
  mirror, holding the raw message when it is downloaded for the bucket
  AttachmentBacklog.run            # newest first, per_pass attachments
    copy_attachment_texts          # a moved copy takes its original's text
    for each message without text
      bounds: per_message → skipped, type → unsupported, max_bytes → too_large
      bytes: held raw message → bucket (blob_key) → server (_fetch_parts)
      extract(kind, bytes)         # python -I -m imap_mailmind_mcp.extract
      set_attachment_texts         # attachment_text rows + messages.attached_text (FTS)
wait: min(interval, 5 s) while a backlog remains
src/imap_mailmind_mcp/
├── extract.py   # new: closed format list, the limited child, the parts of a raw message
├── store.py     # schema v7: attachment_text, attached_text FTS column, one-time index rebuild
├── source.py    # AttachmentBacklog
├── ingest.py    # BODYSTRUCTURE + one section per part
├── jmap.py      # Email/get attachments + one blob download per part
├── actions.py   # a move refreshes the target before it deletes the source rows
└── server.py    # mail_status: attachments=N attachment_backlog=M

The child for each attachment:

  • CPU 10 s (30 s for MarkItDown);
  • 512 MiB of address space;
  • a wall clock of twice the CPU limit;
  • PATH only, cwd /, stderr to /dev/null;
  • no sockets, before any parser is imported;
  • the zip-member check before any Office parser.

Evidence

  • Before: mail_search(query="quokkapdf") on a message whose PDF holds the word: total=0.
    After: one row, on GreenMail (IMAP) and on Stalwart (JMAP), for a PDF and a DOCX each.
  • make check: lint, mypy --strict, 251 unit tests, pip-audit clean.
  • make test-integration: 18 passed.
  • New unit tests, among them:
each extractor on a hand-made fixture            → text
an 8.7 KB PDF that costs pypdf 4 s, at 1 s CPU   → timeout in 1.0 s
a zip member over 20 MB / members over 100 MB    → too_large, no parser run
socket, create_connection, getaddrinfo, urlopen in the child → refused ×4
MarkItDown engine on .zip / .pdf / .html (docx engine) → UnsupportedFormatException
the child after a DOCX                           → no onnxruntime, magika is a stub
IMAP and JMAP with a bucket                      → no part fetch; after a restart, the bucket
held message whose part does not match           → failed, no fetch
retryable fetch error                            → nothing recorded, next pass at the usual interval
bucket error                                     → the server serves the bytes
log records                                      → no file name, no text

Measured on the image (native arm64; RLIMIT_AS is not enforced under amd64 emulation on the Mac, so these stand in for amd64):

Fixture Address space needed Peak RSS
PDF, 100 pages 55 MiB 41 MiB
DOCX, 100 pages 95 MiB 69 MiB
DOCX, 8.6 MB document part 339 MiB 336 MiB
DOCX, 19 MB document part (the zip check's ceiling) 654 MiB 676 MiB

Deviations from ADR 0007 and #73

  • Magika is stubbed out of MarkItDown. MarkItDown loads Magika's ONNX model in every child. That cost about 800 MiB of address space before the child read a byte, and at the limit the child hung instead of failing. The kind is already known, so a stub module stands in, and the child never loads onnxruntime.
  • 512 MiB for MarkItDown, not 1 GiB. The sync container is limited to 768Mi. One child at the 19 MB ceiling (676 MiB resident) beside the sync process and the embedder could get the container OOM-killed. At 512 MiB that file ends as failed in 5.8 s, and a document part up to about 10 MB still gives text. To keep those files, raise the sync limit in deploy/k8s/base and the address-space limit together.
  • The image grows by 83 MB, not 45 to 50 MB. The new packages are Pillow, lxml, python-pptx, mammoth, Magika's package, olefile and pypdf. The venv layer would have reached 94 MB compressed, against the proxy's 100 MB per request. Pillow and lxml now go in a layer of their own.
  • XLSX is read with defusedxml, not stdlib iterparse. ruff S314 flags the stdlib parser on hostile XML. This adds one small dependency.
  • olefile/olefile2.py is excluded from compileall. It is Python 2 source that nothing imports, and it broke the image build.

Known limits

  • A sync pass can see a move's deletion in the source mailbox before its arrival in the target. The moved copy is then extracted again. The result is correct; only work is wasted.
  • An IMAP-to-JMAP switch does not copy attachment text. The two sources record different attachment sizes (encoded and decoded), so their attachment lists never compare equal. The JMAP rows are extracted again.
  • A child killed by the OOM killer reports timeout, because SIGKILL is also the hard CPU limit's signal.
  • per_pass is checked per message, so one pass can go past it by up to per_message - 1.

Merge Danger

Door: one-way, for the mirror file

The first start moves the SQLite file to schema v7: a new table, a new column, and a dropped and rebuilt FTS index. No test opens a v7 file with 0.5.1. A rollback should restore the Litestream backup or re-mirror. Without [attachments], nothing else changes at run time.

Blast Radius: sync

  • The schema move rebuilds the search index once, in seconds per hundred thousand messages. The api waits for the new schema version.
  • With [attachments] set, the sync container fetches attachment bytes from the mail server when there is no bucket. It also runs one child at a time, using up to 512 MiB.
  • Existing configs have no [attachments], so the feature stays off until an operator adds it.

🤖 Generated with Claude Code

Closes #73. Decision: ADR 0007. ## Summary With `[attachments]` set, the sync worker extracts the text of each attachment after every pass. It stores the text, never the bytes. `mail_search` in keyword mode then matches a word that occurs only in an attachment. ```text run_pass (IMAP or JMAP source) mirror, holding the raw message when it is downloaded for the bucket AttachmentBacklog.run # newest first, per_pass attachments copy_attachment_texts # a moved copy takes its original's text for each message without text bounds: per_message → skipped, type → unsupported, max_bytes → too_large bytes: held raw message → bucket (blob_key) → server (_fetch_parts) extract(kind, bytes) # python -I -m imap_mailmind_mcp.extract set_attachment_texts # attachment_text rows + messages.attached_text (FTS) wait: min(interval, 5 s) while a backlog remains ``` ```text src/imap_mailmind_mcp/ ├── extract.py # new: closed format list, the limited child, the parts of a raw message ├── store.py # schema v7: attachment_text, attached_text FTS column, one-time index rebuild ├── source.py # AttachmentBacklog ├── ingest.py # BODYSTRUCTURE + one section per part ├── jmap.py # Email/get attachments + one blob download per part ├── actions.py # a move refreshes the target before it deletes the source rows └── server.py # mail_status: attachments=N attachment_backlog=M ``` The child for each attachment: - CPU 10 s (30 s for MarkItDown); - 512 MiB of address space; - a wall clock of twice the CPU limit; - `PATH` only, cwd `/`, stderr to `/dev/null`; - no sockets, before any parser is imported; - the zip-member check before any Office parser. ## Evidence - **Before:** `mail_search(query="quokkapdf")` on a message whose PDF holds the word: `total=0`. **After:** one row, on GreenMail (IMAP) and on Stalwart (JMAP), for a PDF and a DOCX each. - `make check`: lint, `mypy --strict`, 251 unit tests, pip-audit clean. - `make test-integration`: 18 passed. - New unit tests, among them: ```text each extractor on a hand-made fixture → text an 8.7 KB PDF that costs pypdf 4 s, at 1 s CPU → timeout in 1.0 s a zip member over 20 MB / members over 100 MB → too_large, no parser run socket, create_connection, getaddrinfo, urlopen in the child → refused ×4 MarkItDown engine on .zip / .pdf / .html (docx engine) → UnsupportedFormatException the child after a DOCX → no onnxruntime, magika is a stub IMAP and JMAP with a bucket → no part fetch; after a restart, the bucket held message whose part does not match → failed, no fetch retryable fetch error → nothing recorded, next pass at the usual interval bucket error → the server serves the bytes log records → no file name, no text ``` Measured on the image (native arm64; RLIMIT_AS is not enforced under amd64 emulation on the Mac, so these stand in for amd64): | Fixture | Address space needed | Peak RSS | |---|---|---| | PDF, 100 pages | 55 MiB | 41 MiB | | DOCX, 100 pages | 95 MiB | 69 MiB | | DOCX, 8.6 MB document part | 339 MiB | 336 MiB | | DOCX, 19 MB document part (the zip check's ceiling) | 654 MiB | 676 MiB | ## Deviations from ADR 0007 and #73 - **Magika is stubbed out of MarkItDown.** MarkItDown loads Magika's ONNX model in every child. That cost about 800 MiB of address space before the child read a byte, and at the limit the child hung instead of failing. The kind is already known, so a stub module stands in, and the child never loads onnxruntime. - **512 MiB for MarkItDown, not 1 GiB.** The `sync` container is limited to 768Mi. One child at the 19 MB ceiling (676 MiB resident) beside the sync process and the embedder could get the container OOM-killed. At 512 MiB that file ends as `failed` in 5.8 s, and a document part up to about 10 MB still gives text. To keep those files, raise the `sync` limit in `deploy/k8s/base` and the address-space limit together. - **The image grows by 83 MB, not 45 to 50 MB.** The new packages are Pillow, lxml, python-pptx, mammoth, Magika's package, olefile and pypdf. The venv layer would have reached 94 MB compressed, against the proxy's 100 MB per request. Pillow and lxml now go in a layer of their own. - **XLSX is read with `defusedxml`, not stdlib `iterparse`.** ruff S314 flags the stdlib parser on hostile XML. This adds one small dependency. - **`olefile/olefile2.py` is excluded from `compileall`.** It is Python 2 source that nothing imports, and it broke the image build. ## Known limits - A sync pass can see a move's deletion in the source mailbox before its arrival in the target. The moved copy is then extracted again. The result is correct; only work is wasted. - An IMAP-to-JMAP switch does not copy attachment text. The two sources record different attachment sizes (encoded and decoded), so their attachment lists never compare equal. The JMAP rows are extracted again. - A child killed by the OOM killer reports `timeout`, because SIGKILL is also the hard CPU limit's signal. - `per_pass` is checked per message, so one pass can go past it by up to `per_message - 1`. ## Merge Danger **Door:** one-way, for the mirror file The first start moves the SQLite file to schema v7: a new table, a new column, and a dropped and rebuilt FTS index. No test opens a v7 file with 0.5.1. A rollback should restore the Litestream backup or re-mirror. Without `[attachments]`, nothing else changes at run time. **Blast Radius:** sync - The schema move rebuilds the search index once, in seconds per hundred thousand messages. The `api` waits for the new schema version. - With `[attachments]` set, the `sync` container fetches attachment bytes from the mail server when there is no bucket. It also runs one child at a time, using up to 512 MiB. - Existing configs have no `[attachments]`, so the feature stays off until an operator adds it. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
ADR 0007, #73. With [attachments] set, the sync worker extracts the text of
each attachment after every pass and stores the text, never the bytes. Keyword
search then matches a word found only in an attachment.

- extract.py: the closed format list; pypdf, MarkItDown with one converter and
  no Magika, a defusedxml XLSX reader, charset decoding; a child with CPU,
  512 MiB address-space and wall limits, no sockets, and the zip-member check.
- store.py: schema v7, attachment_text rows, an attached_text FTS column and a
  one-time index rebuild; a moved copy takes its original's text.
- source.py: the backlog, with bytes from the held raw message, the bucket,
  then the server; ingest.py and jmap.py fetch parts and shorten the wait.
- mail_status shows the extracted count and the backlog per account.
- Containerfile: Pillow and lxml in a layer of their own; olefile2.py left out
  of compileall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No description provided.