Design
The design documents are binding. A coding agent implements what they say. When the code and a
design disagree, the design wins until an ADR changes it (see AGENTS.md). When two
pages disagree with each other, Precedence below decides which one wins. Each
document cites requirement IDs from the PRD and rows from the
edge-case register, and ends with a Tests section that maps them to named tests.
The public contracts live in the reference section and are not repeated here: REST API, Errors, Webhook events, Configuration and Limits. The storage schema is in Data model.
Precedence
When two pages disagree, one rule decides which wins:
| Kind of behaviour | Examples | Wins | Must match it |
|---|---|---|---|
| Wire behaviour: what a client sends and receives | Paths and methods, status codes, error codes, request and response fields, enums, defaults and bounds, required permissions and key levels | openapi.yaml | The design pages and the other reference pages (REST API, Errors, MCP, the guides) |
| Internal behaviour: what happens inside the service | Storage, state machines, algorithms, retry schedules, Durable Object requests, queue messages, logs and metrics | The design page that owns the area | The other design pages, the guides and the reference prose |
Agents follow it as a rule: for wire behaviour, openapi.yaml wins and the design must match; for
internal behaviour, the design page wins. A disagreement is a documentation bug, never a choice for the
implementer: fix the losing page in the same pull request, and write an ADR only when the winning page is
itself wrong (Decision records).
Index
| Document | What it decides |
|---|---|
| Rust workspace and platform | The Cargo workspace, crate boundaries and allowed dependencies, exact dependency pins, the release profile, wasm32 constraints, the platform trait set (clock, randomness, D1, Durable Objects, R2, Queues, Workers AI, Vectorize, email, rate limits, DNS-over-HTTPS, HTTP), the wasm-bindgen externs that fill workers-rs gaps, the generated wrangler.toml, the xtask commands, the CI pipeline and the Rust SDK (FR-SDK-1). |
| Data model | Every D1 table, every Durable Object SQLite table, R2 keys and the Vectorize index. It is the source of truth for migrations. The other designs refer to its tables and columns by name. |
| Inbound pipeline | The email() handler (normalisation, directory lookup, reject codes, the R2 write before acknowledgement), the pm-inbound consumer (MIME parsing under caps, sanitising, text derivation, quote and signature stripping, hidden-text removal, reference extraction, automation classification, the authentication verdict, spam score, quarantine), the IdentityMailbox.ingest transaction, attachment safety and text extraction, DSN routing, re-parsing and test-mode loopback. |
| Screening hold for agent-steering mail | The screening gate on inbound mail: policy, the steering scan and severity, quarantine rule 6a, the pm-screen job and classifier, the deadline alarm and backstop, verdict commits, late content, visibility, release, feedback, the per-tenant summary, events and Pylota’s use (FR-SCR-1–12). |
| Calendar invitations | Reading, bounding and verifying inbound iCalendar (iMIP, iTIP) into the message’s calendar object, time-zone resolution, the calendar.received event, threading by UID, iMIP sends from caller-supplied objects with organizer binding and the stale-sequence guard, and the calendar-reply route. No calendar store. |
| Outbound and safe retries | The send path from request to transport: the idempotency fingerprint and reservation, the ordered policy pipeline with its error codes, message composition (From, Reply-To with thread token, threading headers, signature and disclosure, marketing headers, attachments), the thread lock, the MailTransport trait and its implementations, the classification of every transport outcome, delivery events and status roll-up, suppressions, abuse auto-pause, uncertain-send reconciliation, cancel and resolve, SES specifics and the outbound Message-ID strategy. |
| Drafts, approvals and scheduled send | Drafts in the identity’s mailbox with revisions and etags, the content-free D1 index, the approval policy and approval bound to a digest of the content, person-only approval where only people may release quarantine, sending through the one send pipeline with the key draft:{draft_id}:{revision}, scheduled send on the mailbox alarm with its watchdog, attachments, the sources of replies and forwards, privacy, events, the console’s drafts pages, MCP and the CLI (FR-DRF-1–14). |
| Uploads | Staging a file once per identity: the create route and the signed PUT to the Worker, streaming into R2 with the declared size and SHA-256 verified, classification and scanning, attaching by upload_id to sends and drafts, expiry, limits, erasure, MCP and the CLI. Not a file store (FR-UPL-1–12). |
| Deliverability metrics | GET /v1/metrics/rates: every window that can pause sending, with its threshold, counts and headroom, computed in TenantQuota by the function that decides the pauses; GET /v1/metrics/events: hourly and daily event counts that each mailbox writes with its events; visibility, the console, MCP and the CLI (FR-MET-1–10). |
| Threading | The thread token’s exact byte layout and verification, key rotation, the thread resolution order, Message-ID normalisation, subject normalisation, forwarded messages, participants, and which address a reply is sent from (including fallback-pinned threads). |
| Identities, addresses and domains | The identity and address state machines (promote, retire, rollback, retirement, tombstones), username validation with reserved and confusable detection, domain kinds and their onboarding against the Cloudflare and SES APIs, the DomainMonitor health state machine, fallback, domain removal, and the Cloudflare API token permissions. |
| Domains on any DNS host | The six connection methods and the kind, inbound and transport each one fixes; SES in both directions for domains at any DNS host (deployment set-up, the SNS push plus SQS backstop with the ses_ingest ledger, retired and unknown recipients); send_only forwarding; smtp_relay with its alignment probe; zone creation for dedicated domains; delegated subdomains; health checks per method, cost, and spikes S10–S12. |
| Agent signing keys and signed requests | Per-identity Ed25519 keys (generation, sealing, rotation with overlap, revocation, tombstones), agent assertions (JWT) and the per-identity JWKS, signed HTTP requests (Web Bot Auth, RFC 9421) with the deployment key and its signed key directory, the kill switch on pause and suspension, and spike S13. |
| Search | The query language and its typed parse tree, keyword search (FTS5, references, trigram fallback), semantic search (chunking, embeddings, Vectorize), hybrid fusion and reranking, agentic search with deterministic citation verification, facets, cursors, tenant fan-out and the index lifecycle. |
| Triage | Deterministic rules, the model call with fenced untrusted content, output schema validation, categories and risk flags, the thread roll-up and re-runs. |
| Webhooks and events | The transactional outbox and its dispatch alarm, the event envelope and payload builders, endpoint resolution, Standard Webhooks signing and secret storage, the SSRF-guarded HTTP client, the retry schedule, delivery logs, dead letters, auto-disable and replay. |
| Event feed and live stream | The per-tenant event log (TenantEvents), its cursors and visibility, GET /v1/events with long poll, durable consumers, the WebSocket stream (handshake, stream tokens, protocol, flow control, close codes, revalidation, hibernation), failure handling, erasure, MCP mail_events and the CLI. |
| MCP server | The Streamable HTTP endpoint at /mcp, authentication, tool definitions and their mapping to REST, permission filtering and the mail_search_strategy prompt. |
| CLI and setup | The idvy command tree, setup and deploy (resource creation, bundle verification, wrangler.toml rendering), doctor, profiles and output formats. |
| SDKs, skills and agent tooling | The TypeScript and JavaScript SDK @pylotahq/identity, the Python SDK pylota-identity and the Go SDK github.com/PILOTAAI/pylota-identity-go, each built in its own repository from this design (generated layers over openapi.yaml, retries with the same key and bytes, typed outcomes, webhook verification, event and stream helpers, phone and vault helpers, the vault consumer entry point, packaging and publishing), the shared conformance suite all SDKs run, agent skills and plugins checked against the contract, MCP annotations, client hints and the per-key tool allow-list, idvy mcp stdio, the CLI’s --schema, --query and idvy skills generate, and the framework guides (FR-SDK-2–15, FR-SDK-25–33). |
| Security | The threat model, key handling (the four key levels, partner keys included), tenant and partner isolation, secrets and their single purposes, SSRF and content-safety rules, and the attack test suite. |
| Privacy and erasure | Jurisdiction, retention sweeps, erasure jobs per scope with receipts and probes, legal holds and subject-access export. |
| Console and workspaces | The server-rendered console at /console: passwordless sign-in, sessions and CSRF, workspaces, members, roles and invitations, and the console’s pages. |
| Cloud sign-up, sign-in and first run | Hostnames for Pylota Identity Cloud, PM_SIGNUP and the waitlist, Google and GitHub sign-in, TOTP two-step verification and recovery codes, where people land after sign-in, the Overview and its first-run checklist, the Checkout return, and Cloud abuse controls. |
| Workspace policy | Who may write a tenant’s policy and how: the four writers, the field classes with platform and partner ceilings, the guard fields and the decisions reserved for people, the compare-and-set write with its audit row and tenant.policy_updated event, GET and PATCH /v1/tenants/{tenant_id}/policy, and the console’s policy page (FR-TEN-4). |
| Service sign-up ledger | The per-identity ledger of third-party accounts: requests, approval as a decision reserved for people, close and delete, the match rule that ties a verification email to an approved entry, quarantine rule 4a and the wait check, events, retention and erasure, and the console’s accounts page (FR-IDN-10). |
| Agent self-sign-up | Agent self-sign-up behind PM_AGENT_SIGNUP: the provisional workspace, the permission and policy overlays, verification by code, link or claim, refusal, expiry with erasure and the abuse controls (FR-ASU). |
| Plans, metering and billing | The plan catalog, allowances and atomic holds in TenantQuota, 402 billing_limit, the usage API, and Stripe checkout, portal and webhooks. |
| Notifications and usage alerts | Email to the people behind the agents: usage alerts, new-mail notifications, the daily “needs a person” email and account emails; per-person preferences, the per-tenant Notifier Durable Object (coalescing, schedules, caps), one-click unsubscribe, and bounces. |
| Observability and SLOs | Structured logs without content, metrics, alerts, SLOs, dead-letter handling through the platform API, and the runbooks. |
| Parity additions | Nine additions to existing designs: batch message reads and updates, identity-scope allow and block lists, opt-in label events, authentication detail on messages, trusted ARC sealers, per-identity message retention, webhook delivery headers, zone-file export and a documentation link in every error (FR-IN-13–15, FR-OUT-17, FR-WH-6, FR-WH-7, FR-PRV-7, FR-DOM-15, FR-API-3). |
| Phone numbers | Phone numbers on identities through Telnyx: onboarding once per tenant and country, a standing purchase budget a person sets and a one-call purchase, requests approved by people for everything else, capability facets, SMS with consent and US 10DLC, voice routes and approved calls, porting and the port-out guard, the nightly reconciler, money in GBP (FR-PHN-1–54, ADR 0020). |
| Agent credential vault | Logins, API keys and browser sessions used without reveal (ADR 0021): the honest trust model, items bound to approved ledger entries and exact origins, per-tenant X25519 keys with per-version data keys (HPKE) and optional partner custody, grants and uses approved by people and bound to a digest, one-use tickets, registered consumers with signed requests and sealed packets, the consumer contract vault-consumer/1 and its conformance fixtures, TOTP and email and SMS codes into fills, sessions, rotation, signing, console reveal, managed secrets for other services, the hash-chained audit, kill switches, erasure, MCP and the CLI, and the Pylota cut-over (FR-VLT-1–30). |
| Testing | The test layers (core::, conf::, it::, live::, and ts::, py:: and go:: for the SDKs, sdk::conformance:: for the shared suite), the conformance corpus, the workerd harness, fakes, fuzzing, quality gates and the cross-tenant attack suite. |
Shared conventions
These rules apply to every design. A design may add to them but never contradict them.
1. Layering
crates/api-types types only (serde, utoipa). No I/O. depends on: serde, utoipa
crates/core pure logic. No I/O, no clock, no randomness. depends on: api-types + pure crates
crates/platform traits + Cloudflare implementations + fakes. the ONLY crate that imports `worker`
crates/worker handlers, Durable Objects, consumers, transports. depends on: core, api-types, platform
corefunctions take everything they need as arguments: the current time asnow_ms: i64, random bytes as[u8; N], lookups as traits implemented by the caller (for exampleThreadLookupin Threading). They return decisions and data, never perform effects.corebuilds for the host and forwasm32-unknown-unknown.platformwraps every Cloudflare API behind a trait. Native tests use the in-memory fakes inplatform::fakes. No other crate names aworker::type, enforced bycargo xtask check-layering.workerorchestrates: it reads, callscoreto decide, writes, and schedules follow-up work. Business rules that can be expressed without I/O live incore, so they are unit-tested natively.
2. Errors and the error envelope
Every failure that reaches a client is an ApiError, serialised as the
error envelope:
// crates/api-types/src/errors.rs
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode { Unauthenticated, KeyExpired, KeyRevoked, PermissionDenied, ScopeDenied, /* …one
variant per code in errors.md… */ InternalError, UpstreamError, Unavailable, SearchDegraded, Timeout }
impl ErrorCode {
pub const fn http_status(self) -> u16; // from the errors.md tables
pub const fn retryable(self) -> bool; // from the errors.md tables, never decided at call sites
pub const fn default_fix(self) -> &'static str;
pub const fn anchor(self) -> &'static str; // "code-" + the code: its anchor on the errors page
}
pub struct ApiError {
pub code: ErrorCode,
pub message: String, // human text; never contains message content or addresses
pub fix: Option<String>, // overrides default_fix when more specific
pub details: Option<serde_json::Value>,
}
// Serialised with `docs` = "{PM_DOCS_URL}/reference/errors#" + code.anchor(), added by the serialiser in
// crates/worker/src/errors.rs, never by a call site (FR-API-3, Parity additions § 10).
-
corereturns domain errors (AddressError,PolicyError,QueryError, …). Each has oneimpl From<…> for ApiErrornext to the error type incore, so a rule and its error code are defined together. The impls live incorebecausecoredepends onapi-typesandapi-typesdepends on nothing of ours:api-typescannot name acoretype. -
platformreturnsPlatformError { kind, binding, detail }.detailis a short machine string and never contains content or clear-text addresses. The worker maps it:PlatformErrorKindErrorCodeUnavailable(D1 or a Durable Object overloaded, a binding refusing)unavailable(503, retryable)Timeout(an internal deadline)timeout(504, retryable)Upstream(a Cloudflare or SES REST API returned an unexpected status during a synchronous call)upstream_error(502, retryable)NotFoundfor an object the caller namedthe resource’s own *_not_foundcodeNotFoundfor an internal object,Corrupt,Internalinternal_error(500, retryable), logged withrequest_id -
Errors after a send was accepted are never HTTP errors. They become message statuses and
reasoncodes (Errors › Send failures after 202). -
A
404returned by the service always carries one of its own codes. Resources outside the key’s scope return the same*_not_foundas missing ones (NFR-SEC-1).
3. Time, randomness and IDs
- Clock. All time comes from
platform::Clock::now_ms()(Unix milliseconds,i64), implemented withDate.now(). In Workers,Date.now()advances only across I/O, so two reads in one synchronous block return the same value; designs rely on that only for “same transaction, same timestamp”.std::time::SystemTime::now()is never called in wasm code. - Randomness. All randomness comes from
platform::Rng(crypto.getRandomValues).coretakes random bytes as arguments. - IDs are
{prefix}_{ULID}(Data model › Conventions), generated only byplatform::Ids::new_id(prefix). The generator is monotonic within an isolate: if the clock has not advanced past the last ID’s millisecond, it reuses that millisecond and increments the 80-bit random part by one (moving to the next millisecond on overflow). Thereq_request ID is generated at the start of everyfetch,email,queue,scheduledandalarminvocation and carried through internal calls and logs.
4. Durable Object transactions
workers-rs 0.8.7 exposes SqlStorage::exec but not transactionSync (read 2026-10-09 from the
v0.8.7 source). Cloudflare documents ctx.storage.transactionSync(callback), which rolls back if the
callback throws, and forbids BEGIN/SAVEPOINT inside sql.exec()
(SQLite storage API, read
2026-10-09). platform therefore provides Sql::transaction_sync, a wasm-bindgen call to
ctx.storage.transactionSync (see Rust workspace). The rules:
- One write transaction per state change. Every write path in a Durable Object runs inside one
transaction_syncclosure. The closure is synchronous: no.await, no subrequests. - Decide before, re-check inside. Reads used to decide may happen before the transaction (for
example, while waiting on
TenantQuota), but every precondition is re-checked inside it, because other requests can interleave at any.await. - Effects after commit. R2 writes, queue sends, D1 writes and calls to other Durable Objects never run inside a transaction. Those that must happen before the state change (an R2 object the row will point to) run before it; the rest run after commit and are either idempotent or repaired by an alarm.
- Outbox in the same transaction. Every transaction that changes externally visible state appends
its events to the object’s
outboxtable inside the transaction (section 6). - One alarm, many purposes. An object has a single alarm. Each object keeps its pending wake-ups in
metaunderalarm:{purpose}(for examplealarm:outbox,alarm:check,alarm:claim,alarm:dispatch,alarm:maintenance,alarm:drafts,alarm:draft_index,alarm:screen,alarm:expiry,alarm:log_erase; Data model lists each object’s keys). After each transaction it sets the alarm to the earliest pending wake-up if that is earlier than the current alarm. Every mailbox has a dailyalarm:maintenancethat deletes expiredidempotencyrows,rate_windowsolder than 48 hours,verificationspastexpires_ator 1 hour pastconsumed_at,outboxrows past the tenant’sevents_days, unpins quiet fallback threads (Threading), and refreshes the database size inmeta.size_bytes(Data model › Mailbox notes). The alarm handler runs every due purpose, then re-arms. Handlers are idempotent, because Cloudflare delivers alarms at least once and retries a failed handler with exponential backoff from 2 seconds, up to six times (Alarms, read 2026-10-09). - Schema on wake. Each object applies its migrations on first access in a transaction, guarded by
meta.schema_version(J9). Every statement of a migration is idempotent (CREATE TABLE IF NOT EXISTS,CREATE INDEX IF NOT EXISTS,CREATE VIRTUAL TABLE IF NOT EXISTS, andINSERT OR IGNOREfor seededmetakeys), so a migration that ran but whoseschema_versionwrite was lost runs again without an error. - Limits. Durable Object SQLite allows 100 bound parameters per statement, 100 KB statements and 2 MB per row or value (limits, read 2026-10-09). Designs that store text cap it below those limits (see Inbound › Storage caps).
5. Internal Durable Object RPC
Durable Objects are called with a typed request enum over fetch to the stub. There is no other
entry point into an object. The one exception is TenantEvents, which also accepts a WebSocket upgrade at
GET https://do.internal/stream with the envelope in X-PM-Rpc, and the three hibernation handlers
(Event feed § 2.3).
// crates/worker/src/rpc.rs
#[derive(Serialize, Deserialize)]
pub struct RpcEnvelope<T> {
pub v: u8, // 1
pub tenant_id: Option<String>, // None only for platform-level DomainMonitor and SesControl calls
pub identity_id: Option<String>, // required for IdentityMailbox
pub request_id: String, // req_…
pub actor_key_id: Option<String>, // for audit
pub deadline_ms: i64, // absolute; the object refuses work past it
pub req: T,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum MailboxRequest {
Init(InitMailbox), // identity created: stores the owner (from the envelope) in meta,
// emits identity.created once (section 9)
Ingest(IngestInput), // inbound.md
Reparse(ReparseInput), // inbound.md, J3
AttachmentTextReady(AttachmentText), // inbound.md
Submit(SubmitInput), // outbound.md
BeginTransport(BeginTransport), // outbound.md: claim before calling a transport
RecordTransportOutcome(TransportOutcome),// outbound.md
ApplyDeliveryEvent(DeliveryEvent), // outbound.md
Cancel(CancelInput), Resolve(ResolveInput),
LearnMessageId(LearnMessageId), // outbound.md: Message-ID strategy B (journal copy)
RegisterWait(RegisterWait), // inbound.md › The wait handler: E5 registration, every 10 s
WaitPoll(WaitQuery), // inbound.md › The wait handler: one poll, every 1 s
EmitEvent(EmitEvent), // identity.* events written after a D1 change
GetEvents(GetEvents), // webhooks.md delivery and replay
CreateDraft(CreateDraftInput), UpdateDraft(UpdateDraftInput), DeleteDraft(DraftRef),
GetDraft, ListDrafts, ListDraftsByIds, // drafts.md
SendDraft(SendDraftInput), // drafts.md: a draft becomes a message through the Submit path
ApproveDraft(DecisionInput), RejectDraft(DecisionInput),
DraftsDue, // drafts.md: the watchdog wakes the mailbox for overdue drafts
// Read, search, triage, label and erasure operations are added by their designs, and so are those of
// screening, uploads, event counts and retention (screening.md, uploads.md, metrics.md,
// parity-additions.md).
}
pub struct InitMailbox {
pub created_at: i64, // identities.created_at; written to meta.created_at
pub created_event: EmitEvent, // identity.created, built by the handler from the rows its D1 batch wrote
pub message_hours: Option<u32>, // retention.message_hours of an identity created with it (parity-additions.md § 7.2)
}
pub struct EmitEvent {
pub event_id: String, // evt_…, derived from the rpc_intents row (section 9), so a re-sent call
// is absorbed by the outbox's ON CONFLICT (event_id) DO NOTHING
pub event_type: String, // identity.created | identity.updated | identity.paused | identity.resumed |
// identity.key_created | identity.key_rotated | identity.key_revoked
pub occurred_at: i64, // the D1 change time, kept across retries
pub data: serde_json::Value, // built by webhooks/envelope.rs (the identity_* builders) from D1 rows;
// thin, never message content
}
// The object appends the event to its outbox (webhooks.md › Appending) with Some(event_id), so the same
// event_id is stored once and its sequence is taken once.
// DomainRequest, JobRequest, QuotaRequest, SesControlRequest (domain-connections.md § 4.8),
// NotifierRequest (notifications.md § 3) and EventsRequest (event-feed.md § 2.3) follow the same pattern,
// and each starts with an `Init` variant that stores the owner in the object's `meta` (QuotaRequest:
// outbound.md › TenantQuota).
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RpcResult<T> { Ok(T), Err(ApiErrorBody) }
- The caller addresses the object with
id_from_string(<stored DO id>)(IDs are created withunique_id_with_jurisdictionand stored in D1, ADR 0002) and sendsPOST https://do.internal/rpcwith the JSON envelope. A handled result, success or error, is HTTP 200 withRpcResult. Any other status, or a thrown exception, is a platform failure (unavailable). - Tenant check. The handler compares
tenant_idandidentity_idwith the owner stored inmeta(written byInit). A mismatch returnsinternal_error, logs the security eventrpc_owner_mismatchwith both IDs, and incrementsrpc_owner_mismatch_total, which alerts at 1. The public handler has already checked scope against D1 before calling, so a mismatch is always a bug. - An object that has no owner yet accepts only
Init. An object markederased = '1'refuses everything withidentity_not_found. - The caller’s default deadline is 10 seconds (
Ingest,Submit,CreateDraftandUpdateDraft: 30 seconds). The object checksdeadline_msbefore starting a transaction and returnstimeoutif it has passed.
6. Transactional outbox
Every object with an outbox table (IdentityMailbox, DomainMonitor, JobRunner) emits events the
same way, detailed in Webhooks and events:
- Inside the state-change transaction: increment
meta.event_seq, build the full envelope (events) withsequence = event_seq, insert it intooutboxwithdispatched_at = NULL, and recordalarm:outbox = now. - The alarm writes
event_indexrows to D1 (INSERT OR IGNORE), sends onepm-webhooksmessage per event, then setsdispatched_at. - A crash between steps repeats step 2. Consumers deduplicate on the event ID, so delivery is at least once and never lost.
7. Idempotent queue consumers
Every queue is at least once. Every consumer is written so that processing the same message twice has the same effect as once:
| Queue | Message identity | How a repeat is absorbed |
|---|---|---|
pm-inbound | message_id (allocated in email()) | ingest deduplicates on raw_sha256 and returns the stored message; post-commit steps (R2 attachment writes, index jobs) are idempotent by key |
pm-outbound | message_id | The transport claim (BeginTransport) admits one transport call per message; a repeat finds the message no longer queued and acks |
pm-delivery-events | provider eventId | Stored in deliveries.provider_event_ids_json; a repeat is a no-op |
pm-webhooks | (endpoint_id, event_id, attempt) | Unique index on webhook_deliveries; a repeat attempt number is skipped; a Fanout appends to the tenant’s event log with INSERT OR IGNORE on the event ID |
pm-index | job kind + target + version | Each job checks the target’s status (chunks.status, attachments.text_status, triage version) before working |
pm-screen | message_id | ScreenLoad answers Skip once the record is decided; commits are guarded by status = 'pending'; the model cap counts a message once per day |
Rules for every consumer:
- Process messages one at a time within a batch, and
ack()each one after its effect has committed. - Retry counting never uses
Message.attempts.workers-rs0.8.7 does not expose it (itsMessagebinding has onlyid,timestamp,body,retryandack; read 2026-10-09 from the v0.8.7 source). A bounded retry schedule is implemented in one of two ways, named in each design:- Re-enqueue: the body carries
attempt: u32. On a known transient failure the consumer sends a new message withattempt + 1anddelay_secondsfrom the schedule (MessageBuilder::delay_seconds), then acks the current one. Used where the Worker has a producer binding for the queue. - Age: the consumer computes the age of the work from a timestamp it owns (a field in the body,
a provider event timestamp, or a stored row) and calls
retry_with_optionswith the schedule’s delay until the age limit is reached.
- Re-enqueue: the body carries
- An unexpected error (a bug, a panic) is logged and the message is left to the queue’s own retry
(
retry()), up to the queue’smax_retries, then the dead-letter queue, whose consumer records and alerts (J8). - A queue handler that returns an error fails the whole batch (and
workers-rs0.8.7’s own macros turn a returnedErrinto a panic). Handlers therefore ack or retry each message themselves and returnOk(()); the only deliberate error is the inbound temporary failure in Inbound, which the entry glue raises as a thrown exception (Rust workspace). - Queue bodies are JSON with
"v": 1and a"kind"tag. They carry IDs and pointers only, never message bodies, attachment content or subjects (Queues allow 128 KB per message; designs stay under 4 KB). - Consumers never trust a pointer’s scope blindly: they re-read the tenant and identity rows from D1 and check status before writing.
8. Logging
Logs never contain message bodies, subjects, attachment content or clear-text addresses (FR-PRV-6).
Addresses that must be correlated are logged as HMAC-SHA256(PM_HASH_KEY, address) truncated to 16 hex
characters. See Observability.
9. Durable Object calls after a D1 change
Some Durable Object calls must follow a D1 change, and a call made after the commit can fail: the Worker
can die, or the object can be overloaded. Without a record the object would stay without an owner (a
TenantQuota or a mailbox whose Init was lost accepts nothing else), or an identity event would be lost.
Each such call is therefore written down first, in the D1 table rpc_intents
(Data model), in the same D1 batch as the change:
| Change (handler) | Intent | Call |
|---|---|---|
Tenant created (handlers/tenants.rs, M5) | quota · init | QuotaRequest::Init { tenant_id } |
Identity created (handlers/identities.rs, M6) | mailbox · init | MailboxRequest::Init(InitMailbox), carrying identity.created |
| Identity updated, paused or resumed (M6) | mailbox · emit_event | MailboxRequest::EmitEvent with identity.updated, identity.paused or identity.resumed |
Tenant suspended or resumed (handlers/tenants.rs; M6 adds this to the M5 handler) | one mailbox · emit_event per identity paused or resumed, inserted with INSERT … SELECT from identities | identity.paused (reason: tenant_suspended) or identity.resumed |
Identity key created, rotated or revoked (handlers/identity_keys.rs, M25) | mailbox · emit_event | identity.key_created, identity.key_rotated or identity.key_revoked |
Identity retention set or cleared (handlers/identities.rs, M37) | mailbox · set_retention | MailboxRequest::SetRetention { message_hours, version }, version = identities.updated_at; the mailbox ignores an older version (Parity additions § 7.2) |
- Write. The intent’s
idis deterministic ({request_id}:{target_id}:{op}, or{request_id}:{identity_id}:{event_type}), andbody_jsonholds the request. An event’s ID is derived from it like the platform events’ IDs (Webhooks › Platform events): a ULID whose time isoccurred_atand whose random part is the first 10 bytes ofHMAC-SHA256(PM_HASH_KEY, "intent:" + id). So every attempt sends the sameevent_id. - Call. After the commit the handler makes the calls and deletes each intent whose call succeeded.
Before its own call to an object, it sends that object’s older intents still pending, oldest first,
so a mailbox appends an identity’s events in the order of their D1 changes and a later
identity.updatednever overtakes an earlier one. A failed call does not fail the request: the change is committed, and the answer is the normal one (201for a create). Until the object is initialised, a call to it is answered503 unavailable(retryable). - Repair. The every-minute cron (
crons/intents.rs) reads up to 100 rows withnext_at ≤ now, oldestoccurred_atfirst, sends them one object at a time in that order, deletes each that succeeds, and otherwise setsattempts + 1andnext_at = now + min(60 s × 2^attempts, 15 min). An object that answers that it is erased (identity_not_foundfrom an erased mailbox, or a tenant that iserasingorerased) also deletes the row. A row is never dropped otherwise, and a row older than one hour is logged asrpc_intent_stuckat each retry. - Idempotence.
Initfrom the same owner is a no-op that answersOk(another owner is refused, as section 5 says), and the mailbox emitsidentity.createdonce, from the firstInitit accepts.EmitEventappends with itsevent_id, which the outbox stores once. A repeat is therefore harmless, and an event is emitted exactly once into the outbox, from where delivery is at least once (section 6).
The Notifier is not in this table: it is minted by the every-minute cron for any tenant still at
notify_do_id = '' (Notifications). Nor is TenantEvents: the same
cron mints it for any tenant still at events_do_id = '', and its first caller initialises it, because a
queued append that waits loses nothing (Event feed § 2.1). Tests:
it::intents::j21_init_retried and it::intents::j21_identity_event_retried
(Identities and domains › Tests, J21).
Spikes
The spikes run in milestone M1 of the build plan against a scratch Cloudflare account. Each result is recorded in the design it affects, under a “Spike result” note with the date. A failed spike takes the listed fallback, and the design is updated before the build continues.
| Spike | Must prove | Pass criteria | Fallback | Affects |
|---|---|---|---|---|
| S1 Bindings smoke | From Rust with worker 0.8.7, through the platform::export_worker! entry glue (which replaces #[event] and #[durable_object], see Rust workspace): receive an email event and read from, to, headers and the raw stream; send with the send_email binding’s structured send() including replyTo, headers (In-Reply-To, References, Auto-Submitted, X-*) and attachments (attachment and inline with contentId); produce and consume Queues with delay_seconds and retry_with_options, and confirm that Message::timestamp() is unchanged across retries; DO SQLite with the transactionSync extern (a thrown error rolls back) and alarms; D1 batch; a multi-statement request to the D1 query API (POST /accounts/{a}/d1/database/{id}/query); and the response of the local wrangler dev email endpoint to a setReject (Testing §6.4); and one live send to two recipients, one of which a test domain refuses with 550 at RCPT, to see whether send() answers E_DELIVERY_FAILED and whether the other recipient still receives the message (Outbound › Transport outcome classification); and a raw EmailMessage send of a calendar message (multipart/alternative with text/plain and text/calendar; method=REQUEST; charset=UTF-8) to two arbitrary recipients: whether it is accepted, whether one EmailMessage can carry several envelope recipients, whether the text/calendar part and its method parameter arrive unchanged, and whether Cloudflare keeps the composed Message-ID (Calendar invitations §5.6) | Every call works from Rust. The returned messageId is captured. The E_DELIVERY_FAILED behaviour for several recipients is recorded in the outbound design; until it is, such an answer makes the send uncertain (provider_outcome_unknown), never rejected. A rolled-back transaction leaves no rows. A multi-statement D1 query-API request is atomic: when its last statement fails, none of the earlier statements’ rows remain | Raw MIME send (EmailMessage) built with mail-builder for any missing structured field. If the entry glue cannot replace the macros: an ADR allowing exactly one file, crates/worker/src/entry.rs, to use them (Rust workspace §2). If the D1 query API is not atomic: every migration file is made re-runnable and a CI lint enforces it (CLI and setup §8.5). transactionSync has no fallback; this is an accepted risk. The planned path is a wasm-bindgen call to ctx.storage.transactionSync, which Cloudflare documents with no restriction on the calling method beyond a SQLite-backed object (SQLite storage API, read 2026-10-09), so any JS method of the class, including the glue’s, may call it. If S1 shows otherwise, the build stops and an ADR is written before M4 continues. The owner accepted this risk on 2026-10-09. Calendar sends on the cloudflare transport stay refused with 422 transport_unavailable (calendar_needs_raw_mime); with one recipient per raw send, they are limited to one recipient (calendar_single_recipient). | Rust workspace, Outbound, CLI and setup, Calendar invitations |
| S2 Inbound failure semantics | What the sending MTA sees when email() throws, versus setReject (documented as a permanent error); which Authentication-Results headers reach the handler | Throwing yields a 4xx temporary failure and the sender retries. The exact SMTP reply text for both cases is recorded. Record which Authentication-Results authserv-id Cloudflare stamps on delivered mail (setup later writes it to PM_TRUSTED_AUTHSERV_ID, Inbound › Authentication verdict) | Throw only. The handler keeps its in-handler R2 retries (three attempts) and then throws, as designed, whatever the sender is shown; the spike result records the observed reply in Inbound. There is no forward() to a backup address: setup registers no Email Routing destination address (Identities and domains › Cloudflare API token), so none exists to forward to | Inbound |
| S3 FTS5 in DO SQLite | content='', contentless_delete=1, the trigram tokenizer, bm25() with six column weights, DELETE FROM fts WHERE rowid = ?, and renaming an FTS5 table (for the index swap in Search) | All work on the deployed runtime, not only on local workerd | External-content table fts_docs (Data model); disable trigram and rely on reference normalisation plus semantic fallback; without rename, the swap rebuilds fts in place | Data model, Search |
| S4 Wasm budget | Bundle size, cold start, CPU time and peak memory when parsing and verifying a 25 MiB message and a 40 MB message from the SES source (N5), and mail-auth verdict parity on the corpus | Compressed bundle ≤ 10 MiB (NFR-SEC-2), cold start under 1 s, both messages parsed under 128 MB peak and inside the CPU limit, DKIM and DMARC verdicts equal the reference implementation on every corpus message | Write attachments to R2 before parsing bodies; move heavy features behind cargo features; switch the release profile to opt-level = "z" | Rust workspace, Inbound |
| S5 MCP over rmcp | Streamable HTTP served from fetch using rmcp 3.4.1 protocol types, without a tokio runtime. Note: rmcp 3.4.1 (like 3.5.1) declares tokio (features sync, macros, rt, time) as a non-optional dependency (crates.io metadata, read 2026-10-10) | MCP Inspector and Claude Code connect, list tools and call one; the wasm build never starts a tokio runtime or timer, and the bundle stays inside the S4 budget | Implement the JSON-RPC types locally in worker; keep rmcp as a native dev-dependency for client tests. Taken in advance (ADR 0009): M1 still runs S5 against the local types to record the Inspector and Claude Code result | MCP server |
| S6 Externs and jurisdiction | Vectorize upsert, query (namespace and metadata filter), deleteByIds, getByIds and describe() (the vector count); AI.run with the gateway option, including the bge-m3 output shape, the reranker’s score form and the agent model’s chat-completions schema (Search); AI.toMarkdown (including whether PDF output marks page boundaries) — all through wasm-bindgen externs; DO IDs from unique_id_with_jurisdiction("eu") stored as strings and re-addressed with id_from_string | Every call works and each recorded shape matches the design, or the design is updated with the observed one. An EU object reports the EU jurisdiction (ctx.id.jurisdiction) | REST fallbacks (/vectorize/v2/…, /ai/run, /ai/tomarkdown) using PM_CF_API_TOKEN, which then becomes required (Rust workspace §7); one page per document when toMarkdown does not mark pages. If an EU object does not report the EU jurisdiction, the build stops for an owner decision, because FR-PRV-1 depends on it | Rust workspace, Inbound, Search |
| S7 Outbound Message-ID | The relationship between the messageId that send() returns and the Message-ID header recipients see | Either a deterministic mapping (strategy A), or the header learned from a journal copy (strategy B) | Strategy B: a hidden journal BCC to journal+{message ulid}.{identity ulid}@{PM_PLATFORM_DOMAIN}; the email handler records the header and drops the copy (Outbound). If a journal copy never arrives, that message matches replies by thread token and provider ID only | Outbound, Threading |
| S8 SES in wasm | SigV4 signing for SES v2 SendEmail with raw content, and SNS message signature verification (SignatureVersion 2; version 1 is refused), from Rust in wasm | A real send through SES in eu-west-2; a real SNS notification verified, and a tampered one rejected | SES leaves v1.0: an ADR moves send_only, dns_records, smtp_relay with inbound: ses and the SES failover to v1.1 | Outbound, Identities and domains |
| S9 Event subscriptions and onboarding APIs | Create an Email Sending event subscription to pm-delivery-events through the API for one domain (source type email.sending with zone_id and domain; this source shape appears in Wrangler’s source, not yet in the API reference), receive all six event types, delete it. Onboard a zone apex and a subdomain through POST /zones/{zone_id}/email/sending/subdomains, and enable routing on a subdomain through POST /zones/{zone_id}/email/routing/dns with name. A literal routing rule whose worker action value is the script name pylota-identity delivers to the Worker. A subdomain’s routing is enabled without touching the apex’s MX records, and removed on its own (unlock with PATCH …/email/routing/dns and name, delete its records by ID) while the zone’s other mail domains keep receiving; the zone-wide DELETE …/email/routing/dns is recorded, never used for one name. The error codes for a zone gone from the account, a 31st mail domain and an existing zone are recorded | Payload fields match Outbound › Delivery events; subscriptions can be created per domain at runtime with PM_CF_API_TOKEN; apex and subdomain onboarding both work through the API; a subdomain’s routing can be removed on its own | For cloudflare_zone and nameservers, the API creates the domain without a subscription, marks it delivery_events: "manual", sends from the platform address meanwhile, and returns its records with details.action = "run idvy domains subscribe <domain>"; delivery events start once that command has run. A subdomain whose routing cannot be removed on its own is left with no rules and listed by idvy doctor (routing.leftover_subdomains) (Identities and domains › Kind zone, tests it::domains::s9_manual_delivery_events and, for nameservers, it::domains::s9_manual_delivery_events_nameservers). Any onboarding step the API cannot do is listed by idvy domains add as a dashboard step and checked by idvy doctor | Identities and domains, Outbound, CLI and setup |
| S10 Child zones | On an Enterprise account, a subdomain-setup child zone accepts Email Routing catch-all to the Worker and Email Sending onboarding, and both work end to end. Optional: skipped when no Enterprise account is available (Build plan › Human prerequisites) | Mail to any address at the child apex reaches email(); a send is DKIM-aligned | delegated_subdomain stays off; dns_records covers the case | Domains on any DNS host |
| S11 SES receiving | Rule set, S3 action and topic as specified; the notification shape, including the objectKey form; S3 GetObject with SigV4 from a Worker; a 39 MB message (N5); user+tag@ routing; the retired-address bounce; the backstop picks up a message whose push failed | All pass in eu-west-2 | dns_records and smtp_relay with inbound: ses do not ship in v1.0; send_only still does | Domains on any DNS host |
| S12 SMTP from a Worker | Ports 465 and 587 with StartTls against two real providers; the certificate host name is checked (a wrong-name certificate is refused); timeouts and the uncertain window behave as designed | All pass | smtp_relay does not ship in v1.0 | Domains on any DNS host |
| S13 Web Bot Auth format | A request signed by core::httpsig with the deployment key (Signature-Agent as a quoted structured-field string; Signature-Input covering @authority, signature-agent and from, with tag="web-bot-auth", keyid = the JWK thumbprint, created, expires and a 64-byte nonce), sent to https://crawltest.com/cdn-cgi/web-bot-auth, which answers 401 for a well-formed message with an unknown key, 200 for a known key that verifies and 400 otherwise (Web Bot Auth, read 2026-10-09). Needs no Cloudflare account | 401 before the key directory is registered (well-formed, unknown key), never 400 | Signed HTTP requests stay off in v1.0: PM_WEB_BOT_AUTH cannot be turned on. Agent assertions are unaffected | Agent signing keys |
| S-VLT1 HPKE on wasm32 | hpke 0.14.1 (default-features = false; x25519, aes, alloc) builds for wasm32-unknown-unknown with randomness from platform::Rng, passes the RFC 9180 vectors for the suite, and seals and opens 1 MiB within 50 ms of CPU in a Worker | All vectors pass; within budget | The same suite in core::crypto::hpke from the pinned x25519-dalek, hkdf, sha2 and aes-gcm, checked against the same vectors (ADR 0021 decision 4) | Vault § 4.3 |
| S-VLT2 Audit sequence under contention | The guarded batch of Vault § 14.2 under 50 concurrent writers to one tenant, on wrangler dev and staging D1 | No gap or duplicate seq; every change with its row; retries within three | Serialise vault writes per tenant through TenantQuota | Vault § 14 |
| S-VLT3 Consumer signatures | RFC 9421 Ed25519 verification with core::httpsig and verify_strict, against RFC 9421 Appendix B and a fixed set of cross-language signature vectors (committed under sdks/fixtures/conformance/vault-consumer/, made with the Rust reference signer and checked against an independent Ed25519 implementation); the TypeScript, Python and Go helpers are checked against the same vectors later, in M46–M48 | All verify; tampered components fail | None needed | Vault § 8.4 |
The three S-VLT spikes run at the start of M42 and M43, not in M1, against staging (Vault § 24).