Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions performance/mail/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ Measurements of reading a mailbox into the shared store with memo.
same searches after cli-core 0.295.0: 67 s → 0.7 s (2026-10-16).
- [agent-questions](agent-questions/README.md): six everyday questions an agent answers from an imported mailbox —
run 4: 2 answered, 2 partly, 2 not found (before the imported years), and what memo made hard (2026-10-16).
- [types](types/README.md): what typing every email costs cli-core's store (store version 76) — 100,000 emails typed
on the first filtered read in 1.7–11.6 s, one batch of 5,000 under the write lock in 0.1–0.6 s (2026-11-25).
72 changes: 72 additions & 0 deletions performance/mail/types/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Mail types: what typing every email costs the store

## Why it was run

The owner ruled that every email gets a type of its own, apart from its sender: a shop's receipts are `order`, its
sales `promotion`, and a tab such as Subscriptions is a filter over those types, not a table (contact-kinds plan in
cli-core [#3323](https://github.com/WireCatLabs/cli-core/pull/3323), section "Mail categories"). cli-core store
version 76 keeps each email's type and reach on the `emails` row, cleared by triggers when what decides them changes,
and works them out lazily ([#3358](https://github.com/WireCatLabs/cli-core/pull/3358)).

An existing store has no types after the upgrade. The first read that filters by type works out every email, a batch
per write, under the store's write lock, which other writers wait for at most 5 s. The questions:

1. On a store of 100,000 emails, how long does that first read take, and how long does one batch hold the lock?
2. Do warm filtered reads and the per-sender summary stay fast?
3. What does a read-only open of a store never typed cost, which works types out in memory?

The answers decided the batch size (5,000) and whether the work can stay lazy instead of a migration step.

## Setup

- Machine: AMD Ryzen AI 9 HX 370 (24 threads), Linux 7.0, Node 24.19.0. Other agents' runs kept the load average at
14 to 20 and wrote to the same disk, so commits (the store syncs each one to disk) varied a lot between runs.
- Code: cli-core branch `feat/mail-types` (store version 76), built with `pnpm build`.
- Data, all synthetic: 100,000 emails saved through `store.mail.saveThreads`, 100 per thread. 40% newsletters (List-Id
and List-Unsubscribe, 200 lists), 20% sales (one-click unsubscribe), 15% order receipts, 5% sign-in alerts, 5% the
owner's own mail to 2,000 people, 15% mail from those people. No bodies.

```sh
node bench.mjs <cli-core checkout> 100000
```

## Results

Two runs with batches of 5,000 (the shipped size), one earlier run with batches of 2,000 for comparison.

| Step | 5,000 per batch, 2 runs | 2,000 per batch |
| --- | ---: | ---: |
| query-only open of an untyped store: `emails types:[order]`, first 50 | 0.73–0.89 s | 0.47 s |
| query-only open of an untyped store: `mailSenders reach:broadcast` | 0.91–1.81 s | 0.83 s |
| first read: type all 100,000 emails, then `emails types:[order]`, first 50 | 1.7–11.6 s | 21.5 s |
| one batch under the write lock | 91–628 ms | 472 ms (2,000 emails) |
| warm `emails types:[order]`, first 50 | 10–14 ms | 13 ms |
| warm `emails types:[newsletter] reaches:[broadcast]`, first 50 | 14–21 ms | 20 ms |
| warm `emails`, no filter, first 50 | 11–19 ms | 20 ms |
| `mailSenders reach:broadcast` (140 of 1,090 senders) | 193–273 ms | 284 ms |
| `mailSenders`, every sender | 188–195 ms | 196 ms |
| the owner's first mail to a shop: save with triggers, 335 typed emails cleared | 66–595 ms | 117 ms |
| a rules change: all 100,000 typed again | 5.3–9.7 s | 10.8 s |

Working out the types themselves is cheap: 2,000 emails took 15–24 ms in a profile. Almost all of a batch's time is
the commit's sync to disk, which ranged from 18 to 680 ms per commit under the other agents' load.

## What it showed

- One batch holds the write lock well under 1 s, far inside another writer's 5 s wait, even under load.
- The first read after the upgrade takes seconds on 100,000 emails. It runs once, and only when a read filters by type
or asks for the sender summary; plain reads and syncs never wait for it.
- Fewer, larger batches finish sooner: the disk sync per commit, not the classification, is the cost.
- Warm filtered pages stay under 25 ms through the `emails_by_mail_type` index. The sender summary reads every
incoming email and counts in JavaScript: about 0.2–0.3 s at 100,000.
- A first version read each newsletter's senders again in every batch (3.9 s for the query-only read); keeping the
counts for the whole pass made it 8 times faster.

## Not measured

- Real mail: subjects, address words and schema.org markup were not checked for accuracy here. The classifier's
accuracy on real mail is the next measurement, with totals only.
- Stores over 100,000 emails. The sender summary grows with the store; past about 500,000 emails it may need its
counts kept in SQL.
- Bodies and attachments: the synthetic mail had none, so attachment parts were never read.
- What version 76's 14 new triggers add to a mail sync: there is no version 75 baseline run on the same data.
181 changes: 181 additions & 0 deletions performance/mail/types/bench.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
// Times cli-core store version 76 on synthetic mail: typing N emails a store never typed (the first read after the
// upgrade), one batch under the write lock, warm filtered reads, the per-sender summary, a query-only open that works
// types out in memory, and what one trigger clears. Usage: node bench.mjs <cli-core checkout> [N]
import { mkdtempSync } from "node:fs"
import { loadavg, tmpdir } from "node:os"
import { join } from "node:path"

const repo = process.argv[2]
const N = Number(process.argv[3] ?? 100000)
const { openStore } = await import(join(repo, "dist/store/index.js"))
const { openCache } = await import(join(repo, "dist/store/open.js"))
const { storeMailTypes } = await import(join(repo, "dist/store/sqlite/email-types.js"))
const ME = "owner@home.example.com"
const MAIL = { provider: "email", account: ME }
const NOW = Date.parse("2026-11-25T12:00:00Z")
const say = (line) => process.stdout.write(`${line}\n`)

const time = async (label, work) => {
const start = performance.now()
const result = await work()
say(`${label}: ${Math.round(performance.now() - start)} ms`)
return result
}

const ONE_CLICK = { "list-unsubscribe": true, "list-unsubscribe-post": true }

// About the mix of a real inbox: most mail is lists and shops, a fifth is people.
const emailOf = (n) => {
const at = NOW - n * 60_000
const base = { externalId: `<m${n}@bench.example.com>`, sentAt: at, receivedAt: at, bodyText: null }
const to = [{ address: ME, name: null }]
const slot = n % 20
if (slot < 8) {
const list = n % 200
return {
...base,
subject: `Issue ${n}`,
from: { address: `editor@list${list}.example.com`, name: `List ${list}` },
to,
headers: { "list-id": `list${list}.example.com`, "list-unsubscribe": true },
}
}
if (slot < 12) {
const shop = n % 300
return {
...base,
subject: `Winter sale ${n}: 30% off`,
from: { address: `shop@shop${shop}.example.com`, name: `Shop ${shop}` },
to,
headers: ONE_CLICK,
}
}
if (slot < 15) {
const shop = n % 300
return {
...base,
subject: `Thank you for your order #${n}`,
from: { address: `shop@shop${shop}.example.com`, name: `Shop ${shop}` },
to,
}
}
if (slot === 15)
return {
...base,
subject: "New sign-in to your account",
from: { address: `security@bank${n % 50}.example.com`, name: "Bank" },
to,
}
if (slot === 16)
return {
...base,
subject: `Re: plan ${n}`,
from: { address: ME, name: "Me" },
to: [{ address: `person${n % 2000}@firm${n % 300}.example.com`, name: null }],
outgoing: true,
}
return {
...base,
subject: `Hello ${n}`,
from: { address: `person${n % 2000}@firm${n % 300}.example.com`, name: `Person ${n % 2000}` },
to,
}
}

const seeded = async () => {
const path = join(mkdtempSync(join(tmpdir(), "mail-types-")), "store.db")
const store = await openStore({ path })
const accountId = await store.accounts.saveAccount(MAIL, { name: null })
for (let at = 0; at < N; at += 2000) {
const threads = []
for (let t = at; t < Math.min(N, at + 2000); t += 100)
threads.push({
accountId,
externalId: `t${t}`,
now: NOW,
emails: Array.from({ length: Math.min(100, N - t) }, (_, i) => emailOf(t + i)),
})
await store.mail.saveThreads(threads)
}
return { store, path }
}

say(
`node ${process.version}, N = ${N}, load ${loadavg()
.map((x) => x.toFixed(1))
.join(" ")}`,
)
const { store, path } = await time(`seed ${N} emails`, seeded)
const db = await openCache(path)
const untyped = () => Number(db.prepare("SELECT count(*) AS n FROM emails WHERE mail_type IS NULL").get().n)
say(`untyped before the first read: ${untyped()}`)

// 1. A query-only open of the untyped store: types worked out in memory for the read, nothing kept.
await store.close()
{
const readOnly = await openStore({ path, readOnly: true })
await time("query-only open, untyped: emails types:[order], first 50", () =>
readOnly.mail.emails({ types: ["order"], limit: 50 }),
)
await time("query-only open, untyped: mailSenders reach:broadcast", () =>
readOnly.mail.mailSenders({ reaches: ["broadcast"], limit: 50 }),
)
await readOnly.close()
}
const writer = await openStore({ path })

// 2. The first read that asks: every email typed, a batch of 5,000 per write.
await time(`first read: types for ${N} emails, then emails types:[order], first 50`, () =>
writer.mail.emails({ types: ["order"], limit: 50 }),
)
say(`untyped after: ${untyped()}`)

// 3. One batch under the lock: 5,000 emails cleared, then worked out again by the same writer function.
db.prepare("UPDATE emails SET mail_type = NULL WHERE id IN (SELECT id FROM emails ORDER BY id LIMIT 5000)").run()
const raw = await openCache(path)
await time("one batch of 5,000 under the write lock", () => storeMailTypes(raw))
raw.close()

// 4. Warm reads.
await time("warm emails types:[order], first 50", () => writer.mail.emails({ types: ["order"], limit: 50 }))
await time("warm emails types:[newsletter] reaches:[broadcast], first 50", () =>
writer.mail.emails({ types: ["newsletter"], reaches: ["broadcast"], limit: 50 }),
)
await time("warm emails, no filter, first 50", () => writer.mail.emails({ limit: 50 }))
const subs = await time("mailSenders reach:broadcast, first 50", () =>
writer.mail.mailSenders({ reaches: ["broadcast"], limit: 50 }),
)
say(`senders with broadcast mail: ${subs.total}`)
const all = await time("mailSenders, all, first 50", () => writer.mail.mailSenders({ limit: 50 }))
say(`senders: ${all.total}`)
const counts = db.prepare("SELECT mail_type, count(*) AS n FROM emails GROUP BY 1 ORDER BY 2 DESC").all()
say(`types: ${counts.map((row) => `${row.mail_type} ${row.n}`).join(", ")}`)

// 5. A trigger: the owner's first mail to a sender clears that sender's typed mail.
const accountId = Number(db.prepare("SELECT id FROM accounts LIMIT 1").get().id)
await time("owner's first mail to shop8: save, triggers included", () =>
writer.mail.saveThread({
accountId,
externalId: "reply",
now: NOW,
emails: [
{
externalId: "<reply@bench.example.com>",
subject: "Question",
from: { address: ME, name: "Me" },
to: [{ address: "shop@shop8.example.com", name: null }],
sentAt: NOW,
receivedAt: NOW,
bodyText: null,
outgoing: true,
},
],
}),
)
say(`cleared by it: ${untyped()}`)

// 6. A rules change: every type worked out again.
db.prepare("DELETE FROM store_settings WHERE key = 'mail.type_rules'").run()
await time(`rules changed: ${N} emails typed again`, () => writer.mail.emails({ types: ["order"], limit: 50 }))
await writer.close()
db.close()