Skip to Content
JobWzrd Docs

Cloudflare System Design Proposal

Status: REVISION 3 — retargeted to a Cloudflare-native stack. Awaiting approval to run spikes S1–S7. No implementation authorized. Branch: cloudflare (single commit 0e340b3). Constraint honoured: server/ is read-only for this work.

What revision 3 is. Revision 2 designed around PostgreSQL on Neon through Hyperdrive, and was approved only for spikes. The owner has since fixed the driver: Cloudflare platform consolidation and architectural independence from Convex — one primary database (D1), one private object store (R2), Cloudflare-native async execution, no external primary database, no permanent Convex dependency.

That is not a vendor swap. D1 has no interactive transactions, no schemas, no row-level security, no FOR UPDATE SKIP LOCKED, and a single-threaded writer per database. Four of revision 2's central correctness arguments were built on Postgres features that do not exist here. They are re-derived from D1's actual semantics in §D, and every one of them has a spike that must prove it (§T).

Nothing below is approved for implementation. Seven spikes stand between this document and a green light.

Revision history

RevTargetVerdict
1Cloudflare compute + Neon Postgres via HyperdriveRejected: 7 critical findings
2Same, correctedApproved for spikes only
3Cloudflare-native: D1 + Pages + R2 + Queues + Workers AIAwaiting approval for S1–S7

Every number in this document is (a) counted from the tree, (b) quoted from Cloudflare documentation read for this revision, or (c) marked ASSUMPTION / UNKNOWN.


A. What must not change

These survive every architecture decision. They are the reason the migration exists and the reason it can fail.

#InvariantWhere it lives
A1Never claim an external effect that did not happen. A send returns sent / sent_unrecorded / uncertain / failed; unknown means may have been deliveredemail_drafts.status, the HTTP response, the UI
A2Caps are real and server-owned. 5 applies/day, 50 emails/day, one implementationcap_quota + the send path
A3Ownership is never taken from the client. The principal comes from the verified sessionmiddleware + composite FKs
A4AI output is a draft. No model output sets a status implying a senddraft state graph
A5Preference gates run before the money step. Missing preference row → fail closedsend + apply paths
A6The API surface is frozen for the duration: 58 paths, same shapes, same error envelopeopenapi.yaml
A7Dry-run is the default, CAPTCHAs are never auto-solved in the app/apply pathsapply engine
A8Erasure must actually erase, including objectsops_erasure_jobs

B. Current state (verified)

  • 42 defineTable declarations in server/convex/schema.ts (counted).
  • 58 paths in server/openapi.yaml.
  • 13 Next.js routes under app/app/**; 3 of them server-rendered (/, /login, /signup).
  • Owned tables: 22. Corpus: 3. Operational: 9. Plumbing: 1. Duplicate shape: 1. Legacy shim: 1. Dead/stub: 5. Sum 42.
  • The full per-table inventory, with destination and disposition, is DATA-MODEL-PROPOSAL.md §8 and is machine-reconciled by tools/check_table_inventory.py.

C. Focus audit

What is actually being asked: stop depending on Convex, and run the whole thing on one platform.

What that assumes is already answered: that Cloudflare's data layer can carry the integrity guarantees the PostgreSQL design leaned on. Revision 2 answered "yes, via Postgres semantics". Under D1 the question is open again, and it is the only question that matters. §D is the answer; §T is the proof plan.

Is it the right thing to build? The driver is now stated by the owner: consolidation and independence. That is a legitimate goal, and it is no longer a cost argument — which removes the objection that killed Architecture D in revision 1. The remaining risk is entirely technical, and it is testable.


D. What D1 actually changes

D.1 Verified behaviour (read for this revision)

FactConsequence
No interactive transactions. D1 is auto-commit; Better Auth's D1 dialect literally throws on beginTransaction. Atomicity comes from batch()Read-then-write logic cannot be expressed as a transaction with application code in the middle
batch() is a SQL transaction: statements execute sequentially, non-concurrently, and a failure rolls back the entire sequenceMulti-statement atomicity exists, but only as a static list of statements decided up front
Each database is single-threaded, backed by one Durable Object; a full request queue returns an "overloaded" errorWrites serialize globally per database. Throughput ≈ 1/query-duration
No schemas (public/corpus/ops are Postgres constructs)One namespace per database; prefix tables instead
No RLS, no SET ROLE, no rolesOwnership is a code + constraint property, never a database-enforced read filter
No FOR UPDATE / SKIP LOCKEDLeasing must be a guarded UPDATE … WHERE … RETURNING
Composite foreign keys, CHECK, partial unique indexes, expression indexes, ON CONFLICT … DO UPDATE, RETURNING are supported (SQLite)The constraint toolkit survives; the isolation toolkit does not
Limits: 10 GB (Paid) / 500 MB (Free); 30 s query; 1,000 queries per invocation (Paid) / 50 (Free); 2 MB row; 100 KB statement; 100 bound params; 50 MB resultA single 200-row ingest fits comfortably; a full-table rewrite does not
Sessions API gives sequential consistency, read-your-own-writes per session; default session is first-unconstrained, which may read a replicaA new staleness risk that Postgres did not have, with a per-session fix
Better Auth auto-detects a D1 binding and uses a built-in D1SqliteDialect with transaction = falseThe hardest item in revision 2 is now a supported path (§K.1)

D.2 The five mechanisms that do not survive, and what replaces them

#Revision 2 mechanism (Postgres)Why it fails on D1Replacement
1BEGIN … SET LOCAL app.user_id … COMMIT + RLSNo transactions to scope a session variable to; no RLS to read itOwnership by constraint + a single query layer. Composite (parent_id, owner_id) FKs make cross-owner edges unrepresentable; every query goes through a repository that requires an owner predicate
2SELECT … FOR UPDATE SKIP LOCKED for claimsNo row locks, no skip-lockedGuarded UPDATE … WHERE <claimable> … RETURNING, atomic because statements are serialized; zero rows returned = lost the race
3Counting INSERT … WHERE (SELECT count(*)) < capWas already wrong; on D1 the interleaving is different but the pattern is still a read-then-writeGuarded UPDATE on cap_quota with the guard in the statement, plus a CHECK (used <= limit_value) as a backstop
4Effect + completion in one interactive transaction, fenced by lease_idBatch order is static; you cannot decide mid-batchIdempotent effect first, guarded completion second. Ordering inverted, so a crash between them re-runs an idempotent no-op instead of losing work
5Two Hyperdrive bindings to separate the cache from tenant dataD1 has no query cache, but it does have read replicasTwo access classes: withPrimary (no session, primary only) for owner data and read-after-write; withCorpus (session, replicas allowed) for ownerless reads

D.3 The one rule that replaces transactionality

Revision 2 leaned on "these two writes happen together". D1 cannot always give that, so the design uses a weaker-but-sufficient ordering rule everywhere:

Idempotent effects run before the state flip that records them, never after.

A crash between them leaves the effect done and unrecorded, which the next attempt re-applies as a no-op, then records. The reverse order leaves work marked done and not done — the failure mode that lost messages in revision 1.

This is why corpus_job_sources and the ledger carry natural-key uniqueness: idempotence is what makes "effects first" safe.

D.4 What we lose, stated plainly

LostImpactMitigationResidual risk
RLSA missed WHERE owner_id = ? is a cross-tenant read. Postgres would have caught it at the databaseComposite FKs stop cross-owner writes; a single repository layer owns the predicate; a test enumerates every table with owner_id and asserts a query-layer entry existsThis is the biggest regression in the retarget. A bug in one repository function can leak. Named as limitation L-D1-1 and carried to spike S2
Interactive transactionsMulti-step business logic cannot decide-and-write atomicallybatch() for static sequences; guarded single statements for decide-and-writeA sequence whose statements depend on a runtime decision needs a compensating step
10 GB ceilingCorpus + logs + audit must fitLogs already leave the database (ADR-6); audit is bounded by retention; corpus is the growth driverA sizing trigger and a split plan (§D.5)
Single-threaded writesThroughput ceiling ≈ 1 / write-duration per databasebatch() amortises round trips; writes are few and smallAt 100× this still holds; measured, not assumed (R4)

D.5 Sizing and the split trigger

ComponentEstimateBasis
Product rows (100 users)< 100 MB22 tables × bounded rows/user
Corpus (postings)UNKNOWNR3 — average description bytes × growth rate were never measured
Audit + incidents< 50 MB with 400-day retentionbounded by write rate
R2 objectsnot in D1résumés, page bodies, exports

Split trigger, written down so it is a decision and not an improvisation: if corpus_jobs exceeds 4 GB, or write contention on the single writer produces "overloaded" errors under normal load, split corpus into a second D1 database and read it through the corpus access class only. The cost of the split is losing cross-database foreign keys between search_results.job_id and corpus_jobs.id — which the design already tolerates, because a saved job keeps a snapshot and a search result can be rebuilt by re-running the search.

Hard limit maths: at 10 GB the database refuses writes. That is a hard failure, so the split trigger is set at 40% of the ceiling, not 90%.


E. Target architecture

E.1 Deployment shape

                              BROWSER
                   one origin · Bearer JWT · no CORS
                                 │
  ┌──────────────────────────────┼─────────────────────────────────────────┐
  │ CLOUDFLARE                   ▼                                         │
  │  ┌───────────────────────────────────────────────┐                     │
  │  │ FRONTEND HOSTING: Cloudflare Pages            │                     │
  │  │  13 routes · SSR/SSG as S3 decides            │  ◄── S3 reports     │
  │  │  Pages Functions: /api/auth/*, /api/v1/* proxy│      compatibility  │
  │  │    · same-origin  · 256 KiB cap · x-request-id│      before commit  │
  │  │    · forwards signal + deadline               │                     │
  │  └───────────────┬───────────────────────────────┘                     │
  │                  │ service binding (env.API)                           │
  │                  ▼                                                     │
  │  ┌──────────────────────────────────────────────────────────────────┐  │
  │  │ API WORKER  (independent backend service)                        │  │
  │  │  · JWT verify via JWKS  (iss/aud/sub/exp)                        │  │
  │  │  · owner_id := sub   ← never from the body                       │  │
  │  │  · withPrimary() / withCorpus()   ← the only two doors           │  │
  │  │  · caps: guarded UPDATE   · sends: SYNCHRONOUS (never queued)     │  │
  │  │  · assets/content routes (R2)                                    │  │
  │  └───┬──────────────┬───────────────┬──────────────┬───────────────┘  │
  │      │              │               │              │                  │
  │      ▼              ▼               ▼              ▼                  │
  │ ┌──────────┐  ┌───────────┐  ┌──────────┐  ┌────────────┐            │
  │ │ D1       │  │ R2        │  │ KV       │  │ Queue      │            │
  │ │ primary  │  │ jw-blobs  │  │ JWKS cache│  │ jw-async   │            │
  │ │ (writes  │  │ logs/     │  │ public    │  │ + DLQ      │            │
  │ │  serial, │  │ u/<own>/  │  │ config    │  │ (+consumer │            │
  │ │  one DO) │  │ exports/  │  │ ONLY      │  │  Worker)   │            │
  │ └────┬─────┘  └───────────┘  └──────────┘  └─────┬──────┘            │
  │      │  ▲                                        │                  │
  │      │  └── replicas (corpus reads only)         │                  │
  │      │                                           ▼                  │
  │      │        ┌────────────────────────────────────────────┐         │
  │      │        │ ASYNC WORKER (separate, consumer only)      │         │
  │      │        │  consumer_deliveries state machine          │         │
  │      │        │  completed is the ONLY dedupe short-circuit │         │
  │      │        └────────────────────────────────────────────┘         │
  │      │                                                               │
  │ ┌────┴──────────────────────────────────────────────────────────┐     │
  │ │ Cron Triggers: outbox drain · reconciler→dlq_incidents ·       │     │
  │ │                Gmail poll · lease reaper · retention purge     │     │
  │ └───────────────────────────────────────────────────────────────┘     │
  │                                                                       │
  │ ┌────────────────────────┐   ┌───────────────────────────────────┐    │
  │ │ Workers AI (evaluated) │   │ Containers (evaluated)            │    │
  │ │  résumé→profile, rank, │   │  Go scraper · Python apply CLI    │    │
  │ │  classify, enrich      │   │  if Workers/WASM cannot host them │    │
  │ └────────────────────────┘   └───────────────────────────────────┘    │
  └───────────────────────────────────────────────────────────────────────┘
                    │                                    │
              Groq (opt-in fallback,      Gmail API (Google OAuth)
               never silent — S7)

E.2 Component responsibilities

ComponentOwnsMust never
Pages (frontend)Rendering, the client store, the demo/offline seamHold authoritative state, mint tokens, call D1 directly
Pages FunctionsSame-origin proxy for /api/v1/*, auth routes, size cap, correlation id, deadlineRoute, validate business fields, or retry
API WorkerAuthn/authz, all business rules, the API contract, the outbox writeTrust a client-supplied owner id, or do long CPU work inline
Async WorkerConsumer state machine, retries, DLQ persistenceHold the only record that work exists
D1Authoritative state, constraints, the outbox table, the lease tableHold logs, blobs, or prompt bodies
R2Résumés, avatars, page bodies, export artifacts, log archiveServe private objects without a signed URL
KVJWKS and public config onlyHold anything on a path that decides an external effect (eventual consistency)
QueuesTransport for idempotent workCarry a send, or be the only record that work exists
CronSweeps, reconciliation, the Gmail pollCall an authenticated user path
Workers AIModel inference behind the provider seamReceive content unless the owner opted in
ContainersGo/Python execution if native Workers cannot host itDecide what to write

KV is deliberately tiny. Eventual consistency is unacceptable for anything that gates a cap, a send, an authorization decision or a state machine, so KV holds a JWKS cache and public configuration and nothing else. That is a rule, not a preference.

E.3 Trust boundaries

BoundaryThreatControl
Browser → PagesForged identity, oversized bodyBearer JWT verified downstream; 256 KiB cap at the proxy and again in the API
Pages → API WorkerHeader smugglingService binding only; the API re-verifies the token and re-derives the owner
API → D1Cross-tenant read/writeComposite FKs (writes) + repository layer (reads) + tests. No RLS (L-D1-1)
API → R2Object enumerationKeys are u/<owner_id>/...; the owner id in the key is derived server-side; signed URLs are short-TTL
Queue → Async WorkerForged or replayed messagesHMAC on the message body; consumer_deliveries state machine, never a presence flag
Containers → D1Privilege escalationService tokens per surface, no shared fallback; containers write through the API, not directly to D1
Model → DBPrompt injection causing a writeNo model output sets a terminal status; drafts only (A4)

E.4 D1 access classes: replication is the new cache problem

Revision 2's cache/RLS hazard has a D1-shaped successor, and it must be handled the same way: by structure, not by discipline.

D1's Sessions API guarantees sequential consistency within a session, and its default session (first-unconstrained) may begin on a replica. A read-after-write that lands on a replica can therefore return the pre-write state — the same class of bug as a stale query cache, with a different cause.

ClassBinding/APIUsed forGuarantee
withPrimary(fn)env.DB directly, no sessionowner-scoped reads and writes, caps, state machines, auth, authorization, read-after-writeprimary only; strongest available
withCorpus(fn)env.DB.withSession(...)corpus_* reads only (job postings)sequential within the session; replicas allowed

Enforcement:

  1. src/platform/db.ts exports exactly these two, and nothing else accepts a D1Database.
  2. withCorpus is importable only from src/features/jobs/corpus/*; a CI grep fails the build if the session API appears elsewhere.
  3. Every repository function takes an ownerId parameter or is explicitly marked /* corpus */. The query layer refuses to build a statement against an owner-scoped table without one.
  4. A test enumerates tables with an owner_id column and fails if any has no repository entry.

Verification (S2): HC-D1-1 two owners, identical SQL and parameters, no cross-read; HC-D1-2 read-after-write through withPrimary never returns stale; HC-D1-3 corpus session is the only place a bookmark is used.

E.5 Repository shape

backend/
├── README.md · AGENTS.md
├── openapi.yaml                  frozen contract (copied, then drift-tested)
├── wrangler.jsonc                DB · BLOB · KV · ASYNC · ASYNC_DLQ · AI · vars
├── functions/                    Pages Functions: /api/v1/* proxy, auth
├── migrations/                   numbered SQL, one batch per migration
├── docs/decisions/               ADR-1 … ADR-10
├── src/
│   ├── index.ts                  worker fetch() / queue() / scheduled()
│   ├── http/                     router · auth · budget · respond · routes/<origin>.ts
│   ├── features/                 account applications companies inbox jobs outreach profile
│   ├── platform/                 db · limits · retention · storage · worker · ai · outbox · log
│   └── lib/                      pure helpers
└── test/                         integration tests against a real D1 (miniflare) + a preview DB

E.6 Frontend hosting: Pages, with the compatibility question left open on purpose

The target is Cloudflare Pages. Two facts must be reported before anything is built, and S3 exists to report them:

  1. Next.js 16 support on Pages is not assumed. Cloudflare's Pages-based Next.js integration (next-on-pages) has historically lagged Next.js major versions, while the Workers-based @opennextjs/cloudflare adapter tracks them. Whether Next 16 works on Pages is not established by this document and will be answered by S3.
  2. Static export is a real option and has a real cost. output: 'export' is supported and would remove the SSR question entirely — but Next.js refuses API routes under export, so /api/auth/* and the /api/v1/* proxy must move to Pages Functions, and SSR-only behaviour on /, /login, /signup must become prerendered or client-side.

Decision rule, declared in advance so S3 is a measurement and not a negotiation:

S3 findingAction
Next 16 builds and serves all 13 routes on PagesProceed as drawn
Next 16 fails on Pages, static export preserves all functionalitySwitch to static export + Pages Functions; re-verify the 3 SSR routes as prerendered
Next 16 fails on Pages and static export loses functionalityStop and report. The options are: pin Next.js to a Pages-supported version, or host the frontend on Workers with OpenNext. Both are owner decisions, and neither is taken silently

That last row is the point of the instruction "do not silently switch to Workers hosting".


F. Technology decisions

ConcernDecisionRejected, and why
Primary databaseD1Durable Objects SQL (per-object sharding, no cross-entity queries); KV (no queries, eventual); external Postgres (off the table per the driver)
FilesR2, private bucket, prefix-per-ownerD1 blobs (2 MB row cap, and blobs do not belong in an OLTP row)
Frontend hostingCloudflare PagesWorkers hosting — only if S3 proves Pages cannot serve Next 16, and only with owner approval
APIOne API Worker + Pages Functions as a thin same-origin proxyPutting business logic in Pages Functions (Couples the API to the frontend deployment)
AsyncQueues + Cron, with the outbox in D1Durable Objects as a queue (extra state to own); Workflows (durable multi-step not required; discovery is a bounded loop)
CacheKV for JWKS + public config onlyKV for anything transactional
AIWorkers AI evaluated first, provider seam retainedGroq-only (fails the consolidation goal); local tunnel (single workstation, never ran end-to-end)
Go/Python workersContainers, if S5 shows WASM/Workers cannot host themRewriting the scraper or the CLI for Workers speculatively
AuthBetter Auth with its native D1 dialectHand-rolled JWT; keeping the Convex auth component

G. Data model summary

42 tables of ours + 4 Better Auth tables = 46 physical tables, in one D1 database, one namespace, prefix-grouped because D1 has no schemas:

PrefixCountContents
auth_*4Better Auth's own tables (vendor-owned, never hand-edited; not counted in the 42)
(unprefixed product tables)24owner-scoped: profiles, resumes, profile_links, searches, drafts, events, …
corpus_*5shared, ownerless reference data
ops_*13outbox, deliveries, incidents, leases, rates, caps, erasure, upload intents, audit, policy

Full catalogue with constraints, indexes, retention and deletion behaviour: DATA-MODEL-PROPOSAL.md. The count is reconciled by tools/check_table_inventory.py against both server/convex/schema.ts and the catalogue's own DDL.

Types are SQLite's: TEXT ids (UUIDs generated in application code), INTEGER unix-ms timestamps, TEXT for JSON (with json_extract where needed). No uuid, timestamptz, jsonb, numeric or arrays.


H. API architecture

H.1 What is preserved

All 58 paths, the JSON shapes, the Bearer scheme, the error envelope ({ error, code } with demo:true), and the status mapping (CAP_REACHED / SEARCH_ACTIVE / DRAFT_LOCKED → 409; NOT_FOUND / UNKNOWN_SOURCE → 404; UNAUTHENTICATED / SERVICE_UNAUTHORIZED → 401; else 500). ADR-9 stands: only the base URL and the auth endpoints change.

H.2 The browser route, decided explicitly

A browser cannot use a Worker service binding, so the path is:

Browser → https://<app>/api/v1/*            (Pages Function, same origin)
        → env.API.fetch()                   (service binding)
        → API Worker                        (verify JWT, derive owner, run route)
ConcernDecision
Same originYes — the browser never sees a second host
CookiesAuth routes use SameSite=Lax; API calls authenticate by Bearer only, which removes the CSRF surface from every mutating route
CORSNot needed. If a public API origin is ever added, this section is rewritten first
Size256 KiB at the proxy and in the API
Cancellationrequest.signal is forwarded into the binding call
Correlationx-request-id generated at the proxy if absent, written to ops_audit_events
FailureBinding throw → 502 {"error":"upstream unavailable","code":"UPSTREAM"} in the existing envelope

H.3 Realtime

Convex subscriptions become polling. Every screen that used a subscription is enumerated in the checklist before Phase 10, because a missed one is a screen that silently stops updating. This is unchanged from revision 2 and remains a real (if unglamorous) risk.


I. Asynchronous execution on D1

I.1 The outbox

ops_outbox is the durable record. Publication is a lease, and the transaction ends before the external call — the same discipline as revision 2, re-expressed in D1 terms.

1. AUTHORITATIVE WRITE (one batch, atomic)
     UPDATE email_drafts SET status='sending', send_started_at=?
       WHERE id=? AND owner_id=? AND status='approved';        -- guarded: 0 rows = not ours
     UPDATE ops_cap_quota SET used=used+1
       WHERE owner_id=? AND day=? AND kind=? AND used<limit_value
         AND NOT EXISTS (SELECT 1 FROM ops_cap_ledger WHERE owner_id=? AND op_key=?);
     INSERT INTO ops_cap_ledger (...)
       SELECT ... WHERE changes() = 1;   -- DM-23: every batch statement runs
     INSERT INTO ops_outbox (...) VALUES (...);
   -- batch() commits all of it or none of it; a conflict in any statement
   -- rolls back the cap charge too, which is why the ledger check is in the UPDATE
   -- and not a count(*) subquery

2. CLAIM (own batch, commits before any network I/O)
     UPDATE ops_outbox SET publish_state='claimed', publish_claim_id=?, publish_claimed_at=?,
            publish_attempts=publish_attempts+1
      WHERE id IN (SELECT id FROM ops_outbox WHERE publish_state='pending' AND available_at<=?
                    ORDER BY created_at LIMIT 50)
        AND publish_state='pending'
      RETURNING *;

3. PUBLISH   queue.sendBatch(rows)          -- outside every transaction
4. CONFIRM   UPDATE ops_outbox SET publish_state='published', published_at=?
              WHERE publish_claim_id=?;
5. REAP      UPDATE ops_outbox SET publish_state='pending', publish_claim_id=NULL
              WHERE publish_state='claimed' AND publish_claimed_at < ? - 5 minutes;

A crash between 3 and 4 re-publishes. At-least-once, deliberately — which is exactly why the consumer must be idempotent by state.

I.2 The consumer: states, not a flag

received → processing → completed
                ├→ failed   (retryable)
                ├→ dead     (attempt > 5 → incident)
                └→ parked   (operator holds it)

Claim (one statement; D1 serializes writers, so the guard is sufficient):

UPDATE ops_consumer_deliveries
   SET state='processing', attempt=attempt+1, lease_id=?, lease_expires_at=?
 WHERE event_id=?
   AND (state IN ('received','failed','parked')
        OR (state='processing' AND lease_expires_at < ?))
RETURNING state;

Routing, unchanged in meaning from revision 2 and still the case revision 1 got wrong:

ResultMeaningAction
Row returnedWe hold the leaseDo the work
No row, existing completedAlready doneAck — the only short-circuit
No row, processing, lease liveSomeone else is workingThrow (do not ack)

Effect and completion, ordered for D1: the effect is applied first and is idempotent; the completion is a guarded UPDATE … WHERE lease_id=? AND state='processing'. If the completion matches zero rows, the effect is rolled forward on the next attempt as a no-op. This is the §D.3 rule, and it is why a crash between the two cannot lose work.

I.3 Sends are not queued

Unchanged from revision 2, and more important here: a retried Gmail send is a second email, and D1's at-least-once queues cannot prevent that. POST /outreach/send performs the send synchronously and returns sent / sent_unrecorded / uncertain / failed in the response. There is no email.send_requested event because there is no command.

I.4 Dead letters, and recovery when the DLQ itself fails

ScenarioResponse
Consumer fails repeatedlyattempt > 5 → dead; the queue moves the message to the DLQ; the DLQ consumer writes ops_dlq_incidents
The DLQ consumer cannot write (DB down — the likely moment)It does not ack, so the message is redelivered. Its retry budget is non-zero; max_retries: 0 was retracted in revision 2 and stays retracted
The queue and the DLQ are both unavailable, or messages expire at 24 h (Free)The outbox reconciler cron reads ops_outbox from D1 and writes the incident itself, with no queue involved

The outbox row is the durable record that work is unfinished; the queue is only transport. A lost message costs a delay, never a job.

Incidents store event_id, event_type, attempts, error_class and the names of payload fields (payload_keys), never values.

I.5 The worker lease (scrape/ingest)

No SKIP LOCKED; a guarded single statement instead:

UPDATE ops_worker_tasks
   SET status='claimed', lease_id=?, leased_by=?, lease_expires_at=?, heartbeat_at=?,
       attempt=attempt+1
 WHERE id = (SELECT id FROM ops_worker_tasks
              WHERE queue_name=? AND status='queued' AND available_at <= ?
              ORDER BY priority, created_at LIMIT 1)
   AND status='queued'
RETURNING *;
PhaseGuarantee
Eligibilitystatus='queued' AND available_at <= now() — delayed work is one concept, not a status
ClaimServer-generated lease_id; zero rows = another worker won
HeartbeatGuarded UPDATE … WHERE lease_id=? AND status='claimed' AND lease_expires_at > ?
FencingEvery write carries lease_id and an unexpired lease, so a stale worker cannot write even before reclaim
IngestBounded ≤200 rows and ≤900 KB; ON CONFLICT DO NOTHING on corpus_jobs.canonical_url and corpus_job_sources(source_id, source_job_id) so a retried batch is a no-op
CompletionAfter the idempotent ingest (§D.3), guarded by lease_id
RetryReaper returns claimed + expired-beyond-grace to queued with backoff; 3 strikes → failed, fail closed
search_idA typed column on the task, never a payload key — the V-04 fix, made structural

AutoApply execution is out of scope. applications is manual tracking only; the apply cap kind is reserved in cap_quota so the invariant survives without an engine.


J. AI architecture

J.1 Evaluated first, not assumed

The driver says Cloudflare-native, so Workers AI is the primary candidate for the seven AI purposes the product already has:

PurposeInputCurrent promptSuitability question for S7
Résumé → profilerésumé text (30–60 KB)prompt 07Does the context window and extraction accuracy hold?
Profile dossierprofile JSONprompt 07Structured output fidelity
Job ranking20 postings/runprompt 02Cost per run vs. quality
Keyword expansionone searchprompt 013-term expansion
Outreach plannertarget + presetsprompt 0350-lead cap
Cold-email draftingcontact + profileprompts 04–06Tone and length compliance
Reply classificationone emailprompt 066-way category accuracy

Verified platform facts: Workers AI is included on Free and Paid, with 10,000 Neurons/day free and $0.011 / 1,000 Neurons beyond it; JSON mode with a json_schema is supported (and "the model may not always comply", returning a JSON Mode couldn't be met error — so a schema-invalid response is a real path the code must handle).

J.2 The provider seam survives; the default changes

provider seam (lib/ai/provider.ts)
  ├── Workers AI          ← default candidate (consolidation)
  ├── Groq                ← explicit opt-in fallback, never silent
  └── local (tunnel)      ← explicit opt-in, owner's own machine

No silent cross-provider failover. If Workers AI is slow or unavailable, the request fails honestly and the UI says so. The reason is the same as revision 2 and it is a privacy reason, not a performance one: a résumé or a reply body must not be sent to a second provider because the first one timed out.

J.3 Privacy

RuleMechanism
Résumé and email content go to Workers AI only if the owner opted inuser_preferences.ai_provider with an explicit value; no default that implies consent to a third party
A different provider requires a new choiceChanging ai_provider is an explicit user action, shown with what it means
Prompt and completion bodies are never storedops_ai_runs keeps provider, model, token counts, latency, status, error_class — never content
Budget is reserved before the call, settled afterops_rate_windows guarded updates; env knobs read in the action, never a mutation

J.4 What S7 must decide

  1. Does Workers AI extract a real résumé into the profile schema with acceptable accuracy, measured on the owner's actual résumés (the current system has never run one end to end through the local model — R2)?
  2. Is the neuron cost per rank run (20 postings) and per classification within the free allowance or trivially above it?
  3. Does the 10,000-neuron/day free allocation cover the beta workload, and what is the cost at 10× that?
  4. Which purposes need a stronger model, and is the tiering (small model for classification, larger for extraction) expressible in the seam?
  5. Does JSON-schema mode hold often enough that a validation-and-retry loop is bounded?

S7's verdict is a table of purpose → provider → measured quality → cost per operation. If Workers AI fails extraction but passes classification and ranking, the answer is a per-purpose provider map, not a wholesale rejection.


K. Security architecture

K.1 Authentication: the item that got easier

Revision 2 treated Better Auth on Workers as its riskiest item, because a module-scope pg pool is forbidden. D1 removes that hazard at the root: Better Auth ships a D1SqliteDialect, auto-detects a D1 binding (by the presence of batch/exec/prepare), and explicitly sets transaction = false because it uses batch() for atomicity. A module-scope auth instance holding a D1 binding holds no connection, so the Workers I/O-across-requests restriction does not apply.

What this does not remove, and what S1 must still prove:

RequirementWhy it is still a spike
Google OAuth end to endProvider config, redirect URIs on a Pages origin
Explicit account linking by verified email onlyThe authLinking.test.ts invariant: same verified email links, different refuses, unverified refuses. This is a security property, and it must be re-proven against the D1 adapter
Unverified local email cannot linkThe most dangerous regression in any auth migration
Gmail refresh token retrievalMust still resolve through auth_account via a pointer, with email_accounts.token_secret_reference never holding a token
Separate Gmail consentScopes requested incrementally, not bundled with login
Session revocation and expiryRevocation must stop refresh immediately; access-token expiry ≤ 15 min is an accepted, stated limit
UUID idsBetter Auth's default string ids must be reconciled explicitly; the FK type follows the auth table, never the reverse
Auth schema migrationBetter Auth's generated D1 schema must round-trip through the migration runner

K.2 Session → Bearer JWT

PropertyDecision
Issuer / audienceApp origin / jobwzrd-api
Subjectauth_user.id — the only source of owner_id
Expiry15 minutes; refresh via the session cookie
SigningAsymmetric (ES256), so the API verifies with a public key and holds no signing secret
VerificationJWKS cached in KV with a TTL (public data, eventual consistency acceptable) and refetch-on-unknown-kid
RevocationRefresh stops immediately; an issued access token lives ≤ 15 min. Stated, not hidden
CookiesSameSite=Lax for auth routes only; API is Bearer-only

K.3 Ownership without RLS

This is the one genuine security regression of the retarget, and it is stated as such:

LayerMechanismStrength
WriteComposite FKs (parent_id, owner_id) → UNIQUE (id, owner_id) on parentsA cross-owner edge is unrepresentable
Writeowner_id on every row, NOT NULL, REFERENCES auth_user(id) ON DELETE CASCADEOrphan rows impossible
ReadOne repository layer; every function takes ownerId or is marked /* corpus */A single place to audit
ReadCI test: every table with owner_id has a repository entry; withCorpus is unreachable from owner codeStructural
Regression testTwo-owner fixture asserting empty cross-reads on every owner-scoped tableDetectable
ResidualA missed predicate inside one repository function is a leak. PostgreSQL would have caught it at the databaseLimitation L-D1-1

L-D1-1 is the price of the driver. It is not hidden, and S2 exists to measure how well the layers above actually hold.

K.4 Secrets

Unchanged in shape from revision 2 and still fail-closed per surface: BETTER_AUTH_SECRET, GOOGLE_CLIENT_ID/_SECRET, QUEUE_HMAC_KEY, and per-surface service tokens (SERVICE_TOKEN_SCRAPE / _APPLY / _AI / _EMAIL_SYNC / _EXPORT). A missing token fails closed; there is no shared fallback token. The Gmail refresh token lives only in auth_account, never in email_accounts.


L. Reliability and observability

L.1 What D1 changes about failure

BehaviourConsequence
Writes serialize; a full request queue returns "overloaded"The API must treat it as a retryable 503 with backoff, never as a validation error
30 s query limit; 1,000 queries per invocation (Paid)Batch aggressively; a 200-row ingest must be one batch, not 200 statements
10 GB hard ceilingWrites begin failing; the split trigger (§D.5) exists for this
Time Travel: 30 days (Paid) / 7 (Free)Restore is the recovery path for a bad migration

L.2 Logging and evidence

The rule from revision 2 survives and matters more, because D1 has no append-only guarantees:

Compliance-relevant evidence lives in D1 and is written in the same batch as the effect it describes. Logs are best-effort diagnostics; no reader may depend on a log.

DestinationContentsDeliveryGuaranteed?Retention
ops_audit_events (D1)every external effect, cap charge, refusal, erasure stepsame batch as the effectYes400 days then purge
ops_dlq_incidents (D1)dead-lettered workconsumer or outbox reconcilerYes — two independent writersuntil resolved
Workers Logsrequest diagnosticsplatform, sampled (100% errors, 10% info)No — best effortplan-defined (UNKNOWN, R10)
R2 logs/YYYY/MM/DD/*.jsonldiagnostic archiveLogpush (Paid feature)No — no per-record ack30 days

No "100% archived" claim. There is no mechanism that reports per-message archive delivery. Anyone needing that guarantee gets it from ops_audit_events, which is a table, not a pipeline.


M. Capacity: D1's single writer is the real ceiling

PropertyValueSource
WritesSerialized per database (one Durable Object)D1 docs
Read throughput≈ 1 / query duration (1 ms → ≤1,000 qps)D1 docs
Write duration"several milliseconds", depends on rows writtenD1 docs
Queries per invocation1,000 (Paid) / 50 (Free); a batch() counts as oneD1 docs

M.1 Current and projected

All figures below are ASSUMPTION except the platform limits, and R4 says the real request volume has never been measured.

ScaleUsersReads/dayWrites/dayPeak write rateVerdict
1×1~2,000~200« 1/sTrivial
10×10~20,000~2,000~0.1/sTrivial
100×100~200,000~20,000~1/sComfortable, if writes are batched and no query scans a table

The dangerous shape on D1 is not user count; it is a query that scans. The scraper ingest is the one real bulk writer, and it is bounded (≤200 rows/900 KB per batch, 20 targets × 5 pages per discovery run), so it is a sequence of small batches rather than a large one.

Measured, not assumed, in S2 and S4: write latency under concurrent requests, and whether a 200-row ingest fits one batch inside the 30 s limit.


N. Cost

N.1 Verified figures (read for this revision)

ItemValueSource
D1 size limit10 GB Paid / 500 MB FreeD1 limits
D1 databases1,000,000 Paid (first 100,000 included) / 10 FreeD1 limits
D1 Time Travel30 days Paid / 7 FreeD1 limits
QueuesFree 10k ops/day, 24 h retention non-configurable; Paid 1M ops/mo + $0.40/M, retention 4–14 daysQueues pricing
R210 GB-month, 1M Class A, 10M Class B free; $0.015/GB-mo; $4.50/M Class A; $0.36/M Class B; egress $0R2 pricing
Workers AI10,000 Neurons/day free on both plans; $0.011 / 1,000 Neurons aboveWorkers AI pricing
Workers Paid base$5/moWorkers pricing
Workers subrequests50 Free / 10,000 Paid per requestWorkers limits
D1 rows read / rows written (Free allowances, Paid rates)UNKNOWN for this revision — read the D1 pricing page at decision timenot verified here

N.2 What the plan costs

ScaleWorkersD1R2QueuesWorkers AINeonTotal/mo
Spike phaseFreeFreeFreeFreeFree (10k Neurons/day)$0$0
Beta (1 user)Paid $5within free allowances (UNKNOWN, likely)within free tierwithin freepossibly above 10k Neurons on résumé extraction$0$5–15
10 usersPaid $5likely small paid usage (UNKNOWN)~freesmalldominates if AI-heavy$0$20–60
100 usersPaid $5needs measurementsmallsmalldominates$0$60–200

Three honest statements:

  1. The external database line goes to zero. That is the concrete consolidation win, and it is the only cost claim this document makes with confidence.
  2. Cost is now dominated by AI tokens, not infrastructure — and Workers AI's 10k free Neurons/day is small (a single 70B extraction run is ~200k Neurons by list price). S7 must measure this before any figure above is treated as real.
  3. Workers Paid is recommended, not because D1 requires it, but for subrequests (50 → 10,000), queue retention (24 h → days, which the DLQ story needs), and Logpush. Same reasoning as revision 2, and it still holds under D1.

Denial of wallet: caps remain the primary control (5 applies, 50 emails), plus the AI budget in ops_rate_windows. No new surface is introduced by D1.


O. Migration and cutover

O.1 Principle

The old backend is never modified, so the project can stop at any phase boundary and lose nothing but time. server/ stays frozen until Phase 13.

O.2 Phases

#PhaseDeliverableReversible?
0Baseline + driverDriver recorded (done: consolidation + independence), current Convex billing captured, git status cleann/a
1Spikes S1–S7Seven verdict documents. Any red spike stops the migration at its own boundaryYes — throwaway
2Skeleton + schema v1backend/, migrations/0001_init.sql (41 tables, single namespace), constraints tested, repository layer + ownership testsYes — drop the DB
3Auth on D1Better Auth + D1 dialect; S1's invariants as testsYes — throwaway DB
4Read pathCorpus + product reads through the repository; withPrimary/withCorpus provenYes
5Write pathGuarded updates; caps; draft state graph; attachmentsYes
6AsyncOutbox, consumer states, DLQ, reconciler, worker leaseYes
7Blobs + erasureUpload intents, lifecycle, prefix sweep, verified deletionYes
8Contract parityAll 58 operations; the OpenAPI drift test against server/openapi.yamlYes
9Data migrationOne-time export from Convex → D1 into a mirror; counts reconciledYes
10Frontend cutoverPages build; polling replaces subscriptions; nothing writes to D1Yes — env flip
11Shadow windowDual reads against the mirror; zero unexplained diffsYes
12Cutover + rollback drillWrite freeze, final export, import, reconcile, auth+API together, first new writeIrreversible at the first D1 write
13Decommission ConvexOnly after the shadow window and a both-directions drillIrreversible

O.3 Cutover and rollback, stated honestly

The revision-1 error ("rollback is a flip back") is not repeated. Under D1 the story is the same shape as revision 2, with the storage swapped:

WindowActionLossless?
Before the first D1 writeFlip the env var backYes
During the write freezeAbort; users see a maintenance window with no writesYes
After the first D1 writeRollback = migrate back: export D1, import into Convex, reconcile, then flipNo — rows with no Convex shape are unexportable, and every external effect must be reconciled against Gmail

The irreversible point is the first committed D1 write, and it is named here so nobody has to improvise it at 02:00.

No dual-write. Dual reads against a mirrored dataset are how parity is measured; the write freeze is how the mirror stays true. Dual-write would roll back to two divergent truths.


P. Failure modes

Each: trigger → mechanism → impact → detection → prevention → recovery.

#FailureMechanismImpactDetectionPreventionRecovery
P1Better Auth cannot reproduce linking policy on D1Adapter differences in account rowsSecurity — an OAuth login could attach to the wrong accountS1's linking testsPort authLinking.test.ts verbatim as acceptanceFull stop; do not proceed
P2A missed owner predicate leaks a rowNo RLS to catch it (L-D1-1)Cross-tenant readTwo-owner fixture on every tableRepository layer + CI enumerationFix the predicate; add the table to the fixture
P3Cap over-charged or freeRead-then-write instead of a guarded updateUser blocked or sends unlimitedQ1–Q7 concurrency testsGuard in the UPDATE + CHECK (used <= limit)Correct used from the ledger
P4Queue retry duplicates an emailA send on a queueA real second email to a real personSend path has no queueSends are synchronous (§I.3)Impossible by construction — keep it that way
P5Consumer acks without doing workPresence-based dedupeSilent work lossS4 takeover testcompleted is the only short-circuitReplay from the outbox
P6DLQ consumer cannot write, message expiresRetry budget 0, or retention 24 hWork disappears with no recordOutbox reconciler incident countNon-zero retries + reconciler reading D1Replay from ops_outbox
P7D1 overloaded under loadSingle-threaded writer, queue full503s under normal use"overloaded" error rateBatching, small writes, split triggerSplit corpus (§D.5); back off
P8D1 hits 10 GBCorpus growth (R3 unknown)Writes failSize dashboard + 40% alarmRetention, log egress, split triggerSplit corpus to a second database
P9Résumé extraction quality unacceptableWorkers AI model too smallCore feature unusableS7 quality tablePer-purpose provider mapStronger model for extraction only
P10Pages cannot serve Next 16Adapter lagFrontend blockingS3Declared decision rule (§E.6)Static export or owner decision on hosting
P11A stale replica read shows pre-write stateDefault first-unconstrained sessionConfusing UI, wrong cap displayHC-D1-2withPrimary for owner dataUse a session first-unbound→primary
P12Erasure reports complete with objects leftRow-driven deletion misses orphansCompliance failureEmpty-listing verificationPrefix sweep, repeat until emptyRe-run; never mark complete on a partial pass
P13Migration stalls at 60%Scope creep mid-flightCost without valuePhase checklistPhases are independently abandonableStop; server/ is intact

Q. Architecture decision records

ADR-1 — D1 as the single primary database

  • Context: the driver is Cloudflare-native consolidation; no external primary database.
  • Decision: D1, one database, one namespace, prefix-grouped tables.
  • Consequences: No RLS, no interactive transactions, one single-threaded writer, 10 GB ceiling. Every correctness mechanism is re-derived in §D.
  • Revisit if: the split trigger fires (§D.5) — and the first response is a Cloudflare-native adjustment (second D1 database), not another vendor.

ADR-2 — batch() and guarded updates replace transactions and locks

  • Decision: atomicity from static batch() sequences; leasing from guarded UPDATE … RETURNING; effects ordered before completion (§D.3).
  • Consequence: business logic that needs to decide-and-write atomically must be expressed as a single guarded statement.

ADR-3 — No Durable Objects, no Workflows at cutover

  • Context: DOs are now underneath D1, not a design element.
  • Decision: none added. Leasing, caps, and dedupe are SQL-plus-guard, and D1's serialization makes that sufficient.
  • Revisit if: S4 shows the reconciler and the consumer contending in a way SQL cannot order.

ADR-4 — Better Auth with its native D1 dialect

  • Decision: Better Auth, D1 dialect, module-scope instance (no held connection), UUID ids reconciled to the auth table.
  • Consequence: the riskiest item in revision 2 becomes a supported path; the security invariants still need S1.

ADR-5 — Workers AI first, per-purpose provider map

  • Decision: Workers AI is the default candidate; provider choice is per purpose after S7; no silent cross-provider fallback (privacy).

ADR-6 — KV for JWKS and public config only

  • Decision: nothing transactional in KV.

ADR-7 — 41 tables, single namespace

  • Decision: 42 Convex declarations → 41 D1 tables; count verified by tools/check_table_inventory.py, never by hand.

ADR-8 — Pages for the frontend, with S3 as the gate

  • Decision: target Pages. Static export, version pinning, or Workers hosting are reported findings, not silent switches.

ADR-9 — API surface frozen

  • Decision: 58 paths, same shapes, same errors; only base URL and auth endpoints change.

ADR-10 — Containers only where native execution fails

  • Decision: Go/Python stay as-is; host them on Containers if S5 shows Workers/WASM cannot carry them. No speculative rewrite.

R. Unresolved assumptions

#UnknownWhy it mattersHow it closes
R1Current Convex costBaseline for the consolidation claimBilling export, Phase 0
R2No AI purpose has ever run end to end through a real provider on real dataMigrating an unproven pipeline is a different risk classS7
R3Corpus growth rate / average description sizeDecides whether 10 GB is nearMeasure jobs size
R4Actual request and write volumeThe capacity model is structural, not measuredConvex dashboard
R5Realtime subscription inventoryA missed one is a dead screenEnumerate before Phase 10
R6Whether any queue is warranted at this scaleInline classification may be simplerProduct decision on latency
R7D1 rows-read / rows-written pricing and free allowancesCost model cannot be exactD1 pricing page at decision time
R8Whether Next 16 works on PagesBlocks the frontend phaseS3
R9Gmail per-user daily send quota50/day is probably under itGoogle console
R10Workers Logs retention per planArchive necessityDocs at decision time
R11Workers AI extraction quality on the owner's résumésCore feature viabilityS7
R12Whether a second user will existMulti-tenant work is Phase 2 or laterProduct decision
R13Whether unknown can be resolved by Gmail search rather than a humanRemoves a manual stepmessages.list probe
R14Whether Go compiles usefully to WASM here (scraper uses HTTP + parsing)Decides Containers vs WorkersS5
R15Whether Python (apply CLI) can run on Workers at allSameS5
R16Whether batch() of 200 ingest rows stays under 30 sIngest shapeS2/S4
R17Whether a D1 session bookmark is needed for corpus paginationCorrectness of pagingS2

S. Findings register

Findings carried from the adversarial review, plus the ones the retarget created.

IDSeverityFindingDecisionVerificationRemaining limitation
SD-01CriticalPostgres/Hyperdrive cache sat in front of RLSSuperseded: D1 has no query cache, but replicas create the same staleness classwithPrimary for owner data; withCorpus sessions for corpus onlyA corpus read may be seconds stale — accepted
SD-02CriticalIndependent owner FKs allowed cross-tenant edgesComposite FKs survive in SQLite and are keptCross-owner insert rejected for every edge—
SD-03CriticalPresence-based dedupe lost workops_consumer_deliveries state machine; completed only short-circuit; effects before completion (§D.3)S4 takeover testTwo consumers may briefly hold the work; one wins the guard
SD-04CriticalCounting insert raced past the capGuarded UPDATE with the predicate inside, plus CHECK (used <= limit_value)S2 Q1–Q7Changing the cap's day boundary can over-grant one day
SD-05CriticalSend/outbox contradictionSends never queued; no command event existsAssert no send path enqueuesAt-least-once for the events that are queued
SD-06Highuuid[] pretending to be a FKNormalised email_draft_attachments (JSON text cannot be a FK either — so a join table)Cross-owner attachment rejected—
SD-07CriticalLease referenced queue vs queue_name; delayed unclaimableFixed; available_at is the only delay concept; full lifecycle (§I.5)S4 claim/heartbeat/fence/reap—
SD-08HighDraft states had no graphFull graph; queued removed; one CHECK + a transition functionEvery illegal edge refusedGraph is code-enforced except one edge
SD-09CriticalBetter Auth via a module-scope pg poolResolved by the platform: D1 dialect, no held connectionS1's eleven itemsGmail token path and linking still must pass
SD-10HighBrowser cannot use a service bindingPages Function proxy → env.API.fetch()Trace shows one hop, no CORSThe proxy is a second place a contract could drift
SD-11CriticalAuth cut over before the APIAuth and API cut over together in Phase 12Staging login→call→logout on one authority onlyUsers re-authenticate unless sessions migrate
SD-12MediumLog "archive" was not a delivery designEvidence in D1, transactionally; logs best-effortPurge-failure testNo per-record archive guarantee
SD-13MediumWorkers Paid claimed mandatory for Hyperdrive/QueuesRecomputed on real limits; Paid recommended for subrequests, retention, LogpushCost sheet with sourcesD1 usage pricing unverified (R7)
SD-14Critical"Rollback is a flip" after the first writeWrite freeze + named irreversible point + migrate-backBoth directions drilledMigrate-back is lossy for rows with no Convex shape
SD-15MediumInventory arithmetic did not reconcileScripted inventory, 42 → 41tools/check_table_inventory.py—
SD-16 (new)CriticalNo RLS on D1 — a missed predicate is a cross-tenant readComposite FKs for writes; repository layer + CI enumeration + per-table two-owner fixtures for readsS2 HC-D1-1 across all owner tablesL-D1-1: one buggy repository function can leak
SD-17 (new)HighNo interactive transactions — decide-and-write cannot be a transactionGuarded single statements; static batch(); effects-before-completion orderingS2 exercises each guarded pathA multi-step decision needs a compensating step
SD-18 (new)HighSingle-threaded writer — throughput ceiling, "overloaded" errorsBatching, small writes, split trigger at 4 GBS2/S4 load probeShared ceiling for all users on one database
SD-19 (new)HighPages may not serve Next 16Declared decision rule in §E.6; nothing switches silentlyS3The frontend host may need an owner decision
SD-20 (new)MediumAI provider migration unproven on real dataWorkers AI evaluated per purpose; no silent fallbackS7Per-purpose provider map may split across vendors — which the consolidation goal dislikes, so it is an owner call

Schema-level findings DM-01 … DM-18 carry over with D1-appropriate mechanisms (DATA-MODEL-PROPOSAL.md §9), with EXCLUDE constraints replaced by partial unique indexes and all Postgres-only types removed.


T. Spike acceptance criteria

Seven isolated, disposable spikes. Rules that apply to all of them:

  • Disposable. Each gets its own branch, its own D1 database, its own Worker where needed, and is deleted after the verdict is recorded. Nothing from a spike ships.
  • No production data. Copies of schema, fake identities, the owner's own résumés only.
  • A spike fails loudly and stops its own line of work. A red verdict is a result, not a setback.
  • The verdict artifact is a page in this directory: what was tested, the literal commands, the observed output, and PASS / FAIL / PARTIAL with the residual risk.
  • PARTIAL counts as red for anything marked blocking.

S1 — Better Auth on D1 (blocking)

Question: does Better Auth on the native D1 dialect reproduce the security properties the current auth component provides, including the Gmail token path?

Setup: throwaway D1 database, a Pages/Worker dev deployment, a Google OAuth client with two test accounts, one account with a Gmail inbox.

#CriterionPass
1.1betterAuth({ database: env.DB }) initialises under the real request lifecycleSignup and login both succeed across ≥20 sequential requests in one isolate
1.2Auth schema generated and applied by the migration runnerauth_user, auth_session, auth_account, auth_verification exist with the expected columns
1.3ID types reconciledauth_user.id, auth_session.user_id, and every owner_id FK accept the same value; a wrong-type FK fails at insert
1.4Google sign-in works end to endNew user, session issued, JWT verifiable via JWKS
1.5Account linking by verified email onlySame verified email links to the existing user; a different verified email does not; an unverified local email does not
1.6Unverified local email cannot be hijackedReproduce the authLinking.test.ts cases verbatim; all pass
1.7Gmail consent is separate from loginScopes requested incrementally; login works without Gmail scopes
1.8Gmail refresh token retrieveable through the pointeremail_accounts.token_secret_reference holds better-auth:account:<id>, never a token; a Gmail API call succeeds using it
1.9Session revocationRevoked session cannot refresh; existing access token expires ≤15 min
1.10Session expiryExpired token rejected with UNAUTHENTICATED by the API
1.11Concurrent auth requests20 concurrent sign-ins/reads in one isolate: no batch() transaction errors, no lost sessions
1.12Failure behaviourProvider down, D1 unavailable, JWKS unavailable each produce a typed error, never a 200

Red means: the migration stops. Fallbacks, in order: (a) reconcile id types/tables with a hand-written adapter; (b) keep the auth subset on Convex temporarily with an explicit, time-boxed dual authority — an owner decision, not a default.

S2 — D1 integrity and concurrency (blocking) — RAN: PASS (local + remote)

Status: accepted. spikes/d1-integrity, Q1–Q18 plus R0–R9 and the schema audit, twice on local D1 and twice on a remote Cloudflare D1 preview database (temporary account, served_by: v3-prod, region APAC). Final: 18 core + 3 regression + 10 isolation

  • NOT NULL audit, all green, on both targets. Evidence: spikes/d1-integrity/results/FINAL-S2-REPORT.md.

The first run returned REVISE: 12 PASS, 5 FAIL, and every FAIL was this document's own SQL rather than D1's behaviour —

FindingThe claim that failedCorrection now in DATA-MODEL-PROPOSAL.md
DM-23the ledger insert is "only reached if statement 2 matched"WHERE changes() = 1
DM-23bconsequence: 8 sends on a 5/day cap via phantom-row refundssame guard
DM-24EXISTS(released_at = ?) makes refunds idempotentchanges() = 1
DM-25composite ON DELETE SET NULL preserves owner_idplain FK + same-owner triggers
DM-26parked deliveries are heldexcluded from the claim predicate

What survived on D1: the guarded cap update (50-way → exactly 5; 200-way → never 6), batch() atomicity on unique/CHECK/FK failure, lease fencing under takeover, and effect-before-completed.

Correction to the first run's report: the attack matrix has 15 ownership edges (13 composite FKs + 2 pointer edges), not 17; all 15 are rejected by D1 itself, and Q13 covers the third pointer edge's insert trigger. The number in the first report was wrong in both this document and spikes/d1-integrity/results/RESULTS.md.

Read isolation (L-D1-1) is now tested, not argued. R0–R9 attack the repository layer with two independent owners across all 18 owner-scoped tables — direct read by id, keyset pagination (including a cursor issued for the other owner), search-result reads, a 4-table join, counts, update/delete lookups, 11 malformed owner ids, an unknown owner, and a NULL-owner platform row. Nothing leaked.

One remote-only fact: D1 refuses PRAGMA table_info on its internal _cf_* tables (SQLITE_AUTH) while still listing them in sqlite_master, so table enumeration must filter them (DM-28, adopted in the data model's CI rule and in the coverage test).

Question: can D1 carry the integrity rules the Postgres design relied on — without RLS, without interactive transactions, with one writer?

Setup: real D1 (preview database), two owner fixtures, a load generator.

Integrity

#CriterionPass
2.1Composite ownership FKs exist and are enforcedCross-owner child insert (dossier_id of A, owner_id of B) is rejected at every edge in the checklist
2.2CHECK constraints holdcap_quota.used <= limit_value, status enums, draft sending ⇒ send_started_at
2.3Partial unique indexes work on D1One active résumé per owner; email_events dedupe only where provider id is present
2.4ON DELETE CASCADE from auth_userDeleting a user removes every owned row and leaves ops_audit_events (pseudonymised) intact
2.5Ownership isolation across all owner tablesHC-D1-1: for every owner-scoped table, owner B reads zero rows of owner A, with identical SQL text and parameters
2.6Read-after-writeHC-D1-2: withPrimary write → immediate read returns the written state, 200 iterations, no stale
2.7Corpus session behaviourHC-D1-3: withCorpus returns consistent pages; a bookmark resumed later does not reorder

Caps and concurrency

#CriterionPass
2.8Cap never exceededQ1: 50 concurrent distinct operations against a cap of 5 → exactly 5 succeed, 45 refusals, used = 5
2.9Never double-chargedQ2: same op_key 10× concurrently → exactly one ledger row, used moves by exactly 1
2.10Refund is idempotentQ3/Q4: charge → release → release again → used decremented exactly once
2.11Day boundaryQ5: a charge at 23:59:59.9 UTC and one at 00:00:00.1 → two rows, independent caps
2.12Lowering a limit is guardedQ6: the limit change is rejected when used > new_limit
2.13Guarded update is atomic under loadQ7: the same as Q1 with 200 concurrent attempts and artificial latency; never 6
2.14Write latency measuredp50/p95/p99 write duration at 1, 10, 50 concurrent, with a 200-row batch ingest inside the 30 s limit

Red means: the cap or ownership design must be reworked within Cloudflare. A Durable Object per owner-quota is the named D1-native fallback — not another database.

S3 — Pages / frontend compatibility (blocking, report-only)

Question: can the existing 13 routes be served from Cloudflare Pages, and what exactly do we lose if not?

This spike produces a report, not a preference. No switching to Workers hosting without the findings being presented.

#CriterionPass
3.1Build the current app for PagesBuild succeeds on Next 16 or fails with a specific, quotable reason
3.2All 13 routes serveEach route returns 200 (or its intended redirect) from a Pages preview
3.3SSR markers present/, /login, /signup contain server-rendered content in the HTML, not an empty root div
3.4Static export evaluatedoutput: 'export' attempted; report exactly which features break (API routes are known to be unsupported under export)
3.5Pages Functions boundary/api/auth/* and /api/v1/* proxy work as Pages Functions with the service binding
3.6Subrequest countSSR routes stay under the per-request subrequest ceiling (50 Free / 10,000 Paid)
3.7Environment mappingNEXT_PUBLIC_* values reach the browser under the Pages build, read through the existing env.ts table
3.8Verdict tableFor each of the three options (Pages SSR / static export + Functions / Workers hosting) → works or not, and what breaks

Red means: the owner chooses between (a) pinning Next.js to a Pages-supported version, (b) static export with compensating client-side behaviour, (c) hosting the frontend on Workers. The document does not choose.

S4 — Queues and Worker execution (blocking)

Question: does the D1-and-Queues combination preserve at-least-once transport with idempotent effects, durable task state, and recovery when the DLQ itself fails?

#CriterionPass
4.1Pages/Worker → Queue producerA Pages Function and a Worker both enqueue successfully with separate bindings
4.2Separate consumer WorkerConsumer receives, acks, and retries as configured
4.3Outbox leaseClaim commits before publish; a process killed between publish and confirm re-publishes, and the consumer does not double-apply
4.4Consumer state machinecompleted is the only short-circuit; processing with a live lease causes a throw, not an ack
4.5TakeoverKill the consumer mid-work; after lease expiry a second consumer takes over and the effect is applied exactly once
4.6Batch failure semanticsOne failing message in a batch retries the batch; explicitly acked messages are not re-delivered
4.7DLQ pathmax_retries exhausted → message lands in the DLQ → DLQ consumer writes ops_dlq_incidents with identifiers only, no payload bodies
4.8DLQ consumer failureSimulate D1 unavailable: the DLQ consumer does not ack, retries, and messages are not lost on first failure
4.9Reconciler independenceWith the queue fully broken, the outbox reconciler writes incidents from D1 alone
4.10Worker lease and fencingClaim/skip, heartbeat, expired-lease write rejected, reaper requeues, 3 strikes → failed
4.11Idempotent ingestReplaying the same 200-row batch twice changes no row count

Red means: async stays synchronous where possible, and the queue carries only work that can be safely repeated. It does not mean "add another queue vendor".

S5 — Python/Go runtime (blocking for those components)

Question: where do the existing Go scraper and Python apply CLI run, staying inside Cloudflare?

Setup: the real scrapers/MiniWzrd and apply/ code, evaluated against three homes.

#CriterionWhat is measured
5.1Workers/WASM feasibilityDoes Go compile to a Workers-compatible target, and do its HTTP, HTML-parsing and SQLite/HTTP-call dependencies work there? Note every dependency that fails
5.2Python on WorkersIs there a Python runtime path, and does the CLI's dependency set fit?
5.3ContainersBuild and run both as Containers against a D1-backed API; measure cold start, image size, cost at this workload
5.4Minimal adaptationFor each failing dependency, is the adaptation a small change or a rewrite? List them concretely
5.5Boundary preservedIn every option, the worker writes through the API, never directly to D1/Convex, and keeps per-surface service tokens
5.6Recommendation tablePer component: Workers · WASM · Containers · rewrite — with the evidence

Red means: Containers for that component. That is still Cloudflare-native and is an acceptable answer, not a failure.

S6 — R2 lifecycle and account erasure (blocking)

Question: does object storage actually erase, and does the upload lifecycle close the orphan window?

#CriterionPass
6.1Upload intent → objectIntent recorded, key issued, PUT succeeds, finalize verifies size and type via HEAD
6.2Upload succeeded, finalize failedThe object is not orphaned forever: the intent expires and cleanup removes it
6.3Metadata exists, object missingA HEAD reconciliation marks the blob missing; download returns an honest 410
6.4Signed URL expiryA URL past its TTL is refused; a URL cannot be reused to read a different later object
6.5ReplacementNew object, old object deleted, no dangling reference
6.6In-flight upload during erasureNew intents are refused; the sweep waits for outstanding capabilities to expire
6.7Verified erasurePrefix listing repeated until a pass returns zero objects; a partial delete never reports complete
6.8Orphan sweepObjects with no metadata row are found and removed (the case row-driven deletion cannot see)

Red means: erasure is not implemented as designed and the migration stops, because A8 is a compliance invariant, not a feature.

S7 — AI architecture (blocking for AI features)

Question: can Workers AI carry the product's AI purposes, and at what quality and cost?

Setup: the owner's real résumés and a sample of real job postings and replies.

#CriterionPass
7.1Résumé → profileStructured extraction matching the profile schema, measured on ≥3 real résumés; record field accuracy per field
7.2JSON-schema complianceresponse_format: json_schema compliance rate; the JSON Mode couldn't be met path handled and bounded by one retry
7.3Ranking quality20 postings ranked; agreement with a hand-labelled ordering
7.4Classification accuracy6-way reply categories on a labelled sample
7.5EnrichmentCompany/person fields extracted with acceptable accuracy
7.6Cost per operationNeurons per operation, from the dashboard, not from a guess
7.7Free allowanceWhat 10,000 Neurons/day covers; the 10× and 100× cost projection
7.8Privacy behaviourChanging provider is an explicit user action; no content leaves Workers AI unless chosen; provider and model recorded per run
7.9Per-purpose verdictTable: purpose → Workers AI / other → quality → cost → recommendation

Red on extraction only means a per-purpose provider map (extraction elsewhere, cheap tasks on Workers AI) — which is an owner decision, because it trades consolidation for quality.


U. Final recommendation

S1 and S2 PASS. 31 assertions plus a NOT NULL audit, twice each,

and the repository-isolation tests behind L-D1-1. S1 also produced a PASS (16/16,

better-auth 1.7.25); S3 is the next spike, and it is blocked on Pages credentials.

The architecture is coherent under D1; one mechanism (no RLS) remains a real regression —

now covered by tests rather than by an argument.

SpikeStatus
S2 — D1 integrity and concurrencyPASS — 31 assertions + audit, green on local and remote D1 (2 runs each). DM-23…DM-28 closed
S1 — Better Auth on D1RAN: PASS — 16/16 checks, better-auth 1.7.25, local D1 under the real Worker lifecycle; schema reconciled by diff; backend/spikes/b1-auth/B1-REPORT.md
S3 — Pages / frontend compatibilitynot started — next
S4 — Queues and Worker executionnot started
S5 — Python/Go runtimenot started
S6 — R2 lifecycle and erasurenot started
S7 — AI architecturenot started

What S2 changed in this document: §I.1's outbox batch, the enumeration rule, and the verdict above. The cap, lease and consumer mechanisms are unchanged in shape — the guards inside them are now changes()-based, which is a smaller change than it sounds and a larger one than it looks: before it, the daily cap was bypassable.

Still not proved by S2: production D1 under production traffic and data size (preview account, 22-table slice, ≤200 in-flight requests), the production repository, and the tables outside the slice (ops_outbox, corpus_*, erasure, uploads). That is L-10, and it is what Phase 12's drills are for.

The target is what the owner specified, and this document implements it rather than arguing with it:

Cloudflare-native. Pages for the frontend, D1 as the single primary database, R2 for private objects, Pages Functions for the frontend/API seam, Workers for independent services and consumers, Queues for async delivery, Cron for scheduled work, KV only where eventual consistency is acceptable, Workers AI evaluated for the model work, Containers evaluated for the Go/Python workers. No external primary database.

What is genuinely better than revision 2:

ItemImprovement
AuthD1 removes the module-scope-pool hazard entirely; Better Auth's D1 dialect is a supported path (ADR-4)
Cap correctnessD1 serialises writes, and a guarded UPDATE … RETURNING is atomic by statement; the revision-1 counting-insert race is gone and now has a CHECK backstop
Number of vendorsFrom four (Cloudflare, Neon, Groq-by-default, Gmail) to two
Operational surfaceNo connection pooling to tune, no pool exhaustion, no cache-vs-RLS interaction

What is genuinely worse, and is not glossed over:

ItemCost
No RLSOwnership isolation moves from a database guarantee to a code invariant (L-D1-1, SD-16). This is the largest single regression in the retarget
No interactive transactionsSome business logic that would have been atomic must become a guarded statement or a compensating step (SD-17)
One writer, 10 GBA shared throughput ceiling and a hard size ceiling with a split trigger (SD-18, §D.5)
Pages + Next 16Unproven; the frontend host may need an owner decision (SD-19)
AI on real dataNever measured, now measured by S7 on the owner's actual résumés (SD-20, R2)

Sequencing, because not every spike is equally blocking:

OrderSpikeWhy here
1S2 (D1 integrity + caps)If this is red, nothing else matters: the whole model assumes guarded updates and composite FKs
2S1 (auth)Security-blocking, and independent of S2
3S3 (Pages)Decides whether the frontend plan survives at all
4S4 (queues)Needed before any async design is committed
5S7 (AI)Decides whether the product's core feature works
6S6 (R2/erasure)Independent; can run in parallel
7S5 (Go/Python)Independent; can run in parallel

The standard this is held to: every write, read, retry, migration, authorization check and external side effect has a correctness argument that names D1's actual behaviour, and a spike that could falsify it. Where D1 cannot provide a guarantee (RLS), the document says so, states the residual risk, and puts it in a test.

What I am not claiming

That this is safer than the Postgres design (it is not — it trades a database-enforced ownership boundary for a code-enforced one). That it is cheaper (R1 and R7 are unmeasured). That the frontend will work on Pages (S3 decides). That AI quality is sufficient (S7 decides). That the 10 GB ceiling is far away (R3 was never measured).


Approval gate

S2 is answered and accepted. Answer one of these for the next step:

  1. S1 is closed (PASS). Auth now has one identity source (Better Auth sessions, no HS256 authority of our own), a schema diff against the pinned library version, and a regression suite for the linking rules. Its two open carry-overs are L-AUTH-5 (no sign-in rate limit) and L-AUTH-7 (no cross-statement atomicity on D1).
  2. Run S3 next (Pages) — decides whether the frontend plan survives.
  3. Re-run S2 against a remote preview D1 first — needs CLOUDFLARE_API_TOKEN; the harness is already scripted for it and this is the one fidelity gap in the S2 result.

Still true: no application code exists in backend/, backend/migrations/ is empty, no production database exists, and server/ is untouched.

On this page

A. What must not changeB. Current state (verified)C. Focus auditD. What D1 actually changesD.1 Verified behaviour (read for this revision)D.2 The five mechanisms that do not survive, and what replaces themD.3 The one rule that replaces transactionalityD.4 What we lose, stated plainlyD.5 Sizing and the split triggerE. Target architectureE.1 Deployment shapeE.2 Component responsibilitiesE.3 Trust boundariesE.4 D1 access classes: replication is the new cache problemE.5 Repository shapeE.6 Frontend hosting: Pages, with the compatibility question left open on purposeF. Technology decisionsG. Data model summaryH. API architectureH.1 What is preservedH.2 The browser route, decided explicitlyH.3 RealtimeI. Asynchronous execution on D1I.1 The outboxI.2 The consumer: states, not a flagI.3 Sends are not queuedI.4 Dead letters, and recovery when the DLQ itself failsI.5 The worker lease (scrape/ingest)J. AI architectureJ.1 Evaluated first, not assumedJ.2 The provider seam survives; the default changesJ.3 PrivacyJ.4 What S7 must decideK. Security architectureK.1 Authentication: the item that got easierK.2 Session → Bearer JWTK.3 Ownership without RLSK.4 SecretsL. Reliability and observabilityL.1 What D1 changes about failureL.2 Logging and evidenceM. Capacity: D1's single writer is the real ceilingM.1 Current and projectedN. CostN.1 Verified figures (read for this revision)N.2 What the plan costsO. Migration and cutoverO.1 PrincipleO.2 PhasesO.3 Cutover and rollback, stated honestlyP. Failure modesQ. Architecture decision recordsADR-1 — D1 as the single primary databaseADR-2 — batch() and guarded updates replace transactions and locksADR-3 — No Durable Objects, no Workflows at cutoverADR-4 — Better Auth with its native D1 dialectADR-5 — Workers AI first, per-purpose provider mapADR-6 — KV for JWKS and public config onlyADR-7 — 41 tables, single namespaceADR-8 — Pages for the frontend, with S3 as the gateADR-9 — API surface frozenADR-10 — Containers only where native execution failsR. Unresolved assumptionsS. Findings registerT. Spike acceptance criteriaS1 — Better Auth on D1 (blocking)S2 — D1 integrity and concurrency (blocking) — RAN: PASS (local + remote)IntegrityCaps and concurrencyS3 — Pages / frontend compatibility (blocking, report-only)S4 — Queues and Worker execution (blocking)S5 — Python/Go runtime (blocking for those components)S6 — R2 lifecycle and account erasure (blocking)S7 — AI architecture (blocking for AI features)U. Final recommendationS1 and S2 PASS. 31 assertions plus a NOT NULL audit, twice each,and the repository-isolation tests behind L-D1-1. S1 also produced a PASS (16/16,better-auth 1.7.25); S3 is the next spike, and it is blocked on Pages credentials.The architecture is coherent under D1; one mechanism (no RLS) remains a real regression —now covered by tests rather than by an argument.What I am not claimingApproval gate