Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Inbound pipeline

Binding for implementation. This page takes a message from Cloudflare Email Routing, or from Amazon SES for domains with inbound = ses, to a stored, threaded, indexed and evented row in the identity’s mailbox.

RequirementsFR-IN-1 … FR-IN-15, FR-SCR-1 … FR-SCR-12, FR-CAL-1 … FR-CAL-14 (the inbound side), FR-THR-1, FR-THR-2, FR-ADR-3, FR-ADR-5, FR-TEN-3, FR-DLV-5, FR-DOM-9, FR-DOM-10, FR-DOM-11, FR-SRCH-2, FR-SRCH-4, NFR-REL-1, NFR-REL-2, NFR-REL-3
Edge casesA2, A4, A6, A9, A10, A15, A16, B1–B14, C9, D1–D5, D7, D9, D11–D14, E4, E5, E9, E10 and E13 (the ledger gate, Service sign-up ledger), I9, I10, J1–J3, J7, L3, N1–N7, N12, N18, N19, N27, N28
Codecrates/worker/src/email.rs, handlers/{wait.rs, threads.rs, messages.rs, quarantine.rs}, handlers/hooks_ses.rs, crons/ses_backstop.rs, inbound/sources/{routing.rs, ses.rs}, inbound/role_mail.rs, consumers/inbound.rs, consumers/index.rs, mailbox/{ingest.rs, threads.rs, messages.rs, read.rs, attachments.rs, outbox.rs}; crates/core/src/{mime/, sanitize.rs, text.rs, quote.rs, refs/, classify.rs, auth.rs, trust.rs, attach.rs, sns.rs}
RelatedThreading, Outbound (delivery events, loopback), Search (indexing), Triage, Webhooks, Domains on any DNS host (SES receiving, probes, forwarding checks)
 SMTP ─▶ Email Routing ─▶ email()                                    (Worker, per envelope recipient)
                           1 normalise recipient, strip +tag
                           1b platform domain: journal, probe, forwarding check, role names
                           2 directory lookup (cache 60 s hit / 5 s miss)
                           3 reject 550 5.1.1 / 550 5.1.6 / 550 5.2.1, or temporary failure
                           4 raw → R2  t/{ten}/i/{idn}/m/{msg}/raw.eml   (2 retries, else temporary failure)
                           5 pointer (source: routing) → pm-inbound
                                │
 SMTP ─▶ Amazon SES ─▶ S3 in/{key} + SNS ─▶ POST /hooks/ses/inbound    (and the every-minute SQS backstop)
                           verify SNS (version 2) · ses_ingest ledger, once per object and recipient
                           pointer (source: ses) → pm-inbound
                                │
                                ▼
                       pm-inbound consumer                            (Worker, one message at a time)
                           ses only: S3 → R2, directory lookup, drop unknown recipients (no bounce)
                           parse under caps · classify · DSN routing · authenticate (DoH)
                           sanitise · strip hidden text · derive text · strip quotes · refs
                           attachments: sniff, risk, TNEF, scanner · verification codes
                           D1 facts: suppressions, lists, tenant domains, co-recipients
                                │  MailboxRequest::Ingest
                                ▼
                       IdentityMailbox.ingest                         (one SQLite transaction)
                           dedupe · thread · quarantine decision · insert message, attachments,
                           FTS, refs, contacts, verifications · outbox event
                                │ after commit
                                ▼
                       consumer: attachments → R2 · pm-index jobs (attachment text, embed, triage)

Inbound sources

A domain’s inbound property decides how its mail arrives (Domains on any DNS host § 2). Both sources queue an InboundPointer whose source says where the raw message is (The pm-inbound message). From “parse” onwards the consumer runs the same pipeline for both; only the SPF input and the SES verdicts differ.

Email Routing (inbound = routing)Amazon SES (inbound = ses)
DomainsThe platform domain, cloudflare_zone, nameservers, delegated_subdomaindns_records; smtp_relay with inbound: ses
Entry pointemail(), once per envelope recipient (below)POST /hooks/ses/inbound and the every-minute SQS backstop cron; one pointer per recipient (The SES source)
Largest message25 MiB; Cloudflare rejects larger ones before the Worker runs (B1)40 MB including headers, the most a receipt rule stores in S3 (quotas, read 2026-10-09) (N5)
Unknown recipient550 5.1.1 during the SMTP sessionAccepted by SES, then dropped by the Worker without a bounce (N6)
Retired recipient550 5.1.6 during the SMTP sessionBounced 550 5.1.6 by an SES receipt rule pm-retired-{n} (N7)
SPFFrom the trusted Authentication-Results headerFrom SES’s spfVerdict

Mail on send_only domains, and on smtp_relay domains with inbound: forward, reaches the identity’s platform address through the customer’s own forwarding rule, so it arrives by Email Routing.

The email() handler

Interface

The Cloudflare message object exposes the envelope sender and recipient, the headers, the raw stream and its size, setReject (documented as a permanent SMTP error) and forward; it does not expose the client IP (email handler, read 2026-10-09). platform adapts worker::ForwardableEmailMessage (0.8.7) to:

// crates/platform/src/email.rs
pub trait InboundEmail {
    fn envelope_from(&self) -> String;                 // MAIL FROM, "" for the null sender
    fn envelope_to(&self) -> String;                   // RCPT TO, as received (with +detail)
    fn header(&self, name: &str) -> Option<String>;    // first value of a header, from message.headers
    fn raw_size(&self) -> u64;
    async fn read_raw(&self) -> PResult<JsBuffer>;     // reads the stream once into a JS ArrayBuffer
    fn set_reject(&self, reason: &str);
    async fn forward(&self, to: &str) -> PResult<()>;
}

// crates/worker/src/email.rs
pub enum TempFail { Storage, Queue, TenantSuspended, RoleRate, Busy, Check }
pub async fn handle_email<P: Platform>(p: &P, msg: &impl InboundEmail) -> Result<(), TempFail>;

The email entry point (generated by platform::export_worker!, Rust workspace) calls handle_email. Ok(()) accepts the message (after a set_reject, Cloudflare refuses it). Err(TempFail) is raised to the runtime as a thrown exception (logged with the TempFail variant, never with the address). Spike S2 records what the sending MTA sees in that case; the design requires a 4xx temporary failure. If S2 shows otherwise, the S2 fallback is throw only: the handler still retries the R2 write inside the handler and then throws, and a “Spike result” note here records the reply the sender actually sees. Nothing is forwarded to a backup address, because setup registers no Email Routing destination address (Design › Spikes).

Steps

  1. Start. Generate req_…. Record received_at = clock.now_ms().

  2. Normalise the recipient with core::address::parse_envelope(envelope_to):

    • trim whitespace and surrounding <>; split at the last @;
    • domain: strip a trailing dot, convert to an IDNA A-label, lower-case;
    • local part: if it contains a non-ASCII byte, the address cannot exist (SMTPUTF8 local parts are refused at creation, FR-ADR-7), so go to step 5 with “unknown”;
    • lower-case the local part (A1: matching is case-insensitive, dots are significant);
    • split at the first +: base_local before it, detail after it (empty detail = none). Usernames cannot contain +, so the first + is always the separator. Cloudflare preserves the +detail part in message.to when sub-addressing is enabled (routing addresses, read 2026-10-09).
    • base = base_local@domain. The detail is kept for the thread token check in the consumer.
  3. Platform-domain special addresses (only when domain = PM_PLATFORM_DOMAIN):

    base_localHandling
    journal, with a detailOutbound Message-ID learning (spike S7 strategy B). Handled entirely here, see Outbound. Nothing is stored; the handler returns Ok
    pm-probe, with a detailThe alignment probe of an smtp_relay domain (Domains on any DNS host § 5.3, N18); the detail is the probe token. The handler copies the (small) message into wasm memory, checks that the From header still names the domain’s probe_from, and evaluates DMARC for that domain with steps 1–6 of Authentication verdict (an aligned DKIM signature, or SPF on an aligned MAIL FROM). It sends { token, from_unchanged, dkim_d, dmarc } to that domain’s DomainMonitor, which records the probe result. Nothing is stored or counted, and the handler returns Ok, also for an unknown or expired token. If the monitor cannot be reached, Err(TempFail::Check), so the relay retries
    An RFC 2142 operational name (postmaster, abuse, security, hostmaster, webmaster, noc)Relayed to PM_SECURITY_CONTACT through the system identity, as Role mail relay specifies. If PM_SECURITY_CONTACT is unset, is not an email address (bare or mailto:), or routes back into this deployment, reject 550 5.1.1. These names are reserved on the platform domain, so no identity can own them (A4)
    Any other reserved role name (info, sales, support, marketing and the rest of the RFC 2142 list)No special handling: no identity can own them, so the directory lookup (step 4) finds nothing and step 5 rejects 550 5.1.1

    Forwarding check (Domains on any DNS host § 4.4, N12). Before the rows above, a message to any platform-domain address whose header X-Pylota-Identity-Check holds a token is offered to that token’s DomainMonitor. When the token is pending and the envelope recipient is the platform address of the identity that owns the tested address, the monitor sets the address’s forwarding to ok and forwarding_checked_at; the message is not stored and the handler returns Ok. An unknown or expired token changes nothing, and the message continues to step 4 like any other mail. This token is the only proof that mail came through the customer’s forwarder: ordinary mail never changes forwarding (Multiple identities in one tenant).

    Check tokens. Probe and forwarding-check tokens have the form {domain ULID, lower case}.{16 random Crockford base32 characters} (at most 52 characters with the pm-probe+ prefix). The first part names the DomainMonitor that holds the pending token in its storage, for 15 minutes (probe) or 10 minutes (forwarding check); the random part is compared in constant time. Usernames starting with pm-probe or pm-bounce are reserved (Identities › Username validation), so no address row can collide with the probe address or the SES MAIL FROM name.

    Tenant-domain role addresses (any other domain, and base_local is postmaster or abuse; both are reserved on tenant domains, so no address row can exist): look up the domain’s tenant and its owner (SELECT d.id, d.tenant_id, d.monitor_do_id, u.email FROM domains d LEFT JOIN members m ON m.tenant_id = d.tenant_id AND m.role = 'owner' LEFT JOIN users u ON u.id = m.user_id WHERE d.name = ?1 AND d.kind <> 'platform' AND d.state NOT IN ('removing', 'removed')). With an owner whose address does not route back into this deployment, relay the message to the owner as Role mail relay specifies. Otherwise handle it as the platform-domain row above (PM_SECURITY_CONTACT, else 550 5.1.1). The other role names (support, sales, info and the rest) are ordinary addresses on tenant domains and go through steps 4 and 5 (Identities and domains › Username validation).

    Role mail relay

    Role mail is attacker-reachable, so it is relayed as ordinary outbound mail of the system identity, with every control a send has, and never with forward() (which reaches only verified Email Routing destinations, and setup registers none) or a direct EMAIL binding call (A4, D14):

    1. Destination. PM_SECURITY_CONTACT (platform domain, or a tenant without a usable owner) or the tenant owner’s address. A destination routes back into this deployment when its domain is PM_PLATFORM_DOMAIN or the name of any domains row that is not removed (one D1 query, cached for 60 seconds per isolate). Such a destination is never used: the owner falls back to PM_SECURITY_CONTACT, and a PM_SECURITY_CONTACT that routes back counts as unset (idvy doctor reports it as an error, and setup refuses it).
    2. Loop guard. A message that already carries X-Pylota-Identity-Role-Hop, or whose envelope sender is the system identity’s address, is refused with set_reject("550 5.4.6 Routing loop detected").
    3. Rate limits. DomainMonitorRequest::AdmitRoleMail { sender_hash, now } on the destination domain’s DomainMonitor (the platform domain’s for operational names) admits at most 30 role messages an hour per domain and 5 an hour per envelope sender (sender_hash = hex HMAC-SHA256(PM_HASH_KEY, lower-cased envelope sender, or <> for the null sender)), in hourly windows kept in the monitor’s storage for 48 hours. Limited → Err(TempFail::RoleRate), so a real sender retries later; an unreachable monitor → Err(TempFail::Check).
    4. Accept. Write the raw message to inbound-staging/role/{yyyy}/{mm}/{dd}/{ulid}.eml (step 6’s retries; the 15-day lifecycle rule on inbound-staging/ is the backstop), queue InboundJob::RoleMail with the destination, the domain and base_local, and return Ok. A failed write or enqueue is Err(TempFail::Storage) or Err(TempFail::Queue) as in steps 6 and 7.
    5. Relay (in the pm-inbound consumer). Authenticate the message with steps 1–7 of Authentication verdict and classify its attachments with Attachment safety. Then submit, through the system identity’s internal submit path (MailboxRequest::Submit on its mailbox, kind: transactional), a new message to the destination: subject "[{domain}] {base_local} mail: " + original subject (control characters removed, cut to 998 characters) and a short text body naming the original sender, date and verdict. Before submitting, it asks the default tenant’s TenantQuota for the system-mail budget (QuotaRequest::SystemMail { class: Notification, keys: [destination hash, "role:" + domain], day }, Cloud sign-up § 10.2): role relays share the notification part of the system identity’s day and may use at most 5% of that day on their own, so a flood of mail to postmaster@ across many domains can never spend the share kept for sign-in mail. On Spent the pointer is retried with a 1-hour delay; one still refused 24 hours after it was received is dropped and counted in role_mail_failed_total{reason="budget"}. Its internal submit input carries role_relay: true, which makes the service add X-Pylota-Identity-Role-Hop: 1 and Auto-Submitted: auto-generated (Outbound › Headers); like list_unsubscribe, the field exists only on the internal input. The original is attached as message/rfc822 (at most 4 MiB) only when the destination is the deployment’s PM_SECURITY_CONTACT (destination_kind = "security_contact"), its verdict is pass, none of its attachments has a risk and none is infected. A workspace owner (tenant_owner) gets only the header block as text/rfc822-headers (at most 64 KiB) and the first 2,000 characters of its text with every URL defanged (hxxps://…), so mail from no-reply@ of the platform domain never carries a stranger’s message or clickable links to a workspace owner. The submit’s Idempotency-Key is role:{raw_sha256}:{hex HMAC-SHA256(PM_HASH_KEY, destination)[..16]}, so a redelivered copy relays once. The system identity’s policy applies as to any send: suppressions, its daily cap, delivery events and its sent copy. A submit error (for example a suppressed destination or a spent cap) is final for that message: it is counted in role_mail_failed_total{reason} and the staging object is deleted; the sender already had its 250.
    6. Delete the staging object and ack. Nothing is stored in a tenant mailbox.

    For the SES source, the consumer runs steps 1–3 and 5–6 on the staged object directly (SES has already accepted the message, so a refusal there is a drop, counted in role_mail_failed_total{reason}, never a bounce).

  4. Directory lookup. The isolate keeps an LRU cache (thread_local, 10,000 entries) keyed by base: hits and misses are both cached for 60 seconds (a negative entry only exists for an address that received mail before it was created, so the delay it adds is rare). Dictionary guard (A16): the isolate also counts, per recipient domain, the lookups that ended in a miss during the current second; once a domain has 20, further uncached addresses on that domain get Err(TempFail::Busy) (a temporary failure, so a real sender retries) for the rest of that second, without a D1 query, and inbound_dictionary_guard_total is incremented. Cached hits are unaffected. On a cache miss it runs, with a 2-second deadline:

    SELECT a.status AS address_status, a.identity_id, a.tenant_id, i.mailbox_do_id,
           i.status AS identity_status, t.status AS tenant_status, t.mode, t.suspended_at
    FROM addresses a
    JOIN identities i ON i.id = a.identity_id
    JOIN tenants t    ON t.id = a.tenant_id
    WHERE a.address = ?1;
    -- no row:
    SELECT 1 FROM address_tombstones WHERE address_hash = ?1;   -- hex HMAC-SHA256(PM_HASH_KEY, base)
    

    A tombstone and an unknown address get the same answer, so an erased address is indistinguishable from one that never existed (FR-ADR-5). If D1 errors or the deadline passes, go to Staging when the directory is unavailable (J7).

  5. Decide (A6, FR-IN-2, FR-TEN-3):

    Condition (first match)Action
    No row, or tombstoned, or non-ASCII local partset_reject("550 5.1.1 Recipient address rejected: user unknown")
    address_status = 'pending'550 5.1.1 (same text)
    address_status = 'retired'set_reject("550 5.1.6 Recipient address has moved; contact the sender by other means")
    identity_status IN ('deleting','deleted') or tenant_status IN ('erasing','erased')550 5.1.1
    tenant_status = 'suspended' and now - suspended_at < 5 daysErr(TempFail::TenantSuspended) (a temporary failure: setReject is permanent only, so the handler throws instead; S2 records the exact reply the sender sees)
    tenant_status = 'suspended' and now - suspended_at ≥ 5 daysset_reject("550 5.2.1 Mailbox disabled, not accepting messages")
    Otherwise (active/retiring address, active/paused identity, active tenant)Accept: continue

    A paused identity still receives (A7, FR-IDN-3).

  6. Write raw to R2 before acknowledging (FR-IN-1, J1):

    • message_id = ids.new_id(Msg); key t/{tenant_id}/i/{identity_id}/m/{message_id}/raw.eml.
    • raw = msg.read_raw() reads the stream once into a JS ArrayBuffer (≤ 25 MiB; Cloudflare rejects larger messages before the Worker runs, B1; the SES source allows 40 MB, Inbound sources). It is not copied into wasm memory. The bytes are buffered, rather than streamed straight to R2, so the write can be retried.
    • blobs.put(key, BlobBody::Js(raw), meta) with content_type = "message/rfc822" and custom metadata tenant, identity, message. Up to 3 attempts, waiting 100 ms and then 300 ms.
    • After the third failure return Err(TempFail::Storage). Never set_reject for our own failure.
  7. Queue the pointer. Send InboundJob::Message (below) to pm-inbound, up to 3 attempts (100 ms, 300 ms). If all fail, delete the R2 object (best effort), increment inbound_orphan_raw_total if the delete also fails, and return Err(TempFail::Queue): the sender retries, and a later copy is processed normally.

  8. Return Ok(()). Log inbound_accepted with tenant, identity, message ID, size and the hashed recipient (never the clear address).

Staging when the directory is unavailable

When the D1 lookup in step 4 fails transiently (J7), the handler never rejects for our own outage. It stages only mail that could be routable: the recipient domain must be in the isolate’s list of deployment domains (the platform domain and every domains name that is not removed, refreshed every 5 minutes; an isolate that never loaded it stages any domain), and the local part must be a valid username form (^[a-z0-9][a-z0-9._-]{0,63}$). Anything else gets 550 5.1.1 without staging, so a dictionary attack during an outage is not answered with a 250 for every guess (A16). The dictionary guard of step 4 applies here too.

  1. Key inbound-staging/{yyyy}/{mm}/{dd}/{ulid}.eml (UTC date, a bare ULID), custom metadata envelope_to_hash = hex HMAC-SHA256(PM_HASH_KEY, base), and envelope_from, envelope_to and received_at, from which the global staging step rebuilds the pointer if it was lost (Privacy § 5.3). They live as long as the object, at most 15 days.
  2. Write it as in step 6 (same retries; failure → Err(TempFail::Storage)).
  3. Queue InboundJob::Staged; failure → delete the object, Err(TempFail::Queue).
  4. Return Ok(()). The R2 lifecycle rule deletes inbound-staging/ objects after 15 days as a backstop: longer than the 14 days a pointer can wait in pm-inbound-dlq, so a pointer redriven on its last day still finds its object (J7, Privacy § 5.3).

The pm-inbound message

// crates/worker/src/consumers/inbound.rs — JSON, "v": 1, never contains content
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum InboundJob {
    Message(InboundPointer),
    Staged(StagedPointer),
    Reparse(ReparsePointer),
    RoleMail(RoleMailPointer),              // Role mail relay; never stored in a mailbox
}

#[derive(Serialize, Deserialize)]
pub struct InboundPointer {
    pub v: u8,                          // 1
    pub source: RawSource,              // where the raw message is (below)
    pub message_id: Option<String>,     // msg_… allocated in email(); None from SES until the consumer resolves it
    pub tenant_id: Option<String>,      // as message_id
    pub identity_id: Option<String>,    // as message_id
    pub r2_key: Option<String>,         // t/{ten}/i/{idn}/m/{msg}/raw.eml; as message_id
    pub raw_size: u64,                  // 0 from SES until the object is fetched
    pub envelope_from: String,          // "" for the null sender; SES: mail.source
    pub envelope_to: String,            // normalised, including +detail; SES: one receipt.recipients entry
    pub received_at: i64,               // Unix ms, our clock when the pointer was queued
    pub request_id: String,
    pub loopback: Option<LoopbackSource>,   // set only by the outbound loopback transport (L3)
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RawSource {
    Routing,                            // {"type":"routing"}: email() (and loopback); raw already at r2_key
    Ses {                               // {"type":"ses", …}: the object in/{key} in the SES bucket
        bucket: String, key: String,    // key = mail.messageId
        spf: SesVerdict, dkim: SesVerdict, dmarc: SesVerdict, spam: SesVerdict, virus: SesVerdict,
        dmarc_policy: Option<String>,   // present when DMARC failed
    },
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SesVerdict { Pass, Fail, Gray, ProcessingFailed }   // the SES verdict "status" values

#[derive(Serialize, Deserialize)]
pub struct LoopbackSource { pub tenant_id: String, pub identity_id: String, pub message_id: String }

#[derive(Serialize, Deserialize)]
pub struct StagedPointer {
    pub v: u8, pub staging_key: String, pub raw_size: u64,
    pub envelope_from: String, pub envelope_to: String, pub received_at: i64, pub request_id: String,
}

#[derive(Serialize, Deserialize)]
pub struct ReparsePointer {
    pub v: u8, pub job_id: String, pub tenant_id: String, pub identity_id: String,
    pub message_id: String, pub parser_version: u32,
}

#[derive(Serialize, Deserialize)]
pub struct RoleMailPointer {
    pub v: u8, pub staging_key: String,     // inbound-staging/role/…, or inbound-staging/ses/{key} for SES
    pub domain: String, pub base_local: String,         // postmaster, abuse, security, …
    pub destination_kind: String,                       // "security_contact" | "tenant_owner"
    pub tenant_id: Option<String>,                      // the domain's tenant, for "tenant_owner"
    pub raw_size: u64, pub envelope_from: String, pub received_at: i64, pub request_id: String,
}

The destination address itself is never in the queue message: the consumer resolves it again (PM_SECURITY_CONTACT, or the owner query above).

The SES source

For domains with inbound = ses (FR-DOM-9). The set-up, the receipt rules and the ledger are specified in Domains on any DNS host § 4.5; this section is how the pipeline uses them. Spike S11 must pass for it to ship in v1.0.

Arrival. SES stores the message as in/{key} in PM_SES_INBOUND_BUCKET (key = mail.messageId) and publishes a notification to PM_SES_INBOUND_TOPIC_ARN. POST /hooks/ses/inbound (handlers/hooks_ses.rs) receives it by push within seconds. The every-minute cron (crons/ses_backstop.rs) drains the SQS backstop PM_SES_INBOUND_QUEUE_URL and passes each notification to the same handler, which:

  1. verifies the SNS message with core::sns: SignatureVersion must be 2 (version 1 is refused), the certificate host sns.{PM_SES_REGION}.amazonaws.com, the topic PM_SES_INBOUND_TOPIC_ARN, and Timestamp within one hour (14 days on the backstop path). Failure → 403 invalid_signature and ses_sns_rejected_total (N1, N2);
  2. checks that the notification is Received with an S3 action on that bucket;
  3. for each receipt.recipients entry, runs INSERT OR IGNORE INTO ses_ingest (status queued) and queues an InboundPointer with source = ses only when a row was inserted. Duplicates from SNS retries, the backstop, or both stop here (N3);
  4. answers 200 after the enqueue, or 500 on an internal failure (SNS retries 5xx and 429).

Resolution in the consumer. An SES pointer has no tenant, identity or message ID yet. Before step 1 of the consumer:

  1. Fetch the object (GET https://{bucket}.s3.{region}.amazonaws.com/in/{key}, SigV4 with service s3) into R2 as inbound-staging/ses/{key}, unless that copy already exists. NoSuchKey while the ledger row is still queued means the lifecycle rule ran: the row becomes lost (with done_at), ses_object_lost_total is incremented, the ses_object_lost alert fires, and the pointer is acked (N4).

  2. Resolve the recipient: normalise it as in email() step 2, relay tenant-domain postmaster and abuse mail as in Role mail relay (the platform domain never uses SES), and run the directory lookup of step 4.

  3. Decide (first match):

    Directory resultAction
    No row, tombstoned, non-ASCII local part, pending address, identity deleting/deleted, tenant erasing/erasedDropped without a bounce: ledger row dropped, inbound_dropped_total{reason="unknown_recipient",source="ses"} (N6)
    The address’s domain does not have inbound = ses (the platform domain, a Cloudflare-method domain with a J5 failover identity, a send_only domain): SES accepts mail for every verified identity in the region, and delivering it would bypass Email Routing’s SMTP-time rejectsDropped without a bounce: ledger row dropped, inbound_dropped_total{reason="not_ses_domain",source="ses"} (N33, Domains on any DNS host § 4.6)
    retired addressSES normally bounces it before this point (rule pm-retired-{n}, 550 5.1.6, N7). One that still arrives (the rule is not yet updated, the address is past the 150-rule cap, or tenant policy inbound.ses_bounce_retired is false) is dropped as above
    Tenant suspendedHeld (FR-TEN-3): the ledger row becomes held, the staging copy and the S3 object are kept, and the pointer is acked. The every-minute backstop cron re-sends the pointer once the tenant is active again. After 5 days of suspension (tenants.suspended_at) the row becomes dropped, without a bounce, and inbound_dropped_total{reason="tenant_suspended",source="ses"} is incremented (Domains on any DNS host § 4.6)
    OtherwiseAllocate message_id, copy the staging object to t/{tenant_id}/i/{identity_id}/m/{message_id}/raw.eml, and continue with the consumer steps, with envelope_from = mail.source and envelope_to = the recipient. The source stays ses, so its verdicts are used

    A bounce sent after SES has accepted a message goes to whatever sender the message claims, which spam forges (backscatter), so the Worker never bounces SES mail. Email Routing domains keep the SMTP-time answers of email() step 5.

After the commit, the post-commit steps set the ledger row to done with done_at. When no row for the key is still queued or held, the consumer deletes the S3 object (DeleteObject). A pointer whose ledger row is no longer queued is acked without work: the hook inserts the row and then enqueues, which is not one transaction, so the backstop cron re-sends the pointer of any row still queued 15 minutes after received_at, and duplicates must be harmless. The 15-day lifecycle rule on inbound-staging/ removes the R2 copy, and the bucket’s 14-day lifecycle rule is the backstop for S3.

Many recipients. One SES message can name recipients on several domains, of several tenants. Each recipient is its own pointer and is resolved on its own, so tenants stay isolated (N28). Two recipients in one mailbox give one message (duplicate by hash, B14).

Verdicts. The notification is signed by our topic, so its verdicts are trusted. They feed SPF (Authentication verdict), the spam score and the quarantine decision (virus). SES’s own DKIM and DMARC results are only compared.

The pm-inbound consumer

pm-inbound has batch size 10, 10 retries and retry_delay = 120 seconds (the consumer setting that delays every retried message, Wrangler configuration, read 2026-10-10), so the ten retries of a message span about 20 minutes. The consumer processes messages one at a time (a batch could otherwise hold 250 MiB of raw mail in a 128 MB isolate) and acks each after its post-commit steps.

Poison messages. A parser panic aborts the whole invocation, and every message of the batch that was not yet acked is retried. To keep one poison message from dragging fresh ones towards the dead-letter queue, the consumer first processes the pointers whose received_at is less than 120 seconds old (they have not failed before), acking each, and only then the older ones (they may have failed before), oldest last. A message is therefore retried with its batch-mates only when they are retries too.

Steps

  1. Re-read scope from D1 (5-second deadline):

    SELECT i.status, i.mailbox_do_id, i.display_name, t.status AS tenant_status, t.mode,
           t.policy_json, t.provisional_until, t.timezone, t.name AS tenant_name
    FROM identities i JOIN tenants t ON t.id = i.tenant_id
    WHERE i.id = ?1 AND i.tenant_id = ?2;
    

    It reads policy_json and provisional_until, and computes the effective policy (step 5) with the provisional overlay when it is set (Agent self-sign-up §4.2).

    An SES pointer is resolved first (The SES source). Identity deleting/deleted, or tenant erasing/erased (the cache in email() may have been up to 60 seconds stale): delete the raw object, ack, count inbound_dropped_total{reason="identity_gone",source} (source is routing or ses). For a Staged pointer, run the directory query of email() step 4 now: unknown, pending or retired → delete the staging object, ack, count inbound_staged_unroutable_total (the sender already got a 250; no bounce is sent, to avoid backscatter); routable → copy the object to its final key, delete the staging object, and continue as a Message.

  2. Fetch raw from R2 into wasm memory. A missing object is either already processed and erased, or a bug: ask the mailbox whether message_id exists; ack either way and count inbound_raw_missing_total when it does not.

  3. Hash: raw_sha256 = hex(sha256(raw)).

  4. Parse under caps (see Parsing). Degraded mode: workers-rs does not expose the queue’s attempt count, and a parser panic aborts the invocation before anything is recorded, so the consumer counts attempts itself: just before parsing it calls MailboxRequest::NoteParseAttempt { message_id }, which increments meta['parse:{msg}'] and returns the new value (ingest deletes the key; the daily maintenance alarm deletes keys older than a day). From the third attempt (two have failed, about 4 minutes after the first because of retry_delay) the consumer parses headers only, stores the message with parse_degraded, and never drops it (FR-IN-3). A queue backlog does not trigger it, because the count, not the pointer’s age, decides. The degraded attempts skip the body, attachment and reference code paths that can panic; a message that still fails goes to pm-inbound-dlq with its raw object kept for a redrive (J8).

  5. Effective policy = built-in defaults ⊕ PM_DEFAULT_POLICY ⊕ tenants.policy_json (tenant policy), then, for a provisional agent sign-up, the fixed overlay, which only tightens.

  6. Classify automation (Automated mail). A DSN goes to DSN routing inside Ingest.

  7. Authenticate (Authentication verdict), unless loopback is set. For the SES source, SPF comes from SES’s verdict.

  8. Content: sanitise HTML, remove hidden text, derive text, extract new content, snippet (Sanitising, Hidden text, Text, Quotes).

  9. References (Reference extraction).

  10. Attachments: list, sniff, classify risk, unpack TNEF, optional scanner (Attachment safety).

    10a. Calendar: select, read and verify calendar parts; set kind to calendar when it was normal (Calendar invitations §4.2). Skipped in degraded mode (step 4), so a poison invitation is stored without its object and never dropped.

  11. Verification codes and links (Verification codes).

    11a. Steering scan (Screening hold §4.1): when the effective screening.mode is not off, core::screening::scan_message over every field an agent can read and the hidden content sanitising removed; the result goes into IngestInput.screening.

  12. D1 facts (one batch, 5-second deadline):

    • sender suppressed (only sets the flag sender_suppressed; it never hides the message, D7): SELECT 1 FROM suppressions WHERE tenant_id = ?1 AND address_hash = ?2 AND (expires_at IS NULL OR expires_at > ?3);
    • receive lists, both scopes in one statement (Parity additions § 3.5): SELECT identity_id, kind, entry FROM sender_lists WHERE tenant_id = ?1 AND direction = 'receive' AND identity_id IN ('', ?2) AND entry IN (SELECT value FROM json_each(?3)) with ?2 = the identity and ?3 = the sender address and @ + sender domain as one JSON array; core::lists::decide gives the effective receive decision (Parity additions § 3.1: an identity entry overrides the tenant’s of the same or a coarser granularity; among the entries left, block wins);
    • tenant domains: SELECT name, kind FROM domains WHERE (tenant_id = ?1 OR kind = 'platform') AND state <> 'removed'. Every row feeds the look-alike checks; only rows with kind <> 'platform' (the tenant’s own domains) can make a sender known_sender (Trust signals);
    • co-recipient identities (A9);
    • only when the effective policy has accounts.require_approval: true and step 11 found a verification match: the identity’s approved service-ledger entries, SELECT id, sender_domains_json, address FROM service_accounts WHERE identity_id = ?1 AND status = 'approved' ORDER BY created_at, passed as IngestInput.approved_accounts (Service sign-up ledger §5);
    • only when step 10a read a calendar object: the identity’s addresses, SELECT address FROM addresses WHERE identity_id = ?1, for is_self (Calendar invitations §4.2);
    • only when conditions 1–6 of the ARC rescue rule held at step 7: the identity’s addresses, SELECT address FROM addresses WHERE identity_id = ?1 AND status IN ('active','retiring'), for condition 7; the verdict is finished before MailboxRequest::Ingest (Parity additions § 6.3).
  13. Admit against the inbound volume caps (Inbound volume caps): QuotaRequest::AdmitInbound { identity_id, bucket, at, cap } (cap = policy.inbound.per_tenant_per_hour) to the tenant’s TenantQuota. The answer (Admit or Throttle) goes into IngestInput.inbound_admit; ingest ignores a Throttle for a known correspondent or a receive-allowed sender. TenantQuota unavailable → Admit (mail is never lost for our outage; the per-sender throttle inside ingest still applies). Loopback and re-parse pointers skip this step.

  14. Call MailboxRequest::Ingest with an IngestInput (30-second deadline).

  15. Post-commit (Post-commit), then ack.

Failure handling

CallDeadlineOn failure
D1 scope / facts5 sretry(30 s)
R2 get raw10 serror → retry(30 s); not found → step 2
R2 copy for a staged pointer10 sretry(30 s); the staging object is deleted only after the copy succeeds
S3 GetObject for an SES pointer60 serror → retry(30 s); NoSuchKey → ledger lost (The SES source)
D1 ses_ingest update, S3 DeleteObject5 s, 10 sretry(30 s); the repeat Ingest returns the stored message, and a failed delete is retried by the next recipient’s commit or left to the 14-day lifecycle rule
DoH lookups3 s each, 4 s totalsecond resolver, then temperror in the verdict (never a retry of the message)
Scanner (PM_SCANNER_URL)30 s per attachment, 60 s per messagescan_status = 'error', continue, count scanner_error_total
Ingest RPC30 sunavailable or timeout → retry(30 s); ingest is idempotent on raw_sha256 (J2)
R2 put attachments, queue send_batch10 sretry(30 s); the repeat Ingest returns the stored message
Unexpected error or panic–queue retry after retry_delay (120 s) up to 10, degraded parsing from the third attempt, then pm-inbound-dlq (J8)

Parsing

core::mime::parse(raw: &[u8], caps: &Caps) -> ParsedMessage uses mail_parser::MessageParser::default() (every known header parsed) with the full_encoding feature for legacy charsets. mail-parser 0.11.9 has no configurable depth or part limit and no TNEF support (read from its source, 2026-10-09), so the caps are applied while walking the parsed tree:

CapValueWhen exceeded
Nesting depth32Deeper parts are not processed (they stay in the raw MIME); flag parse_degraded
Parts500Parts after the 500th are not processed; flag parse_degraded
Nested message/rfc822 text extraction3 levelsDeeper nested messages are kept as attachments without text

ParsedMessage holds: header fields (From list, Sender, To, Cc, Reply-To, Subject, Date, Message-ID, In-Reply-To, References, Auto-Submitted, List-*, Precedence, Content-Type, X-Pylota-Identity-Hop, Authentication-Results, Disposition-Notification-To), the selected text and HTML bodies, the attachment parts, and flags.

Rules:

  • Bodies. The text body is the first text/plain part that is not Content-Disposition: attachment; the HTML body is the first such text/html part (in multipart/alternative, the last alternative of each type wins, per RFC 2046). Every other leaf part is an attachment, including inline images.
  • Charsets (B5). Decoded to UTF-8. When the decoded text contains U+FFFD and the raw part did not contain the UTF-8 bytes EF BF BD, set parse_degraded.
  • From (B13). No From: from_address is NULL, flag parse_degraded. Several From mailboxes: the first parseable one is used, flag parse_degraded, and auth_json.multiple_from = true caps the verdict at unaligned.
  • Message-ID (B3). Normalised as in Threading. Missing or unparseable: rfc_message_id = "{raw_sha256}@synthetic.invalid", message_id_synthetic = 1.
  • Date. sent_at is the Date header when it parses and lies between received_at − 10 years and received_at + 1 day; otherwise received_at.
  • Encrypted (B9). application/pkcs7-mime with smime-type=enveloped-data, or multipart/encrypted: flag encrypted; text, html_sanitized and extracted_text are NULL; the encrypted part is stored as an attachment. Signed-only (multipart/signed, smime-type=signed-data): content is processed normally and auth_json.signature records { "type": "smime" | "pgp", "status": "present_unverified" }. v1 never verifies S/MIME or PGP signatures (no certificate store or keyring); the signature part is kept as an attachment.
  • TNEF (B6). An application/ms-tnef part (or winmail.dat) is unpacked by core::mime::tnef::extract, which reads the TNEF stream (signature 0x223E9F78) and returns the attachments it carries (attAttachData with attAttachTitle, or the MAPI long filename). The extracted files become ordinary attachments. If unpacking fails, winmail.dat is kept as an attachment.
  • Nested messages (B6, FR-THR-2). See Threading.
  • Calendar (B8). Calendar parts are read at consumer step 10a, after TNEF is unpacked, into the bounded, verified calendar object of Calendar invitations. Invites are never answered or accepted by the service on its own.

Storage caps

Durable Object SQLite allows at most 2 MB per string, BLOB or table row, 100 bound parameters per query, 100 KB per SQL statement and 100 columns per table (limits, read 2026-10-10). The full message always remains in R2, so every stored column is capped, cutting at a UTF-8 character boundary, and the whole row has a budget of 1,900,000 bytes (the sum of the UTF-8 lengths of every column, so a row never reaches 2 MB):

ColumnCap
subject998 characters
from_name, display names256 characters, control characters removed
to_json, cc_json200 addresses each, and 64 KiB of JSON each (later addresses are dropped)
reply_to_json10 addresses
references_json200 msg-ids (the last 200), and 32 KiB of JSON (the oldest entries are dropped until it fits)
automated_json64 KiB; dsn.recipients at most 100 entries, each diagnostic_code at most 512 characters
calendar_json262,144 bytes, with the shrink order of Calendar invitations §4.1
auth_json16 KiB; at most 10 dkim entries
metadata_json, flags_json16 KiB each
extracted_text256 KiB
text512 KiB
html_sanitized1 MiB, and whatever the row budget leaves (below)
snippet240 characters of extracted_text, whitespace collapsed

Row budget. fixed is the size of every column except the three bodies, after the caps above (at most about 526 KiB). A reserve of 16 KiB is kept for later writes to the row (triage_json, added flags). The bodies are cut in this order until fixed + reserve + bodies ≤ 1,900,000: first html_sanitized (the sanitised copy is a convenience; the original HTML is in the raw MIME), then text, then extracted_text. With every cap at its maximum, html_sanitized keeps at least about 560 KiB. The same budget and order apply to outbound rows (Outbound › Storage of an accepted send) and to a re-parse.

When a body is cut, the message gets the flag body_truncated; when an address list or references_json is cut, parse_degraded. A DSN’s recipients beyond the first 100 are not applied to delivery state.

Bound parameters. No statement binds more than 100 parameters: every mailbox and D1 statement that takes a list of values (IDs, addresses, hashes) binds it as one JSON array parameter and expands it with json_each(?n) (as Search does), never as IN (?, ?, …) with one parameter per value. The longest fixed statement is the message insert (40 parameters). Statements are built only from fixed fragments, so none comes near 100 KB.

Sanitising HTML

Sanitising runs in two passes in core::sanitize:

  1. DOM pass (html5ever + markup5ever_rcdom): parse the HTML body, remove hidden elements (Hidden text), remove src from every <img> whose source is not cid: (remote images are never fetched by the service, B7; the alt text stays), record the cid: references, and serialise.
  2. ammonia pass with this policy, built once:
SettingValue
tagsa abbr b bdi bdo blockquote br caption center cite code col colgroup dd del details dfn div dl dt em figcaption figure font h1 h2 h3 h4 h5 h6 hr i img ins kbd li mark ol p pre q s samp small span strike strong sub summary sup table tbody td tfoot th thead time tr tt u ul var wbr
clean_content_tags (removed with their content)script style title noscript template iframe frame frameset object embed applet svg math select textarea button
generic_attributeslang title dir
tag_attributesa: href · img: src alt width height · td, th: colspan rowspan align valign width · table: width border cellpadding cellspacing align · col, colgroup: span width · ol: start type · li: value · time: datetime
url_schemeshttp https mailto tel cid
attribute_filterkeep img src only when it starts with cid:; keep a href only for http, https, mailto, tel
url_relativeDeny
link_relSome("noopener noreferrer nofollow") (rel is not an allowed attribute, as ammonia requires)
strip_commentstrue
style, class, id, on*, data-*never allowed

The result is html_sanitized. The service never renders it. API responses mark all text fields as untrusted content.

Hidden text (B11)

Hidden content is removed from everything an agent reads: text, html_sanitized, extracted_text, snippet, the subject and display names (characters only), attachment text, and triage input (FR-IN-9, B11).

Hidden elements (DOM pass). An element and its subtree are removed when any of these hold, from its inline style, its attributes, or a matching rule in a <style> block (only simple selectors are evaluated: tag, .class, #id, tag.class, comma lists; rules inside @media are ignored):

SignalCondition
Displaydisplay:none; visibility:hidden or collapse; the hidden attribute; <input type="hidden">
Transparencyopacity ≤ 0.05; color:transparent
Sizefont-size ≤ 1 px, ≤ 1 pt, or 0 (any unit); max-height:0, height:0, width:0 or max-width:0 together with overflow:hidden
Positionposition:absolute or fixed with left, top or text-indent ≤ −999 px; clip:rect(0,0,0,0); clip-path:inset(50%) or more
Same colourthe element’s text colour equals its effective background colour, where the background comes from the nearest ancestor background, background-color or bgcolor, defaulting to white (#ffffff). Colours are compared after normalising names, #rgb, #rrggbb and rgb()
CommentsHTML comments, including conditional comments (<!--[if mso]>…<![endif]-->)

Hidden characters are removed from all agent-facing text: U+200B, U+200C, U+2060–U+2064, U+FEFF, U+00AD, U+034F, U+180E, U+115F, U+1160, U+3164, U+FFA0, bidirectional overrides and isolates (U+202A–U+202E, U+2066–U+2069), and tag characters (U+E0000–U+E007F). U+200D (zero-width joiner) is removed except between two Extended_Pictographic characters (emoji sequences). U+200E and U+200F (direction marks) are kept.

Flag. hidden_text is added to flags_json, and the risk flag hidden_text is passed to triage, when any of: a removed element contained at least one non-whitespace character; any tag character or bidirectional override was removed; or more than two zero-width characters were removed outside emoji sequences.

Text derivation (B4)

text is the text/plain body when present. When the message is HTML-only, core::text::derive_text walks the sanitised DOM:

  • block elements (p div br li tr h1–h6 blockquote pre table hr) end a line; p and headings add a blank line;
  • li is prefixed with - (or 1. inside ol);
  • blockquote lines are prefixed with > (so quote stripping recognises them);
  • a renders as text (url) when the URL differs from the text and the scheme is http, https or mailto;
  • img renders as [image: alt] when it has non-empty alt;
  • table cells in a row are joined with |;
  • pre keeps its whitespace; elsewhere runs of whitespace collapse to one space;
  • entities are decoded; at most two consecutive blank lines; trimmed.

text is null only for encrypted messages. HTML-only mail always produces text (FR-IN-7).

Quote and signature stripping

core::quote::extract_new_content(text, html_dom) -> String produces extracted_text, the new content of the message (FR-IN-7).

HTML markers first. If the HTML body has one of these, the DOM is cut at the first one and the text is derived from what precedes it: div.gmail_quote, blockquote[type=cite], div#divRplyFwdMsg, div#appendonsend, hr#stopSpelling, div.yahoo_quoted, div#mail-editor-reference-message-container, blockquote.protonmail_quote.

Text algorithm otherwise, on text (or derived text):

  1. Find the earliest quote header line at or after line 1 (a header on line 0 is ignored, so a reply whose first line matches is not emptied). A match may span two lines (wrapped headers), so line i is also tested joined with line i+1:

    LanguagePatterns (case-insensitive, whole line)
    English^On .{1,200} wrote:$ · ^-{2,} ?Original Message ?-{2,}$ · ^-{2,} ?Forwarded message ?-{2,}$ · ^Begin forwarded message:$
    German^Am .{1,200} schrieb .{1,200}:$ · ^-{2,} ?Ursprüngliche Nachricht ?-{2,}$
    French^Le .{1,200} a écrit ?:$ · ^-{2,} ?Message d'origine ?-{2,}$
    Spanish^El .{1,200} escribió:$ · ^-{2,} ?Mensaje original ?-{2,}$
    Italian^Il .{1,200} ha scritto:$ · ^-{2,} ?Messaggio originale ?-{2,}$
    Dutch^Op .{1,200} schreef .{1,200}:$ · ^-{2,} ?Oorspronkelijk bericht ?-{2,}$
    Portuguese^Em .{1,200} escreveu:$
    Swedish, Danish, Norwegian^Den .{1,200} skrev .{1,200}:$ · ^.{1,200} skrev:$
    Polish^.{1,200} napisał(a)?:$
    Russian^.{1,200} писал(а)?:$
    Japanese`^.{1,200}(さんは書きました
    Chinese^.{1,200}写道[::]$
    ArabicNone yet. A pattern is added only with a reply-attribution sample from real clients in crates/conformance (GAP-21 of the gap register); a pattern is never guessed

    An Outlook-style header block also counts: a line ^(From|Von|De|Da|Van|Från|Od) ?: followed within the next 4 lines by a line ^(Sent|Date|Gesendet|Datum|Envoyé|Enviado|Inviato|Verzonden|Skickat|Wysłano|Enviada) ?: and one ^(To|Subject|An|Betreff|À|Objet|Para|Asunto|A|Oggetto|Aan|Onderwerp|Till|Ämne|Do|Temat|Assunto) ?:. A line of 10 or more underscores directly above such a block is included in the cut.

  2. Cut the text at that line.

  3. Remove every line that starts (after optional spaces) with >. Inline replies between quoted lines are kept.

  4. Signature. Cut at the first line that is exactly -- or -- (RFC 3676), when it is in the last 15 non-blank lines. Also cut mobile signatures when they are in the last 5 non-blank lines: ^Sent from my (iPhone|iPad|Android|mobile device|phone), ^Get Outlook for (iOS|Android), ^Sent from (Mail|Outlook|Yahoo Mail) for, ^Von meinem (iPhone|iPad|Smartphone) gesendet, ^Envoyé de mon (iPhone|iPad), ^Enviado desde mi (iPhone|iPad), ^Inviato da (iPhone|iPad), ^Verzonden (vanaf|met) mijn (iPhone|iPad). Sign-offs such as “Kind regards” are kept.

  5. Trim. Fallbacks: if the result is empty and the cut was at a forward marker, extracted_text is the text from the forward marker onwards (an inline forward with no comment). If it is empty otherwise, extracted_text is text with only step 4 applied.

The hidden-character rules then run on the result, and snippet is its first 240 characters.

Reference extraction

core::refs::extract(subject, extracted_text, packs, custom, tz) -> Vec<Ref> runs at ingest on the subject and extracted_text (not the quoted history, so a quoted invoice number does not make every reply match), and later on attachment text (FR-SRCH-4). Each Ref is { kind, value, source } with source one of subject, body, att:{attachment_id}:{page}. At most 50 refs per kind and 200 per message; values are at most 64 characters.

Pack core (always on):

KindMatchesNormalised value
amountA currency symbol or code next to a number: £ € $, GBP EUR USD, either side, e.g. £412.80, 412,80 €, USD 1,200{ISO code}:{amount with two decimals}, e.g. GBP:412.80. A comma is the decimal separator only for €/EUR amounts of the form \d+,\d{2} with no other separator
phone+ or 00 followed by 7–15 digits with optional spaces, dots, dashes or parentheses; national-format numbers of the tenant’s country, which is derived from its time zone (default GB), the same rule as Search §3.5E.164, e.g. +447700900123
emailRFC 5322 addr-spec in textlower case, A-label domain
domainDomains of matched emails and of http(s) URLsregistrable domain (public suffix list), lower case
dateISO YYYY-MM-DD; D/M/YYYY and D.M.YYYY (read as day first when the tenant time zone is in Europe/, otherwise only when the first number is > 12); D Month YYYY with English month names or three-letter abbreviationsYYYY-MM-DD
invoiceA keyword (invoice, inv, rechnung, facture, factura, fattura), optional no., number, nr., # or :, then [A-Z0-9][A-Z0-9/-]{2,24}; or INV- followed by digitsupper case; for INV- plus digits, the digits only (so Invoice 88213 and INV-88213 both give 88213)
orderorder, ord, po, purchase order, bestellung, commande, pedido, optional separator, then [A-Z0-9][A-Z0-9-]{3,24}upper case

Pack uk_vehicle (opt-in through search.refs_packs):

KindMatchesNormalised value
uk_plateCurrent format [A-Z]{2}\d{2} ?[A-Z]{3}; prefix format [A-Z]\d{1,3} ?[A-Z]{3}; suffix format [A-Z]{3} ?\d{1,3}[A-Z]; on word boundaries, case-insensitiveupper case, spaces and dashes removed: AB12 CDE → AB12CDE (F5)
pcn[A-Z]{2}\d{8} on word boundaries; or, within 20 characters after PCN or penalty charge, [A-Z0-9]{8,12}upper case, spaces removed

custom_refs (up to 20, from policy): each { name, pattern, normalise } is compiled with the regex crate (linear time, no back-references, size_limit 64 KB); invalid patterns are refused when the policy is saved. Matches produce kind custom:{name} with the whole match (or capture group 1 if present), normalised by normalise: upper, lower or none, then trimmed.

Refs are inserted into refs and their values (normalised plus, for plates, the spaced display form) into the FTS refs column (Search).

Ref values are text from the mail: an email or domain value, or a custom ref with normalise: none or lower, can hold up to 64 characters an attacker chose. They are therefore untrusted wherever a model reads them. Only a value that core::injection::fact_ref accepts (after upper-casing, it matches ^[A-Z0-9][A-Z0-9:.+/-]{0,39}$, and its kind is not email or domain) may appear outside a fence, in triage’s FACTS block and the planner’s why= line; every other value goes inside the nonce fence or is left out (Triage § 6.2, Search § 11.6).

Automated mail and loops

core::classify::classify(&ParsedMessage) -> Classification { kind, automated, evidence, dsn, mdn } (FR-IN-6, D6, B8). The first matching row sets kind; evidence from every row is collected into automated_json.evidence.

OrderSignalkind
1Content-Type: multipart/report; report-type=delivery-status (RFC 3464); or a heuristic bounce: From local part mailer-daemon or postmaster, a subject matching `undeliverdelivery status notification
2multipart/report; report-type=disposition-notification (RFC 8098)mdn
3List-Id, List-Unsubscribe or List-Post present, or Precedence: list or bulklist
4Auto-Submitted present with a value other than no (RFC 3834 auto-generated, auto-replied; RFC 5436 auto-notified); X-Autoreply, X-Autorespond; X-Auto-Response-Suppress containing All or OOF; Precedence: junk or auto_reply; a subject starting Out of Office, Automatic reply:, Auto:, Autosvar:, Abwesenheitsnotiz, Réponse automatique; From local part noreply, no-reply, donotreply, do-not-reply; the null envelope sender; X-Pylota-Identity-Hop ≥ MAX_HOP (10)automated
5A calendar object was read at step 10a, and none of the above (step 10a upgrades normal to calendar)calendar
6Otherwisenormal
  • trust.automated is true for dsn, mdn, list and automated. Agents must not auto-reply to these; the send path refuses kind: auto_reply replies to them (Outbound).
  • X-Pylota-Identity-Hop: n is set by our own outbound mail (Outbound). Any value ≥ 1 adds evidence pylota_agent; ≥ MAX_HOP (10, a constant in core::policy) makes the message automated (a loop breaker). The value is stored as automated_json.hop, and the send path refuses any send whose computed hop would reach MAX_HOP, whatever its kind (409 loop_detected, Outbound › Policy pipeline, N13).
  • Disposition-Notification-To adds evidence mdn_requested. Read receipts are never sent (B8).
  • For a DSN, classify also parses the message/delivery-status part into dsn = { reporting_mta, original_envelope_id, original_message_id, original_from, recipients: [{ final_recipient, action, status, diagnostic_code }] } (at most 100 recipients), taking original_message_id and original_from from the Message-ID and From of the returned message/rfc822 or text/rfc822-headers part.

Authentication verdict

core::auth computes the verdict from the trusted Authentication-Results header, our own mail-auth DKIM and ARC verification, and our own DMARC evaluation (FR-IN-4, D1, D9). For Email Routing, Cloudflare’s own checks run before the Worker: mail that fails both SPF and DKIM, or fails the sender’s DMARC policy, is rejected by Email Routing (email lifecycle, read 2026-10-09). Which headers Cloudflare adds before the handler is not documented. Spike S2 records the authserv-id Cloudflare stamps, setup writes it to PM_TRUSTED_AUTHSERV_ID from the mail test (CLI and setup §6.3, step 23), and until then the only input that depends on the header, SPF, is treated as unknown: a sender that could only align through SPF gets unverified, never fail (step 7). The SES rule pm-deliver refuses nothing for authentication, so SES mail that fails DMARC reaches the verdict below. The same DKIM, ARC and DMARC code runs for every source; only the SPF input differs (step 5).

  1. Trusted Authentication-Results. Parse every Authentication-Results header (RFC 8601) in order from the top. If PM_TRUSTED_AUTHSERV_ID is non-empty and the topmost header’s authserv-id equals it, that header is trusted. Every other Authentication-Results header is ignored, including lower ones with the right authserv-id (a sender can add those).

  2. DNS prefetch. Collect the TXT names needed: {s}._domainkey.{d} for each DKIM-Signature (at most 10) and for each ARC-Message-Signature and ARC-Seal (at most 5 instances), plus _dmarc.{from_domain} and _dmarc.{organisational domain} (public suffix list). Query them concurrently through platform::Dns on the first resolver, and on error or timeout on the second (3 s per query, 4 s in total). Each answer is parsed with mail-auth’s TXT record parser into the cache value type and inserted with Parameters::with_txt_cache (verify the parser’s public path at build time, S4). A record that could not be fetched is cached as a temporary error. A cache miss would fall through to mail-auth’s own DoH client, which works on Workers but bypasses the two-resolver rule; the prefetch list is complete, so misses are counted (auth_dns_cache_miss_total) and treated as bugs.

  3. DKIM. verify_dkim over the raw message gives one DkimOutput per signature: d=, s=, result (pass, neutral, fail, permerror, temperror, none).

  4. ARC. verify_arc (feature arc) gives pass, fail or none and the instance count; for pass the newest seal’s d=, the newest AAR’s dmarc result, header.from and smtp.rcpttodomain, and the newest AMS’s h= and t= are recorded in auth_json.arc (with arc.sealer_trusted, whether the sealer is in inbound.trusted_arc_sealers). ARC can rescue a DMARC failure only by the rule of Parity additions § 6.

  5. SPF. Email Workers do not expose the client IP and mail-auth’s SPF check needs it. SPF is taken from the trusted header’s spf= result and smtp.mailfrom (domain = the part after @, or the envelope sender’s domain). Without a trusted header (PM_TRUSTED_AUTHSERV_ID empty, or the topmost header from another authserv-id), SPF is none and recorded as unchecked (auth_json.spf.source = null). SES source: SPF is SES’s spfVerdict (PASS → pass, FAIL → fail, GRAY and PROCESSING_FAILED → none), with mail.source (the envelope MAIL FROM) as the checked domain. SES saw the connecting IP; the Worker did not.

  6. DMARC (core::auth::dmarc, our implementation, because SPF comes from step 5):

    • from_domain = domain of the (first) From address. Look up _dmarc.{from_domain}; if there is no record, _dmarc.{org_domain}. Parse v (must be DMARC1, first), p, sp, adkim, aspf (defaults r); pct and t are parsed and ignored. More than one record, or none: no policy.
    • DKIM-aligned: a pass signature whose d equals from_domain (adkim=s) or shares its organisational domain (adkim=r). SPF-aligned: SPF pass with the same rule over the SPF domain and aspf.
    • Result: pass if either is aligned; fail if a policy exists and neither is aligned; temperror if a needed lookup failed and nothing passed; none if there is no record. auth_json.spf.aligned records whether SPF passed and aligned under aspf, whatever the result.
    • Policy in force: sp when the record came from the organisational domain and from_domain is a subdomain, else p.
    • If our result is temperror and the trusted header has dmarc=pass or dmarc=fail, use the trusted result.
    • The organisational domain uses the public suffix list (RFC 7489). RFC 7489 is obsoleted by RFC 9989 (DMARCbis, 2026), which replaces the list with a DNS tree walk; that change needs an ADR and a corpus re-run before adoption.
  7. Verdict (messages.verdict):

    Condition (first match)verdict
    loopback set (L3)pass
    DMARC passpass
    DMARC fail, or the unverified condition of the next row, and core::auth::arc_rescue succeeded: a validated chain whose newest seal is a trusted sealer, signing From, with a fresh AAR dmarc=pass for the From domain and bound to this identity (Parity additions § 6.3)arc_rescued; auth_json.arc.rescue = { "result": "rescued" }, else { "result": "refused", "reason" }
    DMARC fail, the policy in force is quarantine or reject, no aligned DKIM pass, and SPF unchecked (Email Routing source without a trusted header, step 5)unverified: SPF alignment, which Cloudflare checked before the Worker, could not be read (the authserv-id is recorded by spike S2)
    DMARC fail and the policy in force is quarantine or rejectfail
    DMARC fail with p=noneunaligned
    DMARC temperrorsoftfail
    No DMARC recordnone. Alignment is recorded separately: auth_json.dmarc.aligned_by is dkim, spf or null, and each DKIM entry has aligned

    Then, if multiple_from, the verdict is capped at unaligned (the rescue rule does not run with multiple_from). Only fail and unverified can quarantine; none, unaligned and arc_rescued never quarantine on their own (D1). arc_rescued is not pass: it never yields a verification row, a service-ledger match, a wait release or a trusted delivery report (Parity additions § 6.5).

  8. auth_json:

    {
      "authserv": { "id": "mx.cloudflare.net", "trusted": true },
      "spf":   { "result": "pass", "domain": "mail.brightwell.example", "source": "authserv", "aligned": true },
      "dkim":  [ { "d": "brightwell.example", "s": "s1", "result": "pass", "aligned": true } ],
      "dmarc": { "result": "pass", "policy": "reject", "record_domain": "brightwell.example", "aligned_by": "dkim" },
      "arc":   { "result": "none", "instances": 0 },
      "multiple_from": false,
      "signature": null
    }
    

    dmarc.aligned_by (dkim, spf or null) is set whatever the result, so alignment is recorded even when there is no DMARC record (verdict none, D1).

    For the SES source, authserv is null, spf.source is "ses", and ses holds SES’s own verdicts (spf, dkim, dmarc, spam, virus, dmarc_policy). When SES’s DKIM or DMARC result differs from ours, ses_auth_disagreement_total is incremented; ours decides.

    The API’s trust.spf, trust.dkim, trust.dmarc and trust.arc are the summary results (DKIM: pass if any aligned signature passed, else the first signature’s result, else none). trust also carries the detail read from auth_json: spf_domain, spf_aligned, dkim_domains, dmarc_domain, dmarc_policy, dmarc_aligned_by and arc_sealer (Parity additions § 5.1).

Trust signals

Computed partly in the consumer and finished inside ingest, which can see the mailbox’s contacts.

Authenticated sender (C10). The sender is authenticated when the verdict is pass, or when auth_json.dmarc.aligned_by is dkim or spf: an aligned DKIM signature or an aligned SPF pass proves the From domain even when it publishes no DMARC record or p=none. A verdict of arc_rescued also makes the sender authenticated, because a trusted sealer proved the From address (Parity additions § 6.5), but never for the own-domain rule of known_sender. Every rule below that trusts an address the identity knows (a contact, a participant, a known correspondent) applies only to an authenticated sender, because a From header alone can name anyone.

SignalRule
known_sender (FR-IN-4)True when the sender is authenticated (below) and its address is in contacts with outbound_count > 0 (we have written to them), or its effective receive decision is allow, or its domain is one of the tenant’s own domains (kind <> 'platform') and the verdict is pass (arc_rescued is not enough). The shared platform domain never gives domain-level trust: every tenant’s agents send from it with a passing DMARC verdict, so a platform-domain sender is known only through contacts or an address-level receive-allow entry (D12)
shared_domain_sender (D12)The From domain is PM_PLATFORM_DOMAIN and the sender is not an address of this identity’s own tenant: the mail comes from another workspace on the shared domain, whose name the receiving agent should not take at face value
display_name_spoof (D2)The display name contains an address-like token different from the From address; or its confusable fold equals the fold of the name of a contact with outbound_count > 0 whose address differs; or it equals the identity’s display name or the tenant name while the sender is not this identity
lookalike_domain (D2)The fold of the sender’s registrable domain equals the fold of a tenant domain or of a contact domain with outbound_count > 0, while the domains differ. For a sender on the platform domain, the fold of its local part’s tenant suffix (the part after the last .) is also compared with the folds of the receiving tenant’s own suffix and domain labels. The fold is the UTS #39 skeleton plus the ASCII rules of Identities › Confusables
reply_to_mismatch (D3)Reply-To is present and its organisational domain differs from the From organisational domain. Who replies go to is decided at reply time (Outbound)
thread_join_unverified (D10)Threading
hidden_text (B11)Hidden text

These are stored in flags_json; the API returns hidden_text, display_name_spoof, lookalike_domain, reply_to_mismatch, thread_join_unverified, shared_domain_sender, steering_suspected and attachments_unscreened (both set by screening, Screening hold §7) as trust.flags and the rest as message flags.

Spam score (spam_score, 0–1, FR-IN-4). The consumer computes a base from deterministic signals and ingest applies the sender adjustments, then clamps to [0, 1]:

SignalWeight
verdict arc_rescued / softfail / none / unaligned / unverified / fail+0.05 / +0.20 / +0.10 / +0.10 / +0.20 / +0.50
display_name_spoof, lookalike_domain+0.30 each
shared_domain_sender+0.05
hidden_text+0.20
reply_to_mismatch+0.10
a link whose visible text is a URL or domain different from its href domain+0.20 (once)
HTML-only, at least 3 links, under 200 characters of text+0.10
subject at least 70% upper-case letters (≥ 10 letters)+0.10
known_sender−0.40
sender in contacts with inbound_count ≥ 3 and no previous quarantine−0.10
SES source with spamVerdict FAILthe final score is at least 0.9 (applied after the adjustments above), so the default threshold of 0.8 quarantines it (N27)

SES GRAY and PROCESSING_FAILED verdicts are recorded in auth_json.ses and change nothing; they are never a reason to drop mail.

Quarantine decision

Decided inside ingest (first match wins, FR-IN-5):

OrderConditionstatusquarantine_reason
1The effective receive decision for the sender is block (an identity or tenant receive-block entry, Parity additions § 3, D7)hiddenblocked_sender
2An inbound volume cap exceeded: the per-sender throttle, or a Throttle admission for a sender that is neither a known correspondent nor receive-allowed (D5, D13)throttled–
3verdict = 'fail' and quarantine.on_auth_failquarantinedauth_failed
3averdict = 'unverified' and quarantine.on_auth_fail (no trusted Authentication-Results yet, so SPF alignment could not be checked)quarantinedauth_unverified
4Any attachment has a risk that quarantines (Attachment safety), or scan_status = 'infected', or the SES source’s virusVerdict is FAIL (N27)quarantinedrisky_attachment
4aA verification match, accounts.require_approval, no approved service-ledger entry matching it, and the effective receive decision is not allow (E9, Service sign-up ledger §5)quarantinedaccount_unapproved
4bA verification match with verdict pass, whose matched approved ledger entry has a linked active login item with otp_channel.kind = "email", otp_channel.address equal to delivered_to and the sender’s organisational domain in otp_channel.sender_domains; or, with vault.codes_into_fills_only, any verification match whatever its verdict, sender or entry, except receive-allowed senders (Vault § 9.2)hiddenvault_code
5Unsolicited OTP (E5) and quarantine.unsolicited_otpquarantinedotp_unsolicited
6spam_score ≥ quarantine.spam_threshold and the effective receive decision is not allowquarantinedspam
6aScreening in hold mode, an eligible message (Screening hold §4.3): the scan is decisive, or a test tenant forced suspectquarantinedsteering_suspected
6aA test tenant forced unavailable and on_unavailable is quarantinequarantinedscreening_unavailable
6aNothing is scannable (scannable = false), or a test tenant forced clear, or forced unavailable with on_unavailable = deliverreceived–
6aOtherwisescreening–
7Otherwise (rule 6a did not apply)received–

Rule 6a runs only when rules 1–6 matched nothing, and only for an eligible message (not a DSN or MDN, not the system identity’s mailbox), so it never overrides another reason; a message stored screening waits, hidden, for its verdict (Screening hold §7). In monitor mode rule 6a does not apply and the message is received with a screening record.

hidden and throttled messages are stored for audit, never evented, never auto-replied to, never searched and never counted for notifications. Quarantined and screening messages are visible only to keys with quarantine:review. In mail lists none of the three appears by default: a list shows them only for an explicit status filter from a key holding quarantine:review (Security §5.3). A receive-allow entry skips rules 4a and 6 only, never rule 3. A receive-allow entry does not skip rule 6a.

Suppressed senders are not hidden (D7). A suppression is an outbound decision (a bounce, a complaint, an unsubscribe, a provider entry): it says we must not write to the address, not that its mail is unwanted. Mail from a suppressed address is stored and evented like any other, with the message flag sender_suppressed, so an agent can see why a reply to it would not be delivered (the reply’s delivery is suppressed at submit). Only a receive-block entry hides mail.

Inbound volume caps (D5, D13)

Unsolicited mail costs storage, indexing and model calls, and its From is forgeable, so the caps are keyed by what can be trusted (FR-IN-4, FR-IN-12, D5, D13):

CapKeyDefault (policy)Exceeded
Per sender, per identityThe From address when the sender is authenticated; otherwise unauth: + the From address (or env: + envelope sender when From is missing)60 an hour (inbound.per_sender_per_hour)throttled
Unauthenticated, per identityOne bucket for all mail whose sender is not authenticated (none of them is a known correspondent)120 an hour (inbound.unauthenticated_per_hour)throttled
Per tenantOne bucket per tenant in TenantQuota (AdmitInbound), across its identities, for senders that are not known correspondents2,000 an hour (inbound.per_tenant_per_hour)throttled

For these caps a sender whose verdict is arc_rescued is authenticated: the per-sender key is its From address, and it is outside the unauthenticated bucket; a sender whose verdict is neither pass nor arc_rescued and that has no aligned DKIM or SPF pass is not.

A known correspondent is an authenticated sender in the identity’s contacts with outbound_count > 0 (C10); it and a sender whose effective receive decision is allow are never throttled by the unauthenticated and tenant caps, so a flood from forged senders cannot crowd out the people an agent already writes to. The per-identity caps use the mailbox’s rate_windows inside the transaction:

INSERT INTO rate_windows (sender, window_start, count) VALUES (?1, ?2, 1)
ON CONFLICT (sender, window_start) DO UPDATE SET count = count + 1
RETURNING count;
-- ?1 the key from the table: the sender key, or 'unauth:*' for the unauthenticated bucket
-- ?2 received_at - received_at % 3600000

AdmitInbound { identity_id, bucket, at, cap } increments the tenant’s counters row with metric inbound_hour and window YYYY-MM-DDTHH (the UTC hour of at) and answers Throttle above cap; rows older than 48 hours are deleted by its daily alarm. bucket is the cap’s key from the table, kept for the inbound_throttled_total{cap} label.

A cap exceeded → throttled, inbound_throttled_total{cap} incremented; the observability design alerts on it. Throttled and hidden mail is never triaged, embedded or evented, its attachments are not extracted, and it does not count towards storage_gb, so a flood can neither spend a workspace’s AI budget nor block its sends (Plans, metering and billing › Storage). Rows of rate_windows older than 48 hours are deleted by the mailbox’s daily maintenance alarm.

Verification codes and unsolicited OTP (E5)

Extraction implements FR-IN-11 with the wait handler below.

core::classify::find_verification(subject, extracted_text, links) -> Option<Verification>:

  • Trigger: the subject or the first 2,000 characters of extracted_text contain a keyword (verification, verify, code, passcode, one-time, OTP, security code, confirm, sign in, sign-in, log in, login, password reset, reset your password, 2FA, authentication, Bestätigungscode, code de vérification, código de verificación).
  • Code: the first match within 80 characters after a keyword of \b\d{4,8}\b, \b\d{3}[ -]\d{3}\b, or \b[A-Z0-9]{6,8}\b containing at least one digit; the value keeps its original spacing (481 207).
  • Link: the first http(s) link whose URL or visible text contains verify, confirm, activate, reset, magic, token, login or signin.
  • kind is code when a code was found, else link.

Rules:

  • E5. The mailbox records active wait calls in meta under wait:{sender_domain}: the time until which the registration counts (the wait handler sends MailboxRequest::RegisterWait { from_domain, ttl_ms } when it starts and every 10 seconds while it waits). A message with a verification match is unsolicited when no wait:{d} exists with a value ≥ received_at − 30 min, where d is the sender’s registrable domain.
  • A verifications row is inserted only when the verdict is pass (arc_rescued is not pass) and the status is received (a screening message gets its row when it is screened clear, Screening hold §7): (message_rowid, kind, value, sender_domain, received_at + 24 h, NULL, account_id), where account_id is the service-ledger entry that rule 4a matched, or NULL when the tenant does not require approval. The outbox gets verification.received with message_id, sender_domain, kind and account_id; the value itself is released only through wait (E4).
  • The ledger gate (rule 4a, only with accounts.require_approval: true): a message with a verification match that no approved entry of Service sign-up ledger §5 matches is quarantined account_unapproved, whether or not a wait registered its domain.

Codes for the vault. A message held by rule 4b is invisible to every agent surface, and unlike other hidden mail its content is withheld from API keys whatever their permissions (content_withheld: "vault_code"; raw answers 404). It is never released and never counted in notifications. Its verifications row records account_id and vault_item_id; VaultTakeCode consumes it once into an open email_otp phase. The message, raw object and row are deleted 24 hours after received_at. The step-12 query for approved entries returns each entry’s linked items with an email channel (IngestInput.approved_accounts[].vault_items), so rule 4b reads nothing more.

SMS uses the same trigger keywords and code patterns (core::phone::verify::find_code calls the shared patterns of core::classify::find_verification) without the link rule: a link in an SMS is never a verification object. Solicitation, the ledger gate, vault withholding and redaction for SMS are specified in Phone numbers § 11.

The wait handler (E4)

GET /v1/identities/{identity_id}/wait (FR-IN-11; search:read, any key level, bucket RL_API), in handlers/wait.rs. The request and response shapes are those of REST API › wait; MCP’s mail_wait calls the same function (its timeout_seconds is the API’s timeout). It is P0, because quarantine rule 5 (unsolicited OTP, E5) depends on its registrations.

  1. Validate. timeout 1–60 seconds (default 30); from an address or @domain; subject_contains at most 200 characters; thread_id a thr_ ID; kind any, reply or verification; since RFC 3339, default the request’s start. kind=verification without from is 400 invalid_request (details.errors[0].path = "from"), because a code is released only for an expected sender domain. from_domain is the registrable domain of from (the address’s domain, or the @domain). With kind=verification and the tenant’s accounts.require_approval: true, the handler then needs an approved service-ledger entry of the identity whose sender_domains contains from_domain, or it answers 403 policy_denied with details.reason = "account_not_approved" and registers nothing (E9). With the tenant’s vault.codes_into_fills_only: true, kind=verification answers 403 policy_denied with details.reason = "codes_into_fills_only" (Vault § 9.2).
  2. Register (only when from is given). Send MailboxRequest::RegisterWait { from_domain, ttl_ms } with ttl_ms = (timeout + 10) × 1000. The mailbox sets meta['wait:{from_domain}'] = max(stored value, now + ttl_ms) in one transaction. The handler sends it again every 10 seconds while it waits, so a registration always outlives the request by up to 10 seconds; E5 then counts it for 30 more minutes.
  3. Poll. Every 1 second until deadline = start + timeout, send MailboxRequest::WaitPoll { since_ms, from, subject_contains, thread_id, kind, release_domain } and stop at the first match. The mailbox returns the oldest inbound message with received_at > since_ms that the key may see (received, or quarantined when the key holds quarantine:review; never screening, hidden or throttled; wait has no status filter, so the list rule of Security §5.3 does not apply) and that matches every given filter:
    • from: the From address equals it, or its domain equals the @domain;
    • subject_contains: a case-insensitive substring of the subject;
    • thread_id: the message’s thread;
    • kind = reply: the message joined an existing thread that holds an outbound message (by token or headers, not a new thread), and it does not carry thread_join_unverified: a join that failed a token check, or a header join by someone who is not a participant, never counts as the reply an agent waits for (C9);
    • kind = verification: a verifications row exists for the message with expires_at > now.
  4. Release. With kind = verification (or any with a match that has a verification row), the verification object is filled only when the message’s verdict is pass (never arc_rescued) and the row’s sender_domain equals from_domain, and, with accounts.require_approval: true, the row’s account_id names an entry that is still approved (one D1 read by ID, E13); otherwise it is null and the message is still returned. The first release sets consumed_at = now. A later wait can release the same value for 1 hour after consumed_at (a client retrying after a lost response); the daily maintenance alarm deletes rows past expires_at or more than 1 hour past consumed_at.
  5. Answer. 200 { "message": Message, "verification": {…} | null, "timed_out": false } on a match, or 200 { "message": null, "verification": null, "timed_out": true } at the deadline. A client that disconnects stops the polling at the next tick. Waiting spends no CPU between polls, so a 60-second wait stays inside the Worker’s limits.

Tests (it::wait::e4_*):

TestProves
it::wait::e4_code_released_on_passA code mail from the expected domain with verdict: pass arriving during the wait is returned within 1 s of commit, with verification.code; consumed_at is set
it::wait::e4_code_withheld_unauthenticatedThe same mail with verdict: fail, or from another domain, returns the message with verification: null
it::wait::e4_timeoutNo match: 200 with timed_out: true at the deadline (time-controlled harness)
it::wait::e4_registration_refreshRegisterWait is sent at the start and every 10 s with ttl_ms = (timeout + 10) × 1000; an OTP mail from that domain 20 minutes after the wait ended is not quarantined (E5)
it::wait::e4_filters_and_sincesubject_contains, thread_id, kind=reply and since each narrow the match; a message flagged thread_join_unverified never satisfies kind=reply; kind=verification without from is 400 invalid_request
it::wait::e4_retry_after_releaseA second wait within 1 hour of release returns the same value; after the maintenance purge it returns none

Multiple identities in one tenant (A9)

Email Routing calls email() once per envelope recipient, and the SES source queues one pointer per recipient, so a message to two identities of one tenant becomes two independent copies with the same raw_sha256, one per mailbox. To let integrators act once, each copy computes is_primary_recipient deterministically from the headers, without coordination:

  1. Header recipients in order: every To address, then every Cc address.
  2. One D1 query: SELECT address, identity_id FROM addresses WHERE tenant_id = ?1 AND status IN ('active','retiring') AND address IN (SELECT value FROM json_each(?2)) (at most 50 addresses, bound as one JSON array, so the statement has two parameters whatever the count).
  3. The first header recipient that resolves names the primary identity.
  4. is_primary_recipient = 1 when no header recipient resolves (for example, a BCC-only delivery), or when the primary identity is this identity; else 0.

delivered_to is the envelope recipient without its detail, with one exception: mail for an external domain arrives forwarded to the identity’s platform address, so when the envelope recipient is the platform address and a To/Cc address belongs to the same identity on an external domain, delivered_to is that external address (Identities and domains). Such a message does not prove that forwarding works: anyone can write to the platform address directly with the external address in To, and no header a forwarder adds (ARC, X-Forwarded-To, an SRS envelope sender) can tell that apart from mail the sender forwarded through any account of their own. So ordinary mail never changes an address’s forwarding; only the forwarding-check token of email() step 3, which reaches the platform address only through the customer’s own forwarding rule, sets it to ok (Domains on any DNS host § 4.4, N12). is_bcc = 1 (flag bcc) when delivered_to matches none of To/Cc (A10). The value is stored in messages.is_primary_recipient and returned as is_primary_recipient in the API.

IdentityMailbox.ingest

// crates/worker/src/mailbox/ingest.rs
pub struct IngestInput {
    pub message_id: String, pub received_at: i64, pub raw_r2_key: String, pub raw_size: u64,
    pub raw_sha256: String, pub envelope_from: String, pub delivered_to: String,
    pub detail: Option<String>,                    // +detail of the envelope recipient
    pub parsed: ParsedSummary,                     // headers, bodies (capped), kind, evidence, dsn
    pub auth: AuthSummary,                         // verdict, auth_json
    pub spam_base: f32, pub flags: Vec<String>,
    pub refs: Vec<Ref>, pub attachments: Vec<AttachmentMeta>, pub verification: Option<Verification>,
    pub approved_accounts: Option<Vec<ApprovedAccount>>,   // step 12; None when the gate does not apply
    pub sender_suppressed: bool,
    pub receive_list: Option<ListDecision>,        // core::lists::decide over both scopes (Parity additions § 3.1)
    pub tenant_domains: Vec<(String, DomainKind)>,  // own domains and the platform domain
    pub inbound_admit: Admission,                  // Admit | Throttle, from AdmitInbound (D13)
    pub is_primary_recipient: bool, pub is_bcc: bool,
    pub policy: InboundPolicy, pub parser_version: u32, pub loopback: Option<LoopbackSource>,
    pub calendar: Option<CalendarInput>,           // step 10a; None without a calendar part
    pub screening: Option<ScreeningInput>,         // step 11a; None when policy screening.mode is off
}

pub enum IngestOutcome {
    Stored { message_id: String, thread_id: String, status: String, duplicate: bool,
             stored_raw_r2_key: String,            // the stored message's raw key (a duplicate's differs)
             attachments: Vec<AttachmentToStore>, suppress: Vec<SuppressionRequest>,
             screen_job: bool },                   // true when the message's screenings row is pending
                                                   // (written now, or found by a duplicate, step 2)
    Backscatter,                                   // an unmatched DSN: nothing written (D4)
}                                                  // an untrusted DSN (D11) is Stored, hidden, with no state change
pub struct AttachmentToStore { pub attachment_id: String, pub part_index: u32, pub r2_key: String,
                               pub text_pending: bool }

ingest runs entirely inside one transaction_sync (FR-SRCH-2: the message is searchable in the same transaction that stores it):

  1. Erased check. meta.erased = '1' → identity_not_found.

  2. Duplicate by hash (B14, J2):

    SELECT rowid, id, thread_seq, status FROM messages
    WHERE raw_sha256 = ?1 AND direction = 'inbound' LIMIT 1;
    

    Found → return Stored { duplicate: true, … } with that message’s attachments, screen_job true when its screenings row is still pending (so post-commit step 4a sends a ScreenJob that a failed send lost), and, for a stored DSN, its suppression requests recomputed from automated_json.dsn. No event, no counters.

  3. Duplicate by Message-ID (B3), only when message_id_synthetic = 0:

    SELECT rowid, id, subject, text, html_sanitized FROM messages
    WHERE rfc_message_id = ?1 AND direction = 'inbound';
    

    For each candidate, compare content: subject, text, html_sanitized and the sorted list of attachment sha256 values. All equal → duplicate (as step 2). Otherwise the new message is stored with flag message_id_conflict, and the candidates get the same flag: UPDATE messages SET flags_json = json_insert(flags_json, '$[#]', 'message_id_conflict') WHERE rowid = ?1 AND NOT EXISTS (SELECT 1 FROM json_each(flags_json) WHERE value = 'message_id_conflict').

  4. DSN (kind = 'dsn'): DSN routing. An unmatched DSN returns Backscatter here, before any write.

  5. Thread token. If detail looks like a token, apply the brute-force limits and verify it (Threading › Verification).

  6. Thread with resolve_inbound (Threading); it receives the calendar UID hash only when the calendar object is verified (Calendar invitations §4.3).

  7. Trust and quarantine: known_sender (own domains only), look-alike, display-name and shared-domain checks against contacts and tenant_domains, the final spam score, the volume-cap upserts and inbound_admit (Inbound volume caps), the E5 check, then the Quarantine decision, rule 6a included.

  8. Insert the thread if new (Threading).

    organized_here, before step 9, only for a verified reply, refresh or counter (false for every other object): one indexed query sets the field in the object, with ?2 its organizer and ?3 the replier’s party hash (Calendar invitations §4.2):

    SELECT 1 FROM messages
    WHERE calendar_uid_hash = ?1 AND direction = 'outbound'
      AND status NOT IN ('canceled','rejected','failed','suppressed')
      AND json_extract(calendar_json, '$.method') IN ('request','add','publish')
      AND json_extract(calendar_json, '$.organizer.address') = ?2
      AND EXISTS (SELECT 1 FROM json_each(calendar_json, '$.parties') p WHERE p.value = ?3)
    LIMIT 1;
    
  9. Insert the message with the status of step 7:

    INSERT INTO messages (
      id, thread_seq, direction, status, rfc_message_id, message_id_synthetic, in_reply_to,
      references_json, raw_sha256, raw_r2_key, raw_size, from_address, from_name, sender_domain,
      reply_to_json, to_json, cc_json, delivered_to, is_bcc, is_primary_recipient, subject, text,
      html_sanitized, extracted_text, snippet, sent_at, received_at, kind, automated_json, auth_json,
      verdict, spam_score, known_sender, quarantine_reason, flags_json, read, triage_status,
      triage_json, parser_version, metadata_json, received_evented_at, calendar_json, calendar_uid_hash)
    VALUES (?1, ?2, 'inbound', ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18,
            ?19, ?20, ?21, ?22, ?23, ?24, ?25, ?26, ?27, ?28, ?29, ?30, ?31, ?32, ?33, ?34, 0, ?35, ?36,
            ?37, '{}', ?38, ?39, ?40)
    RETURNING rowid;
    -- 40 bound parameters (the limit is 100)
    -- received_evented_at ?38: the commit time for received (either screening mode), NULL otherwise
    -- (Screening § 4.4); calendar_json ?39 and calendar_uid_hash ?40 from IngestInput.calendar, or NULL
    -- triage_status ?35: 'pending' for received (triage enabled), NULL for quarantined and screening
    -- (triaged once visible), 'skipped' for received with triage disabled, and for hidden, throttled, dsn and mdn;
    -- the system identity's mailbox: always 'skipped' (not_eligible), it is never triaged
    -- triage_json ?36: the skipped record for 'skipped' ({"status":"skipped","reason":"policy_disabled"
    -- or "not_eligible","risk_flags":[],"model":null,"version":TRIAGE_VERSION,"run":0}, Triage § 2),
    -- else NULL
    -- every value is capped by Storage caps (row budget 1,900,000 bytes)
    
  10. Attachments: one row each, id = att_…, r2_key = t/{ten}/i/{idn}/m/{msg}/a/{att}, text_status = pending when eligible for extraction, else skipped (Attachment text extraction), risk, sniffed_type, scan_status.

  11. Keyword index (skipped in the system identity’s mailbox, which is never indexed, A15):

    INSERT INTO fts (rowid, subject, participants, body_new, body_full, attachments, refs)
    VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);
    INSERT INTO fts_tri (rowid, subject, participants, refs) VALUES (?1, ?2, ?3, ?7);
    -- the six values come from core::search::fts_doc, the single builder defined in
    -- Search §5.1; at ingest the attachments column holds filenames only (attachment text is
    -- added by AttachmentTextReady)
    
  12. Refs: INSERT OR IGNORE INTO refs (message_rowid, kind, value, source) VALUES (…) per ref.

  13. Contacts (only for received, quarantined and screening; a contact known only from held mail stays hidden by the contacts visibility clause, Search §12.1):

    INSERT INTO contacts (address, name, domain, first_seen_at, last_seen_at, inbound_count, last_thread_seq)
    VALUES (?1, ?2, ?3, ?4, ?4, 1, ?5)
    ON CONFLICT (address) DO UPDATE SET
      name = COALESCE(NULLIF(excluded.name, ''), contacts.name),
      last_seen_at = MAX(contacts.last_seen_at, excluded.last_seen_at),
      inbound_count = contacts.inbound_count + 1,
      last_thread_seq = excluded.last_thread_seq;
    
  14. Verifications row when applicable (see above): only for received; a screening message gets its row at the clear commit (Screening hold §7).

  15. Thread counters, from visible messages only: the thread’s visible columns are recomputed when the new message is visible (received); a quarantined, screening, hidden or throttled message changes none of them (Threading § 3.4).

    15a. Screening record, when IngestInput.screening is set and the message is eligible: insert the screenings row with mode, on_unavailable, started_at = now, deadline_at = now + deadline_ms, the scan’s signals, and either status = 'pending' or, when decided at ingest (a decisive scan: suspect, reason rules; nothing scannable: clear, reason nothing_to_screen; a test tenant’s forced verdict: reason test_forced), the final status, reason, model and completed_at = now. When pending, set meta['alarm:screen'] = min(current, deadline_at) (Screening hold §4.4).

  16. Outbox: message.received (status received) or message.quarantined (status quarantined), plus verification.received when inserted, plus calendar.received after message.received when the message has a calendar object, is received, and the mailbox is not the system identity’s (Calendar invitations §4.4). No event for screening, hidden, throttled or DSN rows. A message whose screening was decided at ingest emits message.screened first, then message.received (monitor, or a hold-mode nothing_to_screen clear) or message.quarantined (hold, steering_suspected); message.received and message.quarantined carry data.screening when the message has a record. Payloads are built by the builders in Webhooks; extracted_text is cut to policy.webhook_text_bytes, and message.quarantined carries none.

  17. Set alarm:outbox, and re-arm the alarm to the earliest pending wake-up, alarm:screen included.

ingest also deletes meta['parse:{msg}'] (consumer step 4). A message ID listed in erased_ids (an erasure removed it while its pointer was still queued) gets identity_not_found at step 1 too, so a late retry never re-creates erased mail (I10).

Post-commit: attachments and index jobs

After Stored:

  1. Duplicate raw copy (B14, I9). When duplicate is true and stored_raw_r2_key differs from this pointer’s r2_key (a sender’s retry wrote a second copy under a new msg_ ID), delete this pointer’s raw object; the stored message keeps its own. A failed delete is left to the orphan sweep.

  2. Attachments. For each AttachmentToStore: on the first ingest, put the part’s bytes to its r2_key with custom metadata tenant, identity, message, sha256. On a duplicate, head the key first and put only if missing. Then MailboxRequest::ConfirmStored { message_id }: when the answer is Erased (an erasure removed the message while these puts ran), delete every object just put (I10). Attachment bytes therefore appear shortly after the message.received event; the attachment endpoint answers 503 unavailable (retryable) for an attachment row whose object is missing and whose message is less than 5 minutes old.

  3. Suppressions from a trusted DSN (DSN routing): INSERT OR IGNORE INTO suppressions … with an expiry (a DSN alone never creates a permanent suppression), and, when the row was inserted, suppression.created through MailboxRequest::EmitEvent with the deterministic event ID of Outbound › Suppressions.

  4. Index jobs in one send_batch to pm-index (none for the system identity’s mailbox, which is never indexed, embedded or triaged, A15):

    • AttachmentText { tenant_id, identity_id, message_id } when any attachment has text_pending;
    • Embed { tenant_id, identity_id, message_id } for every stored inbound message (Search); the embed consumer skips screening as it skips quarantined;
    • Triage { tenant_id, identity_id, message_id } when the status is received, the kind is not dsn or mdn, and triage is enabled (Triage), so never for screening.

    4a. Screen job. When screen_job is true, send ScreenJob { v: 1, tenant_id, identity_id, message_id, attempt: 0, deferrals: 0, waits: 0, finalize: false } to pm-screen. A failed send fails the post-commit step, the pointer is retried and ingest returns the stored message (duplicate by hash), so the send is repeated; if it never succeeds, the deadline still ends the hold (Screening hold §4.5).

  5. Count it: QuotaRequest::RecordUsage { metric: Inbound, n: 1 } to the tenant’s TenantQuota, which the hourly roll-up flushes to usage_daily (Outbound › TenantQuota); never a D1 write per message.

  6. SES source: set the ses_ingest row to done, and delete the S3 object when no row for its key is still queued (The SES source).

  7. Ack. On a duplicate the same steps run again; every step is idempotent.

Orphan objects

An R2 object that no row names is an orphan: a raw copy whose pointer never reached ingest, an attachment put after its message was erased, an outbound sent copy written for a send that was then refused, or a failed delete. Retention and erasure follow rows, so an orphan would otherwise live for ever (I9). Three rules keep them short-lived:

  1. Delete at the source. The duplicate rule above; email() step 7 and the staging steps delete the object when the enqueue fails; the outbound submit path deletes its sent copy on every refusal after it was written (Outbound › Composition).
  2. Compose markers. Before an outbound sent copy is written, the mailbox records meta['compose:{msg}'] in the transaction that takes the thread lock; the accept transaction deletes it. A marker older than 10 minutes with no messages row names an orphan.
  3. Rolling sweep. The mailbox’s daily maintenance alarm deletes the objects of stale compose markers, and of draft_att markers older than one hour whose attachment is in no draft row (Drafts § 7), then lists the next 5,000 keys under t/{tenant_id}/i/{identity_id}/ (continuing from meta.orphan_sweep_cursor, wrapping at the end) and deletes every key older than 15 days that no row names (messages.raw_r2_key, attachments.r2_key, attachments.text_r2_key, the outbound out/{msg}.eml of a messages row, uploads.r2_key, and the r2_key of each drafts.attachments_json entry, Drafts § 7), in BLOBS and, when configured, BACKUP. Fifteen days is longer than a queue or dead-letter queue keeps a message (14 days), so no pointer that could still be processed or redriven names a swept key. Each deletion increments r2_orphans_deleted_total. A mailbox of any size is covered within a bounded number of days, at a cost of five list calls a day.

The system identity’s mailbox

The system identity sends sign-in links and codes, invitation tokens (valid 7 days) and notification mail, and receives bounces and replies that quote them. Its mailbox is the deployment’s, not the default tenant’s, so it is kept out of every tenant-facing path (A15). MailboxRequest::Init records meta.is_system = '1' for it, and the mailbox then:

  • stores bodies redacted: in text, extracted_text, html_sanitized, snippet and every attachment text, each URL is replaced by [link] and each run of 6 or more digits (alone or split by spaces or dashes) by [code], before the row is written, for inbound and outbound messages alike (the flag body_redacted is set). Its outbound sent copy out/{msg}.eml, which holds the real token, is deleted as soon as the message leaves queued; its inbound raw MIME follows the identity’s fixed 7-day raw retention;
  • is never indexed: no FTS rows, no refs, no Embed, AttachmentText or Triage jobs (its triage_status is skipped, reason not_eligible);
  • never reaches tenant endpoints: the Fanout consumer delivers its events to platform endpoints only and never hands them to a Notifier (Webhooks › Endpoint resolution);
  • is outside every tenant fan-out: tenant search and its agentic tools skip it (Search § 10), MCP reaches it only through those same handlers, and a subject-access export never includes it. Only a platform key reads it, by ID; person deletion still erases the mail sent to that person (Privacy § 6.9).

Attachment safety

core::attach classifies every attachment before anything else touches it (B10). Risky attachments are never passed to agents or to text extraction, and downloading one needs quarantine:review.

Sniffing

The type is sniffed from the first 8 KiB (and, for containers, from the structure). The sniffed type wins over the declared Content-Type and the filename extension.

Container parsers. core runs on wasm32, and flate2 is allowed for native code only, so the container checks use two pure-Rust crates (crates.io sparse index, read 2026-10-10): miniz_oxide = { version = "=0.9.1", default-features = false, features = ["with-alloc"] } (published 2026-03-13; DEFLATE inflation only, with no std) and cfb = "=0.15.0" (published 2026-09-18, more than two weeks before; OLE compound-file directories; its dependencies fnv, uuid and web-time build for wasm32). What each check reads:

  • ZIP: the central directory and local headers are read without inflating anything (names, sizes, the encryption bit). Only three kinds of entry are inflated, each capped at 1 MiB of output: an OOXML [Content_Types].xml, an ODF META-INF/manifest.xml, and one level of nested ZIP for the executable-name check. An entry that would inflate beyond its cap counts as archive_bomb.
  • OLE: cfb lists the stream and storage names (VBA, _VBA_PROJECT, EncryptionInfo, EncryptedPackage); no stream content is read.
  • gzip: the trailer’s ISIZE only; PDF: a byte scan for /Encrypt in the trailer and in cross-reference stream dictionaries (which are not compressed).

Spike S4 measures the bundle with both crates.

MagicSniffed type
%PDF-application/pdf
PK\x03\x04ZIP; refined by entries: [Content_Types].xml with word/, xl/, ppt/ → OOXML document, spreadsheet, presentation; mimetype entry → ODF; META-INF/MANIFEST.MF → JAR; AndroidManifest.xml → APK
D0 CF 11 E0 A1 B1 1A E1OLE compound file (DOC, XLS, PPT, MSG, MSI); refined by stream names
MZPE executable
7F 45 4C 46ELF executable
FE ED FA CE, FE ED FA CF, CE FA ED FE, CF FA ED FE, CA FE BA BEMach-O executable
#!script
Rar!\x1A\x07RAR
7z\xBC\xAF\x27\x1C7z
1F 8Bgzip
MSCFCAB
4C 00 00 00 01 14 02 00Windows shortcut (LNK)
CD001 at offset 0x8001ISO 9660 image
78 9F 3E 22TNEF
{\rtfRTF
\x89PNG, FF D8 FF, GIF8, RIFF….WEBP, II*\0 / MM\0*, ….ftypheicimages
BEGIN:VCALENDARcalendar
<!doctype html or <html within the first 512 bytes after whitespaceHTML
none of the above, valid UTF-8text

Risk classification

riskConditionQuarantines
executableSniffed PE, ELF, Mach-O, script, MSI, LNK, JAR, APK, ISO; or an extension in exe dll scr com bat cmd ps1 psm1 vbs vbe js jse wsf wsh hta msi msp lnk jar apk app dmg iso img vhd vhdx reg cpl pif sh scf url whatever the content; or a ZIP whose entries (or the entries of one nested ZIP) include such a name or typeyes
macroOOXML with a vbaProject.bin part; OLE with a VBA storage or _VBA_PROJECT stream; extensions docm dotm xlsm xltm xlam pptm potm ppam sldmyes
archive_bombZIP central directory: total uncompressed size > 100 MB, or ratio uncompressed/compressed > 100, or more than 10,000 entries, or nested archives deeper than 2; gzip: the trailer’s ISIZE against the compressed size by the same ratioyes
encrypted_archiveA ZIP entry with the encryption bit (general purpose flag bit 0) set; or an archive whose contents cannot be inspected: RAR, 7z, CAByes
type_mismatchThe sniffed family is archive, HTML, script or a macro-capable document while the extension or declared type names a different family (for example invoice.pdf that is a ZIP or HTML). A harmless mismatch (declared application/octet-stream, image declared as another image type) is not a riskyes
encrypted_documentPDF with an /Encrypt dictionary; OLE with EncryptionInfo and EncryptedPackage streams (encrypted OOXML); ODF with encryption-data in its manifestno: text extraction is skipped, download needs quarantine:review

When several apply, the first in the table is recorded. Filenames are sanitised before storage: path components removed, control characters removed, at most 255 bytes.

Malware scanner hook (PM_SCANNER_URL, P1)

When PM_SCANNER_URL is set, the consumer scans each attachment that has no risk and is at most 20 MB, before ingest, so the quarantine decision includes the result:

POST {PM_SCANNER_URL}
Content-Type: application/octet-stream
X-Pylota-Attachment-Sha256: 9f86d081884c7d65…
X-Pylota-Sniffed-Type: application/pdf
User-Agent: PylotaIdentity/1.0

<attachment bytes>
{ "verdict": "clean" }                     // or "infected", or "error"
{ "verdict": "infected", "signature": "Eicar-Test-Signature" }
  • The URL is validated at isolate start and before each request by the SSRF guard of Security § 9 (HTTPS, a public address). Credentials, if any, are part of the URL path chosen by the operator; the URL is never logged.
  • Timeout 30 s per attachment, 60 s per message; no redirects; response body read up to 4 KB.
  • clean → scan_status = 'clean'; infected → scan_status = 'infected' and the message is quarantined (risky_attachment); error, a non-2xx status, a timeout or an unparseable body → scan_status = 'error', the message is not quarantined for it, and scanner_error_total is incremented.
  • Without a scanner, scan_status stays skipped. The value pending is not used in v1.0.

The same hook scans uploads, whole, up to 26,214,400 bytes (Uploads § 4.3).

Attachment text extraction

pm-index job AttachmentText { tenant_id, identity_id, message_id } processes every attachment of the message whose text_status = 'pending' (FR-IN-8). One job per message keeps the keyword index rebuild to one transaction.

Eligibility (decided at ingest; skipped otherwise): no risk, or only encrypted_document (then skipped); scan_status not infected; size ≤ 20 MB; the sniffed family is in inbound.extract_attachment_text (pdf, office, text, html), or is an image and inbound.extract_image_text is true; inline images under 10 KB (signature logos) are skipped.

Extraction by family:

FamilyHow
text (text/plain, text/csv, text/markdown, application/json, text/xml)Decoded in Rust (declared charset, else UTF-8 with replacement); one page
htmlcore::text::derive_text after sanitising; one page
message/rfc822 (nested)core parser: a header block (From, Date, Subject), the nested extracted text, the nested attachment filenames; one page
pdf, office (docx, xlsx, xlsm, xlsb, xls, ods, odt), imagesAi::to_markdown with [{ name: sanitised filename, blob }]. Workers AI’s converter supports PDF, images, HTML, XML, CSV, these spreadsheet formats, DOCX, ODT and ODS; it does not list DOC, PPT or PPTX, which get unavailable (supported formats, read 2026-10-09). Image conversion runs Workers AI models and may cost neurons, which is why extract_image_text defaults to false

Pages. The stored text is Markdown with a marker line before each page:

<!-- pm:page 1 -->
INVOICE 88213 …
<!-- pm:page 2 -->
Terms and conditions …

For PDFs, the call passes conversionOptions: { pdf: { metadata: false } }, so the output has no metadata section (Conversion options, read 2026-10-10). The primary rule is the converter’s own page headings: Workers AI’s published PDF output has a ## Contents heading followed by one ### Page N heading per page (Markdown conversion changelog, 20 March 2025, read 2026-10-10). Each line that is exactly ### Page N (N a positive integer, increasing) starts page N, the heading line itself is replaced by the <!-- pm:page N --> marker, and a leading # {filename} and ## Contents are dropped. Fallback, when the output has no such heading: a form feed (U+000C) is a page boundary; with neither, the whole document is page 1. A ### Page N line inside the text of a page whose N does not follow the previous page is ordinary text. Spike S6 confirms the heading form from Rust; if it differs, the observed form replaces the primary rule here.

Limits (limits): input over 20 MB, more than 200 pages, or more than 2 MB of text → text_status = 'unavailable'. The hidden-character rules are applied to the text.

Result. The job writes t/{ten}/i/{idn}/m/{msg}/a/{att}.md to R2, then sends MailboxRequest::AttachmentTextReady { message_id, items: [{ attachment_id, status, pages, text_r2_key, refs, steering }], fts_text }, and, with the items, the steering signals of each text (core::injection::scan over at most 256 KiB per attachment, Screening hold §8). In one transaction the mailbox sets text_status, text_r2_key and text_pages, inserts the refs with source = att:{id}:{page}, and rebuilds the message’s FTS row with fts_text (filenames plus attachment text, at most 1 MiB) in the attachments column, as specified in Search. It then queues an Embed job for the attachment chunks. When the message no longer exists, or its ID is in erased_ids (an erasure ran while the job converted), the mailbox answers Erased and writes nothing, and the job deletes the .md objects it wrote before acking (I10). When the message has a screenings row and the new signals, with the stored ones, are decisive, the same transaction applies the late-content rule of Screening hold §8.

Failure (B12). A toMarkdown error, an error result, or no answer within 60 s: re-enqueue the job with attempt + 1 after 60 s, then 300 s; after the third attempt, unavailable. The attachment stays fetchable. Search reports attachment_text_unavailable in why when relevant.

DSN routing and backscatter

A message classified dsn updates delivery state instead of reaching agents (FR-IN-6, FR-DLV-5, D4). Most bounces of our own mail arrive as Email Sending delivery events, because the provider owns the envelope sender (Outbound › Delivery events); DSNs reach an identity’s address only from servers that bounce to the From address, or as backscatter.

Sends through an smtp_relay are the exception: a relay reports no delivery events, and its return path is the From address, so every bounce of such a send is an RFC 3464 DSN that comes back to the identity through forwarding or SES (Domains on any DNS host § 5.4, N19). The SMTP transport stores the composed Message-ID as rfc_message_id (Outbound › SMTP relay), so step 1 below finds the original by the DSN’s original Message-ID. For a trusted DSN (below) the recipients’ statuses move from submitted to bounced (hard for 5.x.x, with a 30-day suppression; soft for 4.x.x), and the DSN is stored as in step 4, never shown to agents as new mail.

Anyone can write a DSN. A message classified dsn that names one of our outbound Message-IDs is easy to forge: the ID is in every copy a recipient received. If it were trusted, a forger could mark every recipient of a send as hard-bounced, create suppressions in the tenant, and pause the identity (11 bounces in 200, Outbound › Abuse auto-pause), which on a partner’s tenant only a platform key can undo. So a DSN changes delivery state only when it is trusted (D11):

  • the original was sent through a transport with no provider events, which today means provider = 'smtp' (an smtp_relay domain). For Cloudflare and SES sends the provider’s own events are the only source of delivery state, and a DSN about them is ignored;
  • the DSN’s verdict is pass;
  • the organisational domain of the DSN’s From equals the organisational domain of the final_recipient it reports on (the recipient’s own mail system), or the organisational domain of the relay host (the host in the original’s provider_message_id, smtp:{host}:{Message-ID});
  • the returned header part’s From (dsn.original_from) equals the original’s from_address.

A recipient entry that fails a condition is not applied. Even a trusted DSN never creates a permanent suppression on its own and never feeds abuse auto-pause.

Inside ingest, before any write:

  1. Find the original:

    SELECT rowid, id, thread_seq, provider, provider_message_id, from_address FROM messages
    WHERE direction = 'outbound' AND (rfc_message_id = ?1 OR provider_message_id = ?1)
    ORDER BY rowid DESC LIMIT 1;           -- ?1 = dsn.original_message_id (normalised)
    
  2. No match → backscatter. Return Backscatter. The consumer deletes the raw object, increments backscatter_total, and acks. Nothing is stored.

  3. Match. Evaluate the trust conditions above. For each dsn.recipients[] entry (the first 100) whose final_recipient is a recipient of the original and that passes them, apply a delivery event with event_id = "dsn:{message_id}:{recipient}" and source = Dsn through the same function as provider events (Outbound › Applying an event):

    ActionStatusDelivery status
    failed5.x.xbounced, bounce_type = 'hard'
    failed4.x.xbounced, bounce_type = 'soft'
    delayedanydeferred
    delivered, relayed, expandedanydelivered

    Entries that fail are counted in dsn_untrusted_total{reason} (provider_events, verdict, domain, from) and change nothing.

  4. Store the DSN itself as a message with kind = 'dsn', status = 'hidden', triage_status = 'skipped', in the original’s thread (no token or header threading), with the parsed report in automated_json.dsn and, when no entry was applied, the flag dsn_untrusted. No message.received event; an applied update emits message.bounced (or deferred, delivered). A trusted hard bounce returns a SuppressionRequest with reason hard_bounce and expires_at = now + 30 days, never permanent; the post-commit step writes it and emits suppression.created (Post-commit). The delivery consumer’s abuse windows never see DSN-derived outcomes: ApplyDeliveryEvent returns no outcome for source = Dsn.

Re-parsing (J3)

When a parser bug is fixed, parser_version (a constant in core::mime) is incremented and a reparse job is created (POST through the operator tooling; jobs.kind = 'reparse', params { tenant_id, identity_id?, before_version }). Its JobRunner steps (J3):

  1. list_identities: the identities in scope, cursor over identities.id.
  2. enqueue: per identity, page through SELECT id FROM messages WHERE direction = 'inbound' AND (parser_version IS NULL OR parser_version < ?1) AND rowid > ?2 ORDER BY rowid LIMIT 50 (a MailboxRequest read added by Privacy and erasure), sending one InboundJob::Reparse per message to pm-inbound, at most 500 per alarm run.
  3. wait: completes when the per-identity counts reported back reach the totals.

The consumer handles Reparse like Message, except: the raw object comes from the stored raw_r2_key (if it is past retention, the message is skipped and counted as raw_expired), and it calls MailboxRequest::Reparse, which in one transaction updates the parsed columns (text, html_sanitized, extracted_text, snippet, kind, automated_json, auth_json, verdict, flags_json with reprocessed added, parser_version, calendar_json, calendar_uid_hash), replaces the message’s refs and FTS rows, and matches attachments to existing rows by (sha256, part order) so attachment IDs never change. Thread membership is never changed. A message whose new decision would quarantine it (for example a newly detected risk) moves from received to quarantined; a re-parse never releases a message. The outbox gets message.received or message.quarantined again with data.reprocessed = true (one of the two: when the new parse’s steering scan also moves the message back to quarantine, the single message.quarantined carries rescreened: true too, after a message.screened; Screening hold §8), and calendar.received again with reprocessed: true when the calendar object changed. A re-parse of a message that is still screening answers Busy and is retried after 60 s; the new parse’s steering scan follows Screening hold §8.

Test-mode loopback (L3)

For a test tenant, the outbound loopback transport delivers mail to identities on the same deployment by writing the composed MIME to the recipient’s raw key and queuing an InboundPointer with loopback set (Outbound › Transports, FR-OUT-12, L3). Only the outbound consumer sets this field, and only for a recipient identity in the same tenant, or in another test tenant (mode = 'test') with the same non-null partner_id: loopback skips authentication and spam scoring, so it must never reach a live workspace’s mailbox (L3, G11). The consumer checks it again: a pointer whose loopback.tenant_id is neither the recipient’s tenant nor a test tenant of the same partner as a test recipient tenant (both re-read from D1 in step 1) is processed as ordinary mail, with full authentication and scoring, and loopback_refused_total is incremented. For an accepted loopback pointer the consumer:

  • skips the DNS prefetch and authentication; verdict = 'pass', auth_json = { "source": "loopback", … };
  • adds the flag loopback;
  • sets spam_base = 0 and skips rule 6 of the quarantine decision (risky attachments still quarantine);
  • otherwise runs the normal pipeline, so threading, references, events and triage behave as for real mail.

Read path and release

Every read, label change and release of mail is a MailboxRequest on the identity’s mailbox, after the handler’s scope check (Security § 5.2). The handler passes review, which is true only when the key holds quarantine:review; the mailbox never sees the key otherwise.

// crates/worker/src/mailbox/read.rs
pub enum ReadRequest {                      // variants of MailboxRequest
    ListThreads   { filters: ThreadFilters, limit: u32, cursor: Option<ListBoundary> },
    GetThread     { thread_id: String, messages_limit: u32, cursor: Option<ListBoundary>, include: Include, review: bool },
    ListMessages  { filters: MessageFilters, limit: u32, cursor: Option<ListBoundary>, review: bool },
    GetMessage    { message_id: String, include: Include, review: bool },
    UpdateMessage { message_id: String, labels_add: Vec<String>, labels_remove: Vec<String>, read: Option<bool>, review: bool,
                    label_events: Option<LabelEventContext> },
    UpdateThread  { thread_id: String, labels_add: Vec<String>, labels_remove: Vec<String>, read: Option<bool>, archived: Option<bool>,
                    label_events: Option<LabelEventContext> },
    BatchGet      { message_ids: Vec<String>, extracted_text_bytes: u32, review: bool },   // Parity additions § 2
    BatchUpdate   { message_ids: Vec<String>, labels_add: Vec<String>, labels_remove: Vec<String>,
                    read: Option<bool>, archived: Option<bool>, require_absent: Vec<String>, review: bool,
                    label_events: Option<LabelEventContext> },
    ListQuarantine { limit: u32, cursor: Option<ListBoundary> },
    Release       { message_id: String, actor: Actor, reason: String, key_release: KeyRelease },
    ConfirmStored { message_id: String },   // post-commit check (I10): Stored | Erased
}
pub struct ListBoundary { pub sort_ms: i64, pub key: i64 }   // the last row's sort time and seq or rowid
pub struct Include { pub quoted: bool, pub html: bool, pub headers: bool }
pub enum KeyRelease { NotAKey, Allowed }    // decided by the handler, below
pub struct LabelEventContext { pub actor: Actor, pub request_id: String, pub source: LabelSource }
                                            // None when the tenant's events.labels_changed is off

Visibility. A message is visible when its status is not quarantined, screening, hidden or throttled. Every visibility predicate below is built from core::visibility::not_visible_sql, written out here as NOT IN ('quarantined','screening','hidden','throttled') (Screening hold §9). Lists show visible messages only; ListMessages with an explicit status filter of quarantined, screening, hidden or throttled returns those messages only with review, and otherwise returns none with 200 (Security § 5.3). GetMessage of a message that is not visible answers message_not_found without review, the same as a missing ID.

Threads keep visible-only columns (Threading § 3.4), so a thread list never counts, dates or names mail an agent cannot see. A thread with no visible message has message_count = 0 and is never listed. ListThreads:

-- ?1 archived (0|1), ?2 limit + 1, ?3/?4 the boundary (last_at, seq) or NULL, then the filter parameters
SELECT t.seq, t.id, t.subject, t.participants_json, t.message_count, t.unread_count, t.first_at,
       t.last_at, t.last_inbound_at, t.category, t.needs_reply, t.urgency, t.archived, t.hold_json,
       lm.direction AS last_direction, lm.snippet
FROM threads t
JOIN messages lm ON lm.rowid = (SELECT m.rowid FROM messages m
                                WHERE m.thread_seq = t.seq
                                  AND m.status NOT IN ('quarantined','screening','hidden','throttled')
                                ORDER BY m.received_at DESC, m.rowid DESC LIMIT 1)
WHERE t.message_count > 0 AND t.archived = ?1
  AND (?3 IS NULL OR (t.last_at, t.seq) < (?3, ?4))
  AND (<filters>)
ORDER BY t.last_at DESC, t.seq DESC
LIMIT ?2;

The filters are fixed fragments: category = ?, needs_reply >= ?, unread_count > 0 (is_unread), lm.direction = ?, last_at >= ? and last_at < ? (after, before, resolved to UTC in the handler), and for label, EXISTS (SELECT 1 FROM labels l JOIN messages m ON m.rowid = l.message_rowid WHERE m.thread_seq = t.seq AND l.label = ? AND m.status NOT IN ('quarantined','screening','hidden','throttled')). A thread’s labels (the union over its visible messages) come from one more query per page:

SELECT m.thread_seq, l.label FROM labels l JOIN messages m ON m.rowid = l.message_rowid
WHERE m.thread_seq IN (SELECT value FROM json_each(?1))
  AND m.status NOT IN ('quarantined','screening','hidden','throttled')
GROUP BY m.thread_seq, l.label;

snippet and last_direction are therefore those of the latest visible message.

Messages. ListMessages orders by received_at DESC, rowid DESC with the same boundary rule, and the fixed filters thread_seq = (SELECT seq FROM threads WHERE id = ?), direction = ?, status = ?, EXISTS (… labels …), received_at >= ?, received_at < ?. GetThread returns the thread summary plus its visible messages oldest first (received_at ASC, rowid ASC, messages_limit per page; with review, also its quarantined and screening messages). Each message is built from its row, its attachments, labels, refs and, for outbound, deliveries. extracted_text is always included; text with include=quoted, html (from html_sanitized) with include=html.

include=headers. Header fields are not stored in SQLite: they are read from the raw MIME in R2 and parsed with the core parser (the first 200 fields, at most 64 KiB, each value cut to 2,048 bytes). Once the raw MIME is past raw_days (raw_r2_key is NULL), headers is null, and so it is for outbound messages whose sent copy was deleted (The system identity’s mailbox).

Cursors. Every list cursor uses the HMAC envelope of Search § 5.8 (keyring purpose cursor), with the payload ListCursorV1 { v: 1, list: "threads" | "thread_messages" | "messages" | "quarantine", qh, issued_at, last: ListBoundary } (the contacts list has its own boundary, Search § 12.1). qh is the first 16 bytes of SHA-256 over the list name, the canonical filters, the identity ID and the API key ID, so a cursor works only for the same list, filters and key. A cursor older than 24 hours gets 410 cursor_expired; a bad tag, kid or qh gets 400 invalid_request (details.errors[0].path = "cursor"). Lists are keyset-paginated newest first, so mail that arrives during pagination appears on the first page only and never shifts later pages.

Labels and read state (FR-IN-10). UpdateMessage and UpdateThread run in one transaction each:

  • labels_add: INSERT OR IGNORE INTO labels, refused with 400 invalid_request when a message would pass 64 labels; labels_remove: DELETE FROM labels WHERE message_rowid = ? AND label IN (SELECT value FROM json_each(?)). On a thread they apply to every visible message of the thread;
  • read: sets messages.read (on a thread: every visible inbound message), then recomputes threads.unread_count (visible inbound messages with read = 0);
  • archived (threads only): sets threads.archived. A new visible inbound message in an archived thread sets it back to 0.

They emit message.labels_changed when the handler passes label_events (Parity additions § 4): one event in the same transaction, naming only visible messages whose labels changed, none when only read or archived changed. UpdateMessage on a message that is not visible needs review (else message_not_found).

Batches (Parity additions § 2). BatchGet reads up to 100 messages in request order with a byte budget; BatchUpdate applies labels, read state and archiving to up to 100 messages in one transaction, with require_absent evaluated inside it, so two concurrent claims of one message give one updated and one conflicts. Both apply the visibility rule above per message (with review) and report every ID the key cannot see in not_found. The search operator is:unread and the list filter is_unread read the same columns.

Quarantine list. ListQuarantine (quarantine:review is checked by the handler):

SELECT … FROM messages
WHERE direction = 'inbound' AND status = 'quarantined'
  AND (?2 IS NULL OR (received_at, rowid) < (?2, ?3))
ORDER BY received_at DESC, rowid DESC LIMIT ?1;

Each item is a Message object with quarantine_reason.

Release. The handler first decides whether the caller may release (J14, J16): a person in the console always may (KeyRelease::NotAKey); an API key needs quarantine:review, and, when PM_QUARANTINE_KEY_RELEASE is off and PM_CONSOLE is on, the tenant’s policy.quarantine.key_release must be true and the key must be a platform key or the partner key of the tenant’s own partner (auth::people::key_may_decide, Workspace policy §3). Mail held by screening is released by the same rule (Screening hold §10). The policy is read from D1 for this request, never from a cache, immediately before the call; otherwise 403 permission_denied, and the mailbox is not called. The mailbox refuses a key actor whose request does not carry KeyRelease::Allowed. Then, in one transaction:

  1. Load the row. Not found, or erased → message_not_found. Status not quarantined (including hidden and throttled, which are never released) → 409 not_quarantined with details.status (and details.deadline_at for screening: a message still being screened is never released before its verdict, Screening hold §9).
  2. UPDATE messages SET status = 'received', quarantine_reason = NULL, triage_status = ?, triage_json = ?: pending and NULL when triage is enabled for the tenant (the handler passes the flag) and the kind is not dsn or mdn; otherwise skipped with the skipped record.
  3. Thread: recompute its visible columns (count, unread_count, last_at, last_inbound_at, participants_json, and subject when it is still empty), and update reply_from_address by the inbound rule of Threading § 5 as if the message had just arrived. An archived thread is unarchived.
  4. Verification: when the message has a verification match and its verdict is pass, insert the verifications row with expires_at = received_at + 24 h (none if that has passed). No verification.received event is emitted for a release.
  5. Outbox: message.released with released_by_key_id or released_by_user_id and reason; then, when received_evented_at is NULL, message.received with released: true and, when the message has a calendar object, calendar.received with released: true, and received_evented_at = now (Screening hold §10, Calendar invitations §4.4). For a message with a screening record, set its released_by_* and released_at.

The events of one release are in one transaction, so they have consecutive sequence numbers and none exists without the others. message.received is emitted exactly once per message, when it first becomes visible to agents (re-parse re-emissions, marked reprocessed: true, excepted): a message that was received before (one that a late signal or a re-parse moved back to quarantined) gets message.released only. A second release gets 409 not_quarantined and appends nothing.

After the commit the mailbox queues Triage { reason: Release } (when pending) and Embed { reason: Release }; the handler writes the quarantine.release audit row with the key or user. The message.received event reaches the Notifier through the webhook fan-out (Webhooks › Handing new mail to the Notifier).

Open points

  1. Suspended tenants on the SES source (FR-TEN-3): decided. SES has already accepted the message, so no temporary failure can reach the sender, and a later bounce would be backscatter. The consumer holds such mail for up to 5 days (ledger held, the S3 object kept inside its 14-day lifecycle) and ingests it if the tenant is resumed; after that it drops it without a bounce (table above).

Tests

TestCovers
it::inbound::a4_role_mail_routingpostmaster@ and abuse@ the platform domain become a new message from the system identity to PM_SECURITY_CONTACT (nothing stored in a tenant mailbox); with the variable unset they get 550 5.1.1; info@ the platform domain gets 550 5.1.1; postmaster@ a tenant domain goes to the owner, and to PM_SECURITY_CONTACT when the tenant has no owner or the owner’s address is on a deployment domain (A4)
it::inbound::d14_role_mail_relay_guardedThe 31st role message in an hour to one domain, and the 6th from one sender, get a temporary failure; a message carrying X-Pylota-Identity-Role-Hop, or from the system identity, gets 550 5.4.6; a relay of a message whose verdict is not pass, or that has a risky attachment, attaches only text/rfc822-headers; the same raw message delivered twice is relayed once (role: idempotency key); a suppressed PM_SECURITY_CONTACT ends in role_mail_failed_total with no retry; a PM_SECURITY_CONTACT on the platform domain counts as unset (D14)
it::inbound::a16_dictionary_guard50 messages in one second to random unknown addresses on one domain: the first 20 are looked up in D1 and get 550 5.1.1, the rest get a temporary failure with no D1 query; a known address that is cached still gets through; with D1 down, an address on a domain that is not a deployment domain gets 550 5.1.1 instead of being staged (A16, J7)
it::inbound::d11_forged_dsn_ignoredA DSN naming a Cloudflare- or SES-sent message changes no delivery and creates no suppression; for an SMTP-relay send, a DSN with verdict fail, from a domain aligned with neither the recipient nor the relay, or whose returned From differs, is ignored (dsn_untrusted); a trusted one marks the recipient bounced (hard) with a suppression that expires after 30 days, emits suppression.created once, and adds nothing to the abuse window, so eleven of them never pause the identity (D11, N19)
core::trust::d12_platform_domain_not_knownA pass sender on the platform domain from another tenant is not known_sender and carries shared_domain_sender; the same sender with outbound_count > 0 is known; a sender on the tenant’s own domain with pass is known; a platform-domain local part whose suffix folds to the receiving tenant’s suffix gets lookalike_domain (D12)
it::tenants::d12_suffix_confusable_refusedPOST /v1/tenants with a suffix whose fold is on the reserved list (.stripe, .str1pe, .p0stmaster) gets 400 address_reserved with details.field = "address_suffix"; one whose fold equals an existing tenant’s suffix fold (.acrne beside .acme) gets 409 suffix_taken; a distinct suffix is accepted; the console’s workspace form shows the same errors (D12, REST API › Tenants)
it::inbound::d13_unsolicited_flood_caps200 unauthenticated messages in an hour from 200 forged senders: the 121st onwards is throttled, with no event, triage or embedding; mail from a known correspondent in the same hour is received; 2,001 messages across a tenant’s identities throttle the rest; throttled mail is not counted in storage_gb; with TenantQuota unavailable mail is still stored (D13, D5)
it::inbound::panic_to_degradedA message whose full parse panics (a fault hook) is retried after retry_delay; its third attempt parses headers only and stores it with parse_degraded; a fresh message in the same batch is stored on its first attempt; under a 10-minute queue backlog a healthy message is still parsed in full (B2, FR-IN-3)
it::erasure::orphan_objects_sweptA sender’s retry of the same raw message leaves one raw object (the duplicate’s copy is deleted); a send refused after its sent copy was written (402, 429, thread_busy) leaves no out/ object; a compose marker left by a killed submit is cleaned by the next maintenance run; an orphan key older than 15 days is deleted by the rolling sweep, in BACKUP too; keys named by rows are never deleted (I9)
it::security::a15_system_mailbox_unreachableWith mail in the system identity’s mailbox: a tenant search, keyword or agentic, by a tenant or partner key of the default tenant never returns it; it has no FTS rows and no vectors; its events reach platform endpoints only and never a tenant endpoint or a Notifier; a subject-access export of the default tenant leaves it out; its stored bodies show [link] and [code] instead of the sign-in link and code, and its sent copy is gone once the message is submitted (A15)
it::messages::read_path_visible_threadsA thread whose only message is quarantined is not listed; after release it is, with the released message’s subject, snippet, last_direction, participants and unread_count; a hidden message never changes a thread’s counts; list cursors expire after 24 hours (410 cursor_expired) and refuse other filters or keys (400); include=headers returns null once the raw MIME is past raw_days (FR-IN-10, FR-IN-7)
it::messages::labels_and_read_statePATCH of a message and of a thread adds and removes labels and sets read state; is:unread and is_unread follow; the 65th label is 400 invalid_request; archiving a thread hides it from the default list until new visible mail arrives; a message that is not visible needs quarantine:review (FR-IN-10)
it::quarantine::release_transactionRelease moves the message to received, clears quarantine_reason, recomputes the thread, sets triage_status = 'pending' and queues Triage and Embed, inserts a verifications row for a pass code mail, emits message.released once, then message.received with released: true once, and writes the audit row; a second release gets 409 not_quarantined and appends nothing; a hidden message cannot be released (FR-IN-5)
it::inbound::a6_reject_codesUnknown and erased 550 5.1.1 (indistinguishable), retired 550 5.1.6, suspended tenant temporary failure for 5 days then 550 5.2.1 (A6, FR-IN-2, FR-TEN-3)
it::inbound::a2_forged_token_ignoredA forged +t… detail files by headers and never changes the identity (A2)
it::inbound::a9_two_identities_two_copiesTwo copies, same raw_sha256, exactly one is_primary_recipient = true (A9)
it::inbound::a10_bcc_copy_flaggedEnvelope recipient not in headers → is_bcc, flag bcc (A10; the reply side is it::send::a10_reply_all_excludes_bcc)
live::inbound::b1_oversize_rejectedCloudflare rejects over 25 MiB before the Worker (B1)
conf::mime::b2_*, core::mime::b2_capsMalformed MIME kept, depth 32 and 500 parts, parse_degraded (B2, FR-IN-3)
it::inbound::b3_missing_message_id, it::inbound::b3_same_id_same_body, it::inbound::b3_same_id_different_bodySynthetic ID; dedupe; both kept with message_id_conflict (B3)
conf::mime::b4_html_onlyText derived from HTML (FR-IN-7, B4)
conf::mime::b5_*Charsets and encodings (B5)
conf::mime::b6_*TNEF unpacked; nested message/rfc822 not merged (B6, FR-THR-2)
conf::mime::b7_cid, core::sanitize::b7_no_remote_fetchcid: images kept, remote src removed (B7)
conf::calendar::v*, core::classify::b8_mdn_request_ignoredCalendar parts read into the bounded, verified calendar object (Calendar invitations); MDN request recorded, never answered (B8)
conf::mime::b9_*Encrypted flagged with no body; signed-only processed (B9)
core::attach::b10_*Every row of the risk table, sniff wins over extension, quarantine (B10, FR-IN-5)
core::sanitize::b11_*Every hidden-element signal, hidden characters, emoji ZWJ kept, flag rule (B11, FR-IN-9)
it::index::b12_extraction_failureThree failed conversions → unavailable, attachment still fetchable (B12)
conf::mime::b13_from_anomaliesNo From; several From cap the verdict (B13)
it::inbound::b14_redelivery_dedupedSame raw twice → one row, one event (B14)
core::auth::d1_*No DMARC record gives none with aligned_by recorded; p=none gives unaligned; neither quarantines; every verdict-table row (D1)
core::auth::spf_unchecked_unverifiedWith PM_TRUSTED_AUTHSERV_ID empty, an SPF-only-aligned sender under p=reject gets unverified and auth_unverified, never fail; with the trusted header and spf=pass aligned it gets pass; the SES source is unaffected
core::trust::d2_*Display-name spoof and look-alike domain (D2)
it::inbound::d4_backscatter_droppedUnmatched DSN dropped and counted (D4, FR-DLV-5)
it::inbound::d5_sender_throttleThe 61st message in an hour from one sender is throttled (D5)
core::classify::d6_*RFC 3834, lists, out-of-office, hop counter (D6, FR-IN-6)
it::inbound::d7_blocked_hiddenA receive-blocked sender’s mail is stored hidden with no event; a suppressed sender’s mail (hard bounce, complaint, unsubscribe, provider) is stored received, evented, with the flag sender_suppressed (D7)
it::inbound::receive_allow_skips_spamA sender on the tenant’s receive-allow list (address or @domain) is not quarantined for its spam score, and is still quarantined when authentication fails (build plan M9, with the lists API)
it::inbound::nfr_rel1_no_loss_canaryUnder the J1, J2 and J7 fault injections, every message email() accepted carries a canary token, and once the queues drain each canary is found exactly once through the read API; inbound_raw_missing_total stays 0 (NFR-REL-1, build plan M7)
core::auth::d9_forged_ar_ignoredA lower header with the trusted authserv-id, and any other authserv-id, are ignored (D9)
it::inbound::e5_unsolicited_otpOTP mail without a wait in 30 minutes is quarantined otp_unsolicited; with one it is received and its code is released only to wait (E5, E4)
core::refs::f5_*Plate normalisation and every pack kind (F5, FR-SRCH-4)
core::quote::quote_headers_by_languageEvery quote pattern in the table, Outlook blocks, signatures, fallbacks
it::inbound::fts_same_transactionA keyword search immediately after the message.received event finds the message (FR-SRCH-2)
it::inbound::j1_r2_failureR2 put fails three times → the handler errors (temporary failure) and nothing is queued (J1, FR-IN-1)
it::inbound::j2_retry_idempotentThe consumer crashes after ingest; the retry stores nothing twice and writes the attachments (J2)
it::jobs::j3_reparseRe-parse updates parsed fields, keeps IDs and thread, re-emits with reprocessed: true (J3)
it::inbound::j7_d1_transientD1 down in email() → staged, routed by the consumer, unroutable staged mail dropped (J7)
it::inbound::j7_staging_outlives_dlqA staged message whose pointer is dead-lettered and redriven 14 days later (fake clock) is still routed and stored: the object is not deleted before 15 days, and the staging step re-queues it daily meanwhile (J7)
it::ses::push_and_backstop_once, it::ses::unknown_recipient_dropped, it::ses::cross_tenant_recipientsOne message per object and recipient; unknown recipients dropped with no bounce; recipients of two tenants stay apart (N3, N6, N28)
it::ses::verdict_mapping, it::ses::large_message_40mbSPF from SES, DKIM and DMARC recomputed, virus FAIL quarantined, spam FAIL scores 0.9; a 39 MB message is ingested (N5, N27)
it::inbound::probe_and_forwarding_checkpm-probe+{token} and a forwarding-check token are recorded on the domain’s monitor and never stored as messages; an unknown forwarding token is ordinary mail; mail sent straight to the platform address with the external address in To leaves forwarding unchanged (N12, N18)
it::smtp::dsn_to_bounceAn RFC 3464 DSN for a relay send → bounced (hard), a suppression, the DSN stored hidden (N19)
it::testmode::l3_loopbackTest-tenant mail to an identity of the same tenant, or of another test tenant of the same partner, arrives with verdict: pass and flag loopback; a send to an identity of a live tenant of the same partner, or of any other tenant, gets 403 test_mode_recipient; a forged loopback pointer for another tenant is processed with full authentication (L3)
it::logs::i5_no_content_in_logsNo body text, subject or clear address in captured logs (I5, FR-PRV-6)