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
3 changes: 3 additions & 0 deletions performance/mail/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ Measurements of reading a mailbox into the shared store with memo.
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).
- [rules](rules/README.md): what mail sorting rules cost cli-core's store (store version 77) — 50 rules add about 0.35 s
per 100,000 emails typed, a `gmail.com` rule over 30,000 emails applies in about 1 s plus 1.5–2 s on the next typed
read, and moving 500 senders to bots takes 4–6 s (2026-11-25).
79 changes: 79 additions & 0 deletions performance/mail/rules/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Mail sorting rules: what a rule costs the store

## Why it was run

The owner wants to correct how mail is sorted, and to name the scope of each correction: this mail, this list, this
address or this domain, for past mail too or only for new mail (contact-kinds plan in cli-core
[#3323](https://github.com/WireCatLabs/cli-core/pull/3323), section "Mail categories"; owner's rulings 2026-11-25).
cli-core store version 77 keeps these rules in one table and checks them, in a fixed order, before the header
classifier of version 76 ([types](../types/README.md)). A rule change clears the stored types it affects, and the next
read that filters by type works them out again.

Two questions:

1. What does the rule check add to the first typed read, which types every email?
2. How long does a domain rule take to apply to past mail: on a company domain, on a free-mail domain (`gmail.com`,
allowed only after a dry run), and when it moves a domain's senders to bots?

The answers decided whether rules can stay in the lazy type pass, or need types worked out in SQL.

## 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
6 to 17 and wrote to the same disk. Every commit syncs to disk, so times that include a write varied a lot.
- Code: cli-core branch `feat/mail-rules` (store version 77), built with `pnpm build`.
- Data, all synthetic: 100,000 emails from 20,000 sender addresses, saved through `store.mail.saveThreads`, 100 per
thread. 30% of the senders are on `gmail.com` (6,000 addresses, 30,000 emails), 500 on one shop domain, the rest
spread over 2,000 company domains. 30% of the mail has a List-Id, 10% an order subject. No bodies.
- The 50 rules: 20 address, 20 domain, 5 List-Id and 5 subject rules, each setting a type.

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

## Results

Runs 2 to 4 below. Run 1 put the company domains under `example.com`, which the Public Suffix List folds into one
registrable domain, so each "company" rule covered 14,000 addresses; its numbers are left out. Run 2's in-memory pass
with no rule ran first and cold; runs 3 and 4 take the best of three after a warm-up. Runs 2 and 3 moved a rule's
senders in the same write as the rule; run 4 is the shipped code, which moves them 100 per write.

| Step | Run 2 | Run 3 | Run 4 |
| --- | ---: | ---: | ---: |
| type all 100,000 in memory, no rule | 1,383 ms (cold) | 560 ms | 484 ms |
| type all 100,000 in memory, 50 rules | 842 ms | 915 ms | 579 ms |
| first typed read, no rule: 100,000 typed and kept | 7.4 s | 9.2 s | 3.4 s |
| first typed read, 50 rules: 100,000 typed and kept | 7.5 s | 18.1 s | 8.2 s |
| 50 rules added, one by one | 15.5 s | 17.4 s | 7.8 s |
| company domain rule (7 addresses, 35 emails): add | 335 ms | 726 ms | 516 ms |
| next typed read | 223 ms | 356 ms | 315 ms |
| `gmail.com` rule: dry run (6,000 addresses, 30,000 emails) | 188 ms | 143 ms | 220 ms |
| `gmail.com` rule: add with its confirm, 29,800 types cleared | 1.2 s | 1.0 s | 1.3 s |
| next typed read: 29,800 typed again | 2.1 s | 1.5 s | 2.8 s |
| undo of the `gmail.com` rule | 1.2 s | 1.6 s | 0.9 s |
| next typed read | 2.1 s | 2.3 s | 2.2 s |
| sender rule: 500 senders of one domain moved to bots | 6.1 s (one write) | 4.0 s (one write) | 5.6 s (5 writes) |
| next typed read | 672 ms | 530 ms | 317 ms |
| removal of that rule: 500 senders moved back (0 bots left) | 577 ms | 368 ms | 868 ms |

## What it showed

- The rule check costs 0.1 to 0.35 s per 100,000 emails in memory with 50 rules (484 → 579 ms and 560 → 915 ms,
best of 3). A first typed read takes 3 to 18 s either way: the disk sync of each batch's commit, not the rules, is
the cost, and the spread is the load of the other runs.
- Each rule added takes 0.15 to 0.35 s on 100,000 emails: the preview and the clear each read the emails in its scope,
and a List-Id or subject rule reads every email.
- Applying a domain rule to past mail is cheap for a company domain (under 1 s to add, then a fraction of a second to
type again). On a free-mail domain with 30,000 emails it is about 1 s to add and 1.5 to 2.8 s on the next typed read.
Undo costs the same as the add.
- Moving senders is the slow part: each sender goes through `moveToBot`, about 8 to 12 ms each. In one write, 500
senders held the write lock for 4 to 6 s, past the 5 s another writer waits. So the shipped code moves 100 per
write: about 1 s of lock each, the same 5.6 s in total. A sender rule on a free-mail domain with 6,000 senders would
take about a minute in total by the same rate (an estimate, not measured).

## Not measured

- Real mail: how often the owner's rules disagree with the classifier on real data.
- A free-mail domain rule that moves its 6,000 senders.
- Mail sync with sender rules live: sync settles the senders of each saved batch, and its cost per batch was not timed.
- Stores over 100,000 emails, and more than 50 rules.
147 changes: 147 additions & 0 deletions performance/mail/rules/bench.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// Times cli-core store version 77 mail sorting rules on synthetic mail: what the rule check adds to typing every
// email, and how long a domain rule takes to apply to past mail (a type rule on a company domain and on a free-mail
// domain, and a rule that moves a domain's senders to bots). Usage: node bench.mjs <cli-core checkout> [N] [senders]
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 SENDERS = Number(process.argv[4] ?? 20000)
const { openStore } = await import(join(repo, "dist/store/index.js"))
const { openCache } = await import(join(repo, "dist/store/open.js"))
const { typesOf } = 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
}

// 30% of senders on one free-mail domain, 500 on one shop, the rest over 2,000 company domains.
const FREE = Math.round(SENDERS * 0.3)
const SHOP = 500
const addressOf = (s) =>
s < FREE ? `user${s}@gmail.com` : s < FREE + SHOP ? `desk${s}@bigshop.example` : `person${s}@org${s % 2000}.example`

const emailOf = (n) => {
const at = NOW - n * 60_000
const s = n % SENDERS
const list = n % 10 < 3
return {
externalId: `<m${n}@bench.example.com>`,
subject: list ? `Issue ${n}` : n % 10 === 3 ? `Your order #${n}` : `Hello ${n}`,
from: { address: addressOf(s), name: `Sender ${s}` },
to: [{ address: ME, name: null }],
sentAt: at,
receivedAt: at,
bodyText: null,
headers: list ? { "list-id": `list${n % 300}.example.com`, "list-unsubscribe": true } : {},
}
}

const seeded = async () => {
const path = join(mkdtempSync(join(tmpdir(), "mail-rules-")), "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}, senders = ${SENDERS}, load ${loadavg()
.map((x) => x.toFixed(1))
.join(" ")}`,
)
const { store, path } = await time(`seed ${N} emails from ${SENDERS} senders`, seeded)
const db = await openCache(path)
const count = (sql) => Number(db.prepare(sql).get().n)
const ids = db
.prepare("SELECT id FROM emails ORDER BY id")
.all()
.map((row) => Number(row.id))

// The fastest of three, after one warm-up pass, so the JIT and the page cache do not favour the second measurement.
const inMemory = async (label) => {
const pass = () => {
const start = performance.now()
const senders = new Map()
for (let at = 0; at < ids.length; at += 5000) typesOf(db, ids.slice(at, at + 5000), senders)
return performance.now() - start
}
pass()
const best = Math.min(pass(), pass(), pass())
say(`${label}: typesOf over all ${N} in memory, nothing kept, best of 3: ${Math.round(best)} ms`)
}

// 1. The rule check's cost, apart from disk: typing in memory with no rule, then with 50.
await inMemory("no rules")
await time("first typed read, no rules (types kept)", () => store.mail.emails({ types: ["order"], limit: 50 }))
const rules = [
...Array.from({ length: 20 }, (_, i) => ({ scope: "address", value: addressOf(FREE + SHOP + i * 37) })),
...Array.from({ length: 20 }, (_, i) => ({ scope: "domain", value: `org${i * 13}.example` })),
...Array.from({ length: 5 }, (_, i) => ({ scope: "list", value: `list${i * 7}.example.com` })),
...Array.from({ length: 5 }, (_, i) => ({ scope: "subject", value: `winter sale ${i}` })),
]
await time("50 rules added (address, domain, list, subject)", async () => {
for (const rule of rules) await store.mail.sorting.add({ ...rule, mailType: "promotion", applyTo: "all" }, "owner")
})
await inMemory("50 rules")
db.prepare("UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL").run()
await time("first typed read, 50 rules (types kept)", () => store.mail.emails({ types: ["order"], limit: 50 }))
say(`typed by a rule: ${count("SELECT count(*) AS n FROM emails WHERE type_signal LIKE 'rule:%'")}`)

// 2. A type rule on a company domain, applied to past mail.
const company = "org1999.example"
const small = await time(`domain rule ${company}: add, past mail cleared`, () =>
store.mail.sorting.add({ scope: "domain", value: company, mailType: "bill", applyTo: "all" }, "owner"),
)
say(` touches ${small.preview.addresses} addresses, ${small.preview.emails} emails`)
await time(" next typed read", () => store.mail.emails({ types: ["bill"], limit: 50 }))

// 3. A type rule on the free-mail domain: dry run, then the add with its confirm, then the next read.
const free = { scope: "domain", value: "gmail.com", mailType: "newsletter", applyTo: "all" }
const dry = await time("free-mail domain rule gmail.com: dry run", () =>
store.mail.sorting.add(free, "owner", { dryRun: true }),
)
say(` touches ${dry.preview.addresses} addresses, ${dry.preview.emails} emails, retypes ${dry.preview.retyped}`)
await time(" add with confirm, past mail cleared", () =>
store.mail.sorting.add(free, "owner", { confirm: dry.preview.confirm }),
)
say(` untyped after the add: ${count("SELECT count(*) AS n FROM emails WHERE mail_type IS NULL")}`)
await time(" next typed read: retyped", () => store.mail.emails({ types: ["newsletter"], limit: 50 }))

// 4. Undo of that rule: its mail typed again without it.
await time("undo the gmail.com rule", () => store.mail.sorting.undo("owner"))
await time(" next typed read", () => store.mail.emails({ types: ["newsletter"], limit: 50 }))

// 5. A rule that moves a domain's 500 senders to bots, each through moveToBot.
const bots = await time(`sender rule bigshop.example → bot: ${SHOP} senders moved`, () =>
store.mail.sorting.add({ scope: "domain", value: "bigshop.example", sender: "bot", applyTo: "all" }, "owner"),
)
say(` moved ${bots.preview.senders}, bots now ${count("SELECT count(*) AS n FROM sender_bots")}`)
await time(" next typed read (bot moves cleared their mail's types)", () =>
store.mail.emails({ types: ["order"], limit: 50 }),
)
await time(" remove it: senders moved back", () => store.mail.sorting.remove(bots.rule.id, "owner"))
say(
` bots holding an identity after the removal: ${count("SELECT count(DISTINCT bot_id) AS n FROM sender_bot_identities")}`,
)

await store.close()
db.close()