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
| Rev | Target | Verdict |
|---|---|---|
| 1 | Cloudflare compute + Neon Postgres via Hyperdrive | Rejected: 7 critical findings |
| 2 | Same, corrected | Approved for spikes only |
| 3 | Cloudflare-native: D1 + Pages + R2 + Queues + Workers AI | Awaiting 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.
| # | Invariant | Where it lives |
|---|---|---|
| A1 | Never claim an external effect that did not happen. A send returns sent / sent_unrecorded / uncertain / failed; unknown means may have been delivered | email_drafts.status, the HTTP response, the UI |
| A2 | Caps are real and server-owned. 5 applies/day, 50 emails/day, one implementation | cap_quota + the send path |
| A3 | Ownership is never taken from the client. The principal comes from the verified session | middleware + composite FKs |
| A4 | AI output is a draft. No model output sets a status implying a send | draft state graph |
| A5 | Preference gates run before the money step. Missing preference row → fail closed | send + apply paths |
| A6 | The API surface is frozen for the duration: 58 paths, same shapes, same error envelope | openapi.yaml |
| A7 | Dry-run is the default, CAPTCHAs are never auto-solved in the app/apply paths | apply engine |
| A8 | Erasure must actually erase, including objects | ops_erasure_jobs |
B. Current state (verified)
- 42
defineTabledeclarations inserver/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 bytools/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)
| Fact | Consequence |
|---|---|
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 sequence | Multi-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" error | Writes 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 roles | Ownership is a code + constraint property, never a database-enforced read filter |
No FOR UPDATE / SKIP LOCKED | Leasing 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 result | A 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 replica | A 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 = false | The 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 D1 | Replacement |
|---|---|---|---|
| 1 | BEGIN … SET LOCAL app.user_id … COMMIT + RLS | No transactions to scope a session variable to; no RLS to read it | Ownership 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 |
| 2 | SELECT … FOR UPDATE SKIP LOCKED for claims | No row locks, no skip-locked | Guarded UPDATE … WHERE <claimable> … RETURNING, atomic because statements are serialized; zero rows returned = lost the race |
| 3 | Counting INSERT … WHERE (SELECT count(*)) < cap | Was already wrong; on D1 the interleaving is different but the pattern is still a read-then-write | Guarded UPDATE on cap_quota with the guard in the statement, plus a CHECK (used <= limit_value) as a backstop |
| 4 | Effect + completion in one interactive transaction, fenced by lease_id | Batch order is static; you cannot decide mid-batch | Idempotent effect first, guarded completion second. Ordering inverted, so a crash between them re-runs an idempotent no-op instead of losing work |
| 5 | Two Hyperdrive bindings to separate the cache from tenant data | D1 has no query cache, but it does have read replicas | Two 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
| Lost | Impact | Mitigation | Residual risk |
|---|---|---|---|
| RLS | A missed WHERE owner_id = ? is a cross-tenant read. Postgres would have caught it at the database | Composite 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 exists | This 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 transactions | Multi-step business logic cannot decide-and-write atomically | batch() for static sequences; guarded single statements for decide-and-write | A sequence whose statements depend on a runtime decision needs a compensating step |
| 10 GB ceiling | Corpus + logs + audit must fit | Logs already leave the database (ADR-6); audit is bounded by retention; corpus is the growth driver | A sizing trigger and a split plan (§D.5) |
| Single-threaded writes | Throughput ceiling ≈ 1 / write-duration per database | batch() amortises round trips; writes are few and small | At 100× this still holds; measured, not assumed (R4) |
D.5 Sizing and the split trigger
| Component | Estimate | Basis |
|---|---|---|
| Product rows (100 users) | < 100 MB | 22 tables × bounded rows/user |
| Corpus (postings) | UNKNOWN | R3 — average description bytes × growth rate were never measured |
| Audit + incidents | < 50 MB with 400-day retention | bounded by write rate |
| R2 objects | not in D1 | ré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
| Component | Owns | Must never |
|---|---|---|
| Pages (frontend) | Rendering, the client store, the demo/offline seam | Hold authoritative state, mint tokens, call D1 directly |
| Pages Functions | Same-origin proxy for /api/v1/*, auth routes, size cap, correlation id, deadline | Route, validate business fields, or retry |
| API Worker | Authn/authz, all business rules, the API contract, the outbox write | Trust a client-supplied owner id, or do long CPU work inline |
| Async Worker | Consumer state machine, retries, DLQ persistence | Hold the only record that work exists |
| D1 | Authoritative state, constraints, the outbox table, the lease table | Hold logs, blobs, or prompt bodies |
| R2 | Résumés, avatars, page bodies, export artifacts, log archive | Serve private objects without a signed URL |
| KV | JWKS and public config only | Hold anything on a path that decides an external effect (eventual consistency) |
| Queues | Transport for idempotent work | Carry a send, or be the only record that work exists |
| Cron | Sweeps, reconciliation, the Gmail poll | Call an authenticated user path |
| Workers AI | Model inference behind the provider seam | Receive content unless the owner opted in |
| Containers | Go/Python execution if native Workers cannot host it | Decide 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
| Boundary | Threat | Control |
|---|---|---|
| Browser → Pages | Forged identity, oversized body | Bearer JWT verified downstream; 256 KiB cap at the proxy and again in the API |
| Pages → API Worker | Header smuggling | Service binding only; the API re-verifies the token and re-derives the owner |
| API → D1 | Cross-tenant read/write | Composite FKs (writes) + repository layer (reads) + tests. No RLS (L-D1-1) |
| API → R2 | Object enumeration | Keys are u/<owner_id>/...; the owner id in the key is derived server-side; signed URLs are short-TTL |
| Queue → Async Worker | Forged or replayed messages | HMAC on the message body; consumer_deliveries state machine, never a presence flag |
| Containers → D1 | Privilege escalation | Service tokens per surface, no shared fallback; containers write through the API, not directly to D1 |
| Model → DB | Prompt injection causing a write | No 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.
| Class | Binding/API | Used for | Guarantee |
|---|---|---|---|
withPrimary(fn) | env.DB directly, no session | owner-scoped reads and writes, caps, state machines, auth, authorization, read-after-write | primary only; strongest available |
withCorpus(fn) | env.DB.withSession(...) | corpus_* reads only (job postings) | sequential within the session; replicas allowed |
Enforcement:
src/platform/db.tsexports exactly these two, and nothing else accepts aD1Database.withCorpusis importable only fromsrc/features/jobs/corpus/*; a CI grep fails the build if the session API appears elsewhere.- Every repository function takes an
ownerIdparameter or is explicitly marked/* corpus */. The query layer refuses to build a statement against an owner-scoped table without one. - A test enumerates tables with an
owner_idcolumn 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 DBE.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:
- 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/cloudflareadapter tracks them. Whether Next 16 works on Pages is not established by this document and will be answered by S3. - 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,/signupmust become prerendered or client-side.
Decision rule, declared in advance so S3 is a measurement and not a negotiation:
| S3 finding | Action |
|---|---|
| Next 16 builds and serves all 13 routes on Pages | Proceed as drawn |
| Next 16 fails on Pages, static export preserves all functionality | Switch to static export + Pages Functions; re-verify the 3 SSR routes as prerendered |
| Next 16 fails on Pages and static export loses functionality | Stop 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
| Concern | Decision | Rejected, and why |
|---|---|---|
| Primary database | D1 | Durable Objects SQL (per-object sharding, no cross-entity queries); KV (no queries, eventual); external Postgres (off the table per the driver) |
| Files | R2, private bucket, prefix-per-owner | D1 blobs (2 MB row cap, and blobs do not belong in an OLTP row) |
| Frontend hosting | Cloudflare Pages | Workers hosting — only if S3 proves Pages cannot serve Next 16, and only with owner approval |
| API | One API Worker + Pages Functions as a thin same-origin proxy | Putting business logic in Pages Functions (Couples the API to the frontend deployment) |
| Async | Queues + Cron, with the outbox in D1 | Durable Objects as a queue (extra state to own); Workflows (durable multi-step not required; discovery is a bounded loop) |
| Cache | KV for JWKS + public config only | KV for anything transactional |
| AI | Workers AI evaluated first, provider seam retained | Groq-only (fails the consolidation goal); local tunnel (single workstation, never ran end-to-end) |
| Go/Python workers | Containers, if S5 shows WASM/Workers cannot host them | Rewriting the scraper or the CLI for Workers speculatively |
| Auth | Better Auth with its native D1 dialect | Hand-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:
| Prefix | Count | Contents |
|---|---|---|
auth_* | 4 | Better Auth's own tables (vendor-owned, never hand-edited; not counted in the 42) |
| (unprefixed product tables) | 24 | owner-scoped: profiles, resumes, profile_links, searches, drafts, events, … |
corpus_* | 5 | shared, ownerless reference data |
ops_* | 13 | outbox, 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)| Concern | Decision |
|---|---|
| Same origin | Yes — the browser never sees a second host |
| Cookies | Auth routes use SameSite=Lax; API calls authenticate by Bearer only, which removes the CSRF surface from every mutating route |
| CORS | Not needed. If a public API origin is ever added, this section is rewritten first |
| Size | 256 KiB at the proxy and in the API |
| Cancellation | request.signal is forwarded into the binding call |
| Correlation | x-request-id generated at the proxy if absent, written to ops_audit_events |
| Failure | Binding 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:
| Result | Meaning | Action |
|---|---|---|
| Row returned | We hold the lease | Do the work |
No row, existing completed | Already done | Ack — the only short-circuit |
No row, processing, lease live | Someone else is working | Throw (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
| Scenario | Response |
|---|---|
| Consumer fails repeatedly | attempt > 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 *;| Phase | Guarantee |
|---|---|
| Eligibility | status='queued' AND available_at <= now() — delayed work is one concept, not a status |
| Claim | Server-generated lease_id; zero rows = another worker won |
| Heartbeat | Guarded UPDATE … WHERE lease_id=? AND status='claimed' AND lease_expires_at > ? |
| Fencing | Every write carries lease_id and an unexpired lease, so a stale worker cannot write even before reclaim |
| Ingest | Bounded ≤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 |
| Completion | After the idempotent ingest (§D.3), guarded by lease_id |
| Retry | Reaper returns claimed + expired-beyond-grace to queued with backoff; 3 strikes → failed, fail closed |
search_id | A 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:
| Purpose | Input | Current prompt | Suitability question for S7 |
|---|---|---|---|
| Résumé → profile | résumé text (30–60 KB) | prompt 07 | Does the context window and extraction accuracy hold? |
| Profile dossier | profile JSON | prompt 07 | Structured output fidelity |
| Job ranking | 20 postings/run | prompt 02 | Cost per run vs. quality |
| Keyword expansion | one search | prompt 01 | 3-term expansion |
| Outreach planner | target + presets | prompt 03 | 50-lead cap |
| Cold-email drafting | contact + profile | prompts 04–06 | Tone and length compliance |
| Reply classification | one email | prompt 06 | 6-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 machineNo 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
| Rule | Mechanism |
|---|---|
| Résumé and email content go to Workers AI only if the owner opted in | user_preferences.ai_provider with an explicit value; no default that implies consent to a third party |
| A different provider requires a new choice | Changing ai_provider is an explicit user action, shown with what it means |
| Prompt and completion bodies are never stored | ops_ai_runs keeps provider, model, token counts, latency, status, error_class — never content |
| Budget is reserved before the call, settled after | ops_rate_windows guarded updates; env knobs read in the action, never a mutation |
J.4 What S7 must decide
- 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)?
- Is the neuron cost per rank run (20 postings) and per classification within the free allowance or trivially above it?
- Does the 10,000-neuron/day free allocation cover the beta workload, and what is the cost at 10× that?
- Which purposes need a stronger model, and is the tiering (small model for classification, larger for extraction) expressible in the seam?
- 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:
| Requirement | Why it is still a spike |
|---|---|
| Google OAuth end to end | Provider config, redirect URIs on a Pages origin |
| Explicit account linking by verified email only | The 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 link | The most dangerous regression in any auth migration |
| Gmail refresh token retrieval | Must still resolve through auth_account via a pointer, with email_accounts.token_secret_reference never holding a token |
| Separate Gmail consent | Scopes requested incrementally, not bundled with login |
| Session revocation and expiry | Revocation must stop refresh immediately; access-token expiry ≤ 15 min is an accepted, stated limit |
| UUID ids | Better Auth's default string ids must be reconciled explicitly; the FK type follows the auth table, never the reverse |
| Auth schema migration | Better Auth's generated D1 schema must round-trip through the migration runner |
K.2 Session → Bearer JWT
| Property | Decision |
|---|---|
| Issuer / audience | App origin / jobwzrd-api |
| Subject | auth_user.id — the only source of owner_id |
| Expiry | 15 minutes; refresh via the session cookie |
| Signing | Asymmetric (ES256), so the API verifies with a public key and holds no signing secret |
| Verification | JWKS cached in KV with a TTL (public data, eventual consistency acceptable) and refetch-on-unknown-kid |
| Revocation | Refresh stops immediately; an issued access token lives ≤ 15 min. Stated, not hidden |
| Cookies | SameSite=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:
| Layer | Mechanism | Strength |
|---|---|---|
| Write | Composite FKs (parent_id, owner_id) → UNIQUE (id, owner_id) on parents | A cross-owner edge is unrepresentable |
| Write | owner_id on every row, NOT NULL, REFERENCES auth_user(id) ON DELETE CASCADE | Orphan rows impossible |
| Read | One repository layer; every function takes ownerId or is marked /* corpus */ | A single place to audit |
| Read | CI test: every table with owner_id has a repository entry; withCorpus is unreachable from owner code | Structural |
| Regression test | Two-owner fixture asserting empty cross-reads on every owner-scoped table | Detectable |
| Residual | A missed predicate inside one repository function is a leak. PostgreSQL would have caught it at the database | Limitation 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
| Behaviour | Consequence |
|---|---|
| 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 ceiling | Writes 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.
| Destination | Contents | Delivery | Guaranteed? | Retention |
|---|---|---|---|---|
ops_audit_events (D1) | every external effect, cap charge, refusal, erasure step | same batch as the effect | Yes | 400 days then purge |
ops_dlq_incidents (D1) | dead-lettered work | consumer or outbox reconciler | Yes — two independent writers | until resolved |
| Workers Logs | request diagnostics | platform, sampled (100% errors, 10% info) | No — best effort | plan-defined (UNKNOWN, R10) |
R2 logs/YYYY/MM/DD/*.jsonl | diagnostic archive | Logpush (Paid feature) | No — no per-record ack | 30 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
| Property | Value | Source |
|---|---|---|
| Writes | Serialized 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 written | D1 docs |
| Queries per invocation | 1,000 (Paid) / 50 (Free); a batch() counts as one | D1 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.
| Scale | Users | Reads/day | Writes/day | Peak write rate | Verdict |
|---|---|---|---|---|---|
| 1× | 1 | ~2,000 | ~200 | « 1/s | Trivial |
| 10× | 10 | ~20,000 | ~2,000 | ~0.1/s | Trivial |
| 100× | 100 | ~200,000 | ~20,000 | ~1/s | Comfortable, 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)
| Item | Value | Source |
|---|---|---|
| D1 size limit | 10 GB Paid / 500 MB Free | D1 limits |
| D1 databases | 1,000,000 Paid (first 100,000 included) / 10 Free | D1 limits |
| D1 Time Travel | 30 days Paid / 7 Free | D1 limits |
| Queues | Free 10k ops/day, 24 h retention non-configurable; Paid 1M ops/mo + $0.40/M, retention 4–14 days | Queues pricing |
| R2 | 10 GB-month, 1M Class A, 10M Class B free; $0.015/GB-mo; $4.50/M Class A; $0.36/M Class B; egress $0 | R2 pricing |
| Workers AI | 10,000 Neurons/day free on both plans; $0.011 / 1,000 Neurons above | Workers AI pricing |
| Workers Paid base | $5/mo | Workers pricing |
| Workers subrequests | 50 Free / 10,000 Paid per request | Workers limits |
| D1 rows read / rows written (Free allowances, Paid rates) | UNKNOWN for this revision — read the D1 pricing page at decision time | not verified here |
N.2 What the plan costs
| Scale | Workers | D1 | R2 | Queues | Workers AI | Neon | Total/mo |
|---|---|---|---|---|---|---|---|
| Spike phase | Free | Free | Free | Free | Free (10k Neurons/day) | $0 | $0 |
| Beta (1 user) | Paid $5 | within free allowances (UNKNOWN, likely) | within free tier | within free | possibly above 10k Neurons on résumé extraction | $0 | $5–15 |
| 10 users | Paid $5 | likely small paid usage (UNKNOWN) | ~free | small | dominates if AI-heavy | $0 | $20–60 |
| 100 users | Paid $5 | needs measurement | small | small | dominates | $0 | $60–200 |
Three honest statements:
- 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.
- 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.
- 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
| # | Phase | Deliverable | Reversible? |
|---|---|---|---|
| 0 | Baseline + driver | Driver recorded (done: consolidation + independence), current Convex billing captured, git status clean | n/a |
| 1 | Spikes S1–S7 | Seven verdict documents. Any red spike stops the migration at its own boundary | Yes — throwaway |
| 2 | Skeleton + schema v1 | backend/, migrations/0001_init.sql (41 tables, single namespace), constraints tested, repository layer + ownership tests | Yes — drop the DB |
| 3 | Auth on D1 | Better Auth + D1 dialect; S1's invariants as tests | Yes — throwaway DB |
| 4 | Read path | Corpus + product reads through the repository; withPrimary/withCorpus proven | Yes |
| 5 | Write path | Guarded updates; caps; draft state graph; attachments | Yes |
| 6 | Async | Outbox, consumer states, DLQ, reconciler, worker lease | Yes |
| 7 | Blobs + erasure | Upload intents, lifecycle, prefix sweep, verified deletion | Yes |
| 8 | Contract parity | All 58 operations; the OpenAPI drift test against server/openapi.yaml | Yes |
| 9 | Data migration | One-time export from Convex → D1 into a mirror; counts reconciled | Yes |
| 10 | Frontend cutover | Pages build; polling replaces subscriptions; nothing writes to D1 | Yes — env flip |
| 11 | Shadow window | Dual reads against the mirror; zero unexplained diffs | Yes |
| 12 | Cutover + rollback drill | Write freeze, final export, import, reconcile, auth+API together, first new write | Irreversible at the first D1 write |
| 13 | Decommission Convex | Only after the shadow window and a both-directions drill | Irreversible |
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:
| Window | Action | Lossless? |
|---|---|---|
| Before the first D1 write | Flip the env var back | Yes |
| During the write freeze | Abort; users see a maintenance window with no writes | Yes |
| After the first D1 write | Rollback = migrate back: export D1, import into Convex, reconcile, then flip | No — 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.
| # | Failure | Mechanism | Impact | Detection | Prevention | Recovery |
|---|---|---|---|---|---|---|
| P1 | Better Auth cannot reproduce linking policy on D1 | Adapter differences in account rows | Security — an OAuth login could attach to the wrong account | S1's linking tests | Port authLinking.test.ts verbatim as acceptance | Full stop; do not proceed |
| P2 | A missed owner predicate leaks a row | No RLS to catch it (L-D1-1) | Cross-tenant read | Two-owner fixture on every table | Repository layer + CI enumeration | Fix the predicate; add the table to the fixture |
| P3 | Cap over-charged or free | Read-then-write instead of a guarded update | User blocked or sends unlimited | Q1–Q7 concurrency tests | Guard in the UPDATE + CHECK (used <= limit) | Correct used from the ledger |
| P4 | Queue retry duplicates an email | A send on a queue | A real second email to a real person | Send path has no queue | Sends are synchronous (§I.3) | Impossible by construction — keep it that way |
| P5 | Consumer acks without doing work | Presence-based dedupe | Silent work loss | S4 takeover test | completed is the only short-circuit | Replay from the outbox |
| P6 | DLQ consumer cannot write, message expires | Retry budget 0, or retention 24 h | Work disappears with no record | Outbox reconciler incident count | Non-zero retries + reconciler reading D1 | Replay from ops_outbox |
| P7 | D1 overloaded under load | Single-threaded writer, queue full | 503s under normal use | "overloaded" error rate | Batching, small writes, split trigger | Split corpus (§D.5); back off |
| P8 | D1 hits 10 GB | Corpus growth (R3 unknown) | Writes fail | Size dashboard + 40% alarm | Retention, log egress, split trigger | Split corpus to a second database |
| P9 | Résumé extraction quality unacceptable | Workers AI model too small | Core feature unusable | S7 quality table | Per-purpose provider map | Stronger model for extraction only |
| P10 | Pages cannot serve Next 16 | Adapter lag | Frontend blocking | S3 | Declared decision rule (§E.6) | Static export or owner decision on hosting |
| P11 | A stale replica read shows pre-write state | Default first-unconstrained session | Confusing UI, wrong cap display | HC-D1-2 | withPrimary for owner data | Use a session first-unbound→primary |
| P12 | Erasure reports complete with objects left | Row-driven deletion misses orphans | Compliance failure | Empty-listing verification | Prefix sweep, repeat until empty | Re-run; never mark complete on a partial pass |
| P13 | Migration stalls at 60% | Scope creep mid-flight | Cost without value | Phase checklist | Phases are independently abandonable | Stop; 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 guardedUPDATE … 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
| # | Unknown | Why it matters | How it closes |
|---|---|---|---|
| R1 | Current Convex cost | Baseline for the consolidation claim | Billing export, Phase 0 |
| R2 | No AI purpose has ever run end to end through a real provider on real data | Migrating an unproven pipeline is a different risk class | S7 |
| R3 | Corpus growth rate / average description size | Decides whether 10 GB is near | Measure jobs size |
| R4 | Actual request and write volume | The capacity model is structural, not measured | Convex dashboard |
| R5 | Realtime subscription inventory | A missed one is a dead screen | Enumerate before Phase 10 |
| R6 | Whether any queue is warranted at this scale | Inline classification may be simpler | Product decision on latency |
| R7 | D1 rows-read / rows-written pricing and free allowances | Cost model cannot be exact | D1 pricing page at decision time |
| R8 | Whether Next 16 works on Pages | Blocks the frontend phase | S3 |
| R9 | Gmail per-user daily send quota | 50/day is probably under it | Google console |
| R10 | Workers Logs retention per plan | Archive necessity | Docs at decision time |
| R11 | Workers AI extraction quality on the owner's résumés | Core feature viability | S7 |
| R12 | Whether a second user will exist | Multi-tenant work is Phase 2 or later | Product decision |
| R13 | Whether unknown can be resolved by Gmail search rather than a human | Removes a manual step | messages.list probe |
| R14 | Whether Go compiles usefully to WASM here (scraper uses HTTP + parsing) | Decides Containers vs Workers | S5 |
| R15 | Whether Python (apply CLI) can run on Workers at all | Same | S5 |
| R16 | Whether batch() of 200 ingest rows stays under 30 s | Ingest shape | S2/S4 |
| R17 | Whether a D1 session bookmark is needed for corpus pagination | Correctness of paging | S2 |
S. Findings register
Findings carried from the adversarial review, plus the ones the retarget created.
| ID | Severity | Finding | Decision | Verification | Remaining limitation |
|---|---|---|---|---|---|
| SD-01 | Critical | Postgres/Hyperdrive cache sat in front of RLS | Superseded: D1 has no query cache, but replicas create the same staleness class | withPrimary for owner data; withCorpus sessions for corpus only | A corpus read may be seconds stale — accepted |
| SD-02 | Critical | Independent owner FKs allowed cross-tenant edges | Composite FKs survive in SQLite and are kept | Cross-owner insert rejected for every edge | — |
| SD-03 | Critical | Presence-based dedupe lost work | ops_consumer_deliveries state machine; completed only short-circuit; effects before completion (§D.3) | S4 takeover test | Two consumers may briefly hold the work; one wins the guard |
| SD-04 | Critical | Counting insert raced past the cap | Guarded UPDATE with the predicate inside, plus CHECK (used <= limit_value) | S2 Q1–Q7 | Changing the cap's day boundary can over-grant one day |
| SD-05 | Critical | Send/outbox contradiction | Sends never queued; no command event exists | Assert no send path enqueues | At-least-once for the events that are queued |
| SD-06 | High | uuid[] pretending to be a FK | Normalised email_draft_attachments (JSON text cannot be a FK either — so a join table) | Cross-owner attachment rejected | — |
| SD-07 | Critical | Lease referenced queue vs queue_name; delayed unclaimable | Fixed; available_at is the only delay concept; full lifecycle (§I.5) | S4 claim/heartbeat/fence/reap | — |
| SD-08 | High | Draft states had no graph | Full graph; queued removed; one CHECK + a transition function | Every illegal edge refused | Graph is code-enforced except one edge |
| SD-09 | Critical | Better Auth via a module-scope pg pool | Resolved by the platform: D1 dialect, no held connection | S1's eleven items | Gmail token path and linking still must pass |
| SD-10 | High | Browser cannot use a service binding | Pages Function proxy → env.API.fetch() | Trace shows one hop, no CORS | The proxy is a second place a contract could drift |
| SD-11 | Critical | Auth cut over before the API | Auth and API cut over together in Phase 12 | Staging login→call→logout on one authority only | Users re-authenticate unless sessions migrate |
| SD-12 | Medium | Log "archive" was not a delivery design | Evidence in D1, transactionally; logs best-effort | Purge-failure test | No per-record archive guarantee |
| SD-13 | Medium | Workers Paid claimed mandatory for Hyperdrive/Queues | Recomputed on real limits; Paid recommended for subrequests, retention, Logpush | Cost sheet with sources | D1 usage pricing unverified (R7) |
| SD-14 | Critical | "Rollback is a flip" after the first write | Write freeze + named irreversible point + migrate-back | Both directions drilled | Migrate-back is lossy for rows with no Convex shape |
| SD-15 | Medium | Inventory arithmetic did not reconcile | Scripted inventory, 42 → 41 | tools/check_table_inventory.py | — |
| SD-16 (new) | Critical | No RLS on D1 — a missed predicate is a cross-tenant read | Composite FKs for writes; repository layer + CI enumeration + per-table two-owner fixtures for reads | S2 HC-D1-1 across all owner tables | L-D1-1: one buggy repository function can leak |
| SD-17 (new) | High | No interactive transactions — decide-and-write cannot be a transaction | Guarded single statements; static batch(); effects-before-completion ordering | S2 exercises each guarded path | A multi-step decision needs a compensating step |
| SD-18 (new) | High | Single-threaded writer — throughput ceiling, "overloaded" errors | Batching, small writes, split trigger at 4 GB | S2/S4 load probe | Shared ceiling for all users on one database |
| SD-19 (new) | High | Pages may not serve Next 16 | Declared decision rule in §E.6; nothing switches silently | S3 | The frontend host may need an owner decision |
| SD-20 (new) | Medium | AI provider migration unproven on real data | Workers AI evaluated per purpose; no silent fallback | S7 | Per-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.
| # | Criterion | Pass |
|---|---|---|
| 1.1 | betterAuth({ database: env.DB }) initialises under the real request lifecycle | Signup and login both succeed across ≥20 sequential requests in one isolate |
| 1.2 | Auth schema generated and applied by the migration runner | auth_user, auth_session, auth_account, auth_verification exist with the expected columns |
| 1.3 | ID types reconciled | auth_user.id, auth_session.user_id, and every owner_id FK accept the same value; a wrong-type FK fails at insert |
| 1.4 | Google sign-in works end to end | New user, session issued, JWT verifiable via JWKS |
| 1.5 | Account linking by verified email only | Same verified email links to the existing user; a different verified email does not; an unverified local email does not |
| 1.6 | Unverified local email cannot be hijacked | Reproduce the authLinking.test.ts cases verbatim; all pass |
| 1.7 | Gmail consent is separate from login | Scopes requested incrementally; login works without Gmail scopes |
| 1.8 | Gmail refresh token retrieveable through the pointer | email_accounts.token_secret_reference holds better-auth:account:<id>, never a token; a Gmail API call succeeds using it |
| 1.9 | Session revocation | Revoked session cannot refresh; existing access token expires ≤15 min |
| 1.10 | Session expiry | Expired token rejected with UNAUTHENTICATED by the API |
| 1.11 | Concurrent auth requests | 20 concurrent sign-ins/reads in one isolate: no batch() transaction errors, no lost sessions |
| 1.12 | Failure behaviour | Provider 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 NULLaudit, 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 —
Finding The claim that failed Correction now in DATA-MODEL-PROPOSAL.mdDM-23 the ledger insert is "only reached if statement 2 matched" WHERE changes() = 1DM-23b consequence: 8 sends on a 5/day cap via phantom-row refunds same guard DM-24 EXISTS(released_at = ?)makes refunds idempotentchanges() = 1DM-25 composite ON DELETE SET NULLpreservesowner_idplain FK + same-owner triggers DM-26 parkeddeliveries 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_infoon its internal_cf_*tables (SQLITE_AUTH) while still listing them insqlite_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
| # | Criterion | Pass |
|---|---|---|
| 2.1 | Composite ownership FKs exist and are enforced | Cross-owner child insert (dossier_id of A, owner_id of B) is rejected at every edge in the checklist |
| 2.2 | CHECK constraints hold | cap_quota.used <= limit_value, status enums, draft sending ⇒ send_started_at |
| 2.3 | Partial unique indexes work on D1 | One active résumé per owner; email_events dedupe only where provider id is present |
| 2.4 | ON DELETE CASCADE from auth_user | Deleting a user removes every owned row and leaves ops_audit_events (pseudonymised) intact |
| 2.5 | Ownership isolation across all owner tables | HC-D1-1: for every owner-scoped table, owner B reads zero rows of owner A, with identical SQL text and parameters |
| 2.6 | Read-after-write | HC-D1-2: withPrimary write → immediate read returns the written state, 200 iterations, no stale |
| 2.7 | Corpus session behaviour | HC-D1-3: withCorpus returns consistent pages; a bookmark resumed later does not reorder |
Caps and concurrency
| # | Criterion | Pass |
|---|---|---|
| 2.8 | Cap never exceeded | Q1: 50 concurrent distinct operations against a cap of 5 → exactly 5 succeed, 45 refusals, used = 5 |
| 2.9 | Never double-charged | Q2: same op_key 10× concurrently → exactly one ledger row, used moves by exactly 1 |
| 2.10 | Refund is idempotent | Q3/Q4: charge → release → release again → used decremented exactly once |
| 2.11 | Day boundary | Q5: a charge at 23:59:59.9 UTC and one at 00:00:00.1 → two rows, independent caps |
| 2.12 | Lowering a limit is guarded | Q6: the limit change is rejected when used > new_limit |
| 2.13 | Guarded update is atomic under load | Q7: the same as Q1 with 200 concurrent attempts and artificial latency; never 6 |
| 2.14 | Write latency measured | p50/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.
| # | Criterion | Pass |
|---|---|---|
| 3.1 | Build the current app for Pages | Build succeeds on Next 16 or fails with a specific, quotable reason |
| 3.2 | All 13 routes serve | Each route returns 200 (or its intended redirect) from a Pages preview |
| 3.3 | SSR markers present | /, /login, /signup contain server-rendered content in the HTML, not an empty root div |
| 3.4 | Static export evaluated | output: 'export' attempted; report exactly which features break (API routes are known to be unsupported under export) |
| 3.5 | Pages Functions boundary | /api/auth/* and /api/v1/* proxy work as Pages Functions with the service binding |
| 3.6 | Subrequest count | SSR routes stay under the per-request subrequest ceiling (50 Free / 10,000 Paid) |
| 3.7 | Environment mapping | NEXT_PUBLIC_* values reach the browser under the Pages build, read through the existing env.ts table |
| 3.8 | Verdict table | For 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?
| # | Criterion | Pass |
|---|---|---|
| 4.1 | Pages/Worker → Queue producer | A Pages Function and a Worker both enqueue successfully with separate bindings |
| 4.2 | Separate consumer Worker | Consumer receives, acks, and retries as configured |
| 4.3 | Outbox lease | Claim commits before publish; a process killed between publish and confirm re-publishes, and the consumer does not double-apply |
| 4.4 | Consumer state machine | completed is the only short-circuit; processing with a live lease causes a throw, not an ack |
| 4.5 | Takeover | Kill the consumer mid-work; after lease expiry a second consumer takes over and the effect is applied exactly once |
| 4.6 | Batch failure semantics | One failing message in a batch retries the batch; explicitly acked messages are not re-delivered |
| 4.7 | DLQ path | max_retries exhausted → message lands in the DLQ → DLQ consumer writes ops_dlq_incidents with identifiers only, no payload bodies |
| 4.8 | DLQ consumer failure | Simulate D1 unavailable: the DLQ consumer does not ack, retries, and messages are not lost on first failure |
| 4.9 | Reconciler independence | With the queue fully broken, the outbox reconciler writes incidents from D1 alone |
| 4.10 | Worker lease and fencing | Claim/skip, heartbeat, expired-lease write rejected, reaper requeues, 3 strikes → failed |
| 4.11 | Idempotent ingest | Replaying 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.
| # | Criterion | What is measured |
|---|---|---|
| 5.1 | Workers/WASM feasibility | Does 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.2 | Python on Workers | Is there a Python runtime path, and does the CLI's dependency set fit? |
| 5.3 | Containers | Build and run both as Containers against a D1-backed API; measure cold start, image size, cost at this workload |
| 5.4 | Minimal adaptation | For each failing dependency, is the adaptation a small change or a rewrite? List them concretely |
| 5.5 | Boundary preserved | In every option, the worker writes through the API, never directly to D1/Convex, and keeps per-surface service tokens |
| 5.6 | Recommendation table | Per 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?
| # | Criterion | Pass |
|---|---|---|
| 6.1 | Upload intent → object | Intent recorded, key issued, PUT succeeds, finalize verifies size and type via HEAD |
| 6.2 | Upload succeeded, finalize failed | The object is not orphaned forever: the intent expires and cleanup removes it |
| 6.3 | Metadata exists, object missing | A HEAD reconciliation marks the blob missing; download returns an honest 410 |
| 6.4 | Signed URL expiry | A URL past its TTL is refused; a URL cannot be reused to read a different later object |
| 6.5 | Replacement | New object, old object deleted, no dangling reference |
| 6.6 | In-flight upload during erasure | New intents are refused; the sweep waits for outstanding capabilities to expire |
| 6.7 | Verified erasure | Prefix listing repeated until a pass returns zero objects; a partial delete never reports complete |
| 6.8 | Orphan sweep | Objects 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.
| # | Criterion | Pass |
|---|---|---|
| 7.1 | Résumé → profile | Structured extraction matching the profile schema, measured on ≥3 real résumés; record field accuracy per field |
| 7.2 | JSON-schema compliance | response_format: json_schema compliance rate; the JSON Mode couldn't be met path handled and bounded by one retry |
| 7.3 | Ranking quality | 20 postings ranked; agreement with a hand-labelled ordering |
| 7.4 | Classification accuracy | 6-way reply categories on a labelled sample |
| 7.5 | Enrichment | Company/person fields extracted with acceptable accuracy |
| 7.6 | Cost per operation | Neurons per operation, from the dashboard, not from a guess |
| 7.7 | Free allowance | What 10,000 Neurons/day covers; the 10× and 100× cost projection |
| 7.8 | Privacy behaviour | Changing provider is an explicit user action; no content leaves Workers AI unless chosen; provider and model recorded per run |
| 7.9 | Per-purpose verdict | Table: 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.
| Spike | Status |
|---|---|
| S2 — D1 integrity and concurrency | PASS — 31 assertions + audit, green on local and remote D1 (2 runs each). DM-23…DM-28 closed |
| S1 — Better Auth on D1 | RAN: 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 compatibility | not started — next |
| S4 — Queues and Worker execution | not started |
| S5 — Python/Go runtime | not started |
| S6 — R2 lifecycle and erasure | not started |
| S7 — AI architecture | not 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:
| Item | Improvement |
|---|---|
| Auth | D1 removes the module-scope-pool hazard entirely; Better Auth's D1 dialect is a supported path (ADR-4) |
| Cap correctness | D1 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 vendors | From four (Cloudflare, Neon, Groq-by-default, Gmail) to two |
| Operational surface | No connection pooling to tune, no pool exhaustion, no cache-vs-RLS interaction |
What is genuinely worse, and is not glossed over:
| Item | Cost |
|---|---|
| No RLS | Ownership 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 transactions | Some business logic that would have been atomic must become a guarded statement or a compensating step (SD-17) |
| One writer, 10 GB | A shared throughput ceiling and a hard size ceiling with a split trigger (SD-18, §D.5) |
| Pages + Next 16 | Unproven; the frontend host may need an owner decision (SD-19) |
| AI on real data | Never measured, now measured by S7 on the owner's actual résumés (SD-20, R2) |
Sequencing, because not every spike is equally blocking:
| Order | Spike | Why here |
|---|---|---|
| 1 | S2 (D1 integrity + caps) | If this is red, nothing else matters: the whole model assumes guarded updates and composite FKs |
| 2 | S1 (auth) | Security-blocking, and independent of S2 |
| 3 | S3 (Pages) | Decides whether the frontend plan survives at all |
| 4 | S4 (queues) | Needed before any async design is committed |
| 5 | S7 (AI) | Decides whether the product's core feature works |
| 6 | S6 (R2/erasure) | Independent; can run in parallel |
| 7 | S5 (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:
- 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).
- Run S3 next (Pages) — decides whether the frontend plan survives.
- 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.