Data Model Proposal
Cloudflare D1 (SQLite) schema for the JobWizard migration — revision 3.
Revision 2 was written for PostgreSQL. The target is now D1: no schemas, no RLS, no interactive transactions, one single-threaded writer, 10 GB ceiling. Three of revision 2's integrity mechanisms used Postgres features that do not exist here, and one of them (RLS) was the security backbone. All three are re-derived below from what SQLite and D1 actually provide.
Status: design only. No DDL has been written, no database created, no migration run.
Revision history
| Rev | Target | Verdict |
|---|---|---|
| 1 | Postgres | Rejected — 7 critical findings |
| 2 | Postgres | Corrected; approved for spikes |
| 3 | D1 (SQLite) | Approved for spikes |
| 3.1 | D1 (SQLite) | S2 ran and returned REVISE. Four statements corrected below (§2.4) |
| 3.2 | D1 (SQLite) | S2 accepted: PASS on local and remote D1 — 18 core + 3 regression + 10 isolation assertions plus a NOT NULL audit. spikes/d1-integrity/results/FINAL-S2-REPORT.md |
1. The rules this model is built on
- One row, one owner. Every user-owned row carries
owner_id TEXT NOT NULL. - Ownership is a relational fact, not a convention. Composite foreign keys
(parent_id, owner_id)→UNIQUE (id, owner_id)make a cross-owner edge unrepresentable. (SQLite enforces multi-column FKs; this survives the retarget.) - Every counter that can be exceeded is a guarded single statement. No
read-then-write, and no
count(*)comparison. In abatch(), a statement that must happen only if an earlier one matched is guarded bychanges() = 1, because every statement in a batch runs. See §5.3 and DM-23/DM-24. - Idempotent effects run before the state flip that records them. D1 cannot always give "these two writes happen together", so the order carries the guarantee: a crash leaves the effect done and unrecorded, which the retry re-applies as a no-op.
- Deduplication records progress, never presence. A consumer row reaches
completedonly after its effect is committed. "The row exists" is not "the work is done". - Nothing is enforced unless a constraint, a guard, or a test proves it. Where the database cannot enforce something, §9.1 says so in the row it applies to.
1.1 The rule that replaced RLS
Revision 2 leaned on ENABLE ROW LEVEL SECURITY so a missing WHERE owner_id = ? was
caught by the database. D1 has no RLS. That guarantee is gone, and pretending
otherwise would be the most dangerous thing this document could do.
What replaces it, and how strongly:
| Layer | Mechanism | Catches |
|---|---|---|
| Writes | Composite FKs | A row parented onto another owner's record — impossible, not just detected |
| Writes | owner_id NOT NULL + REFERENCES auth_user(id) ON DELETE CASCADE | Orphan rows, null owners |
| Reads | One repository layer; every function takes ownerId or is marked /* corpus */ | A forgotten predicate in one place |
| Reads | CI test: every table with owner_id has exactly one repository entry | A new table with no read path audited |
| Reads | Two-owner fixture per owner table, asserting zero cross-rows | A predicate that exists but is wrong |
Residual risk, named and carried: L-D1-1. A bug inside a repository function can still leak, where PostgreSQL would have refused the read. This is the price of the driver, it is measured by spike S2, and it is the single strongest argument anyone could make against this migration. It is not mitigated away; it is bounded to one layer.
2. Layout and naming
D1 has no schemas, so grouping moves into the table name:
| Prefix | Meaning | Count |
|---|---|---|
auth_* | Better Auth's own tables — vendor-generated, never hand-edited | 4 |
| (none) | owner-scoped product data | 23 |
corpus_* | shared, ownerless reference data | 5 |
ops_* | operational and integrity machinery | 13 |
42 tables of ours + 4 Better Auth tables = 46 physical tables. The 42 is the number
that reconciles against the 42 Convex declarations, and it is computed by
tools/check_table_inventory.py, never by hand.
2.1 Types
SQLite has four useful storage classes and no native uuid/timestamp/json types:
| Concept | Column type | Convention |
|---|---|---|
| Identifier | TEXT | A UUID v4 generated in application code; never INTEGER AUTOINCREMENT for entities (insert order must not leak, and ids are used in R2 keys) |
| Timestamp | INTEGER | Unix milliseconds, UTC. Never a text date |
| Boolean | INTEGER | 0/1 with CHECK (x IN (0,1)) |
| Enum | TEXT | CHECK (x IN (...)) — readable in a query result, unlike an integer code |
| JSON | TEXT | json_extract where a value must be queried |
| Money/score | INTEGER (cents) / REAL | No floating point for money |
| Large text | TEXT or moved to R2 | 2 MB row limit |
No arrays. No uuid[]. An array has no FK and no type; the revision-1 defect (SD-06)
came from exactly that, so §3.17 uses a join table instead.
2.2 What SQLite gives us, and what it does not
| Available | Not available |
|---|---|
PRIMARY KEY, UNIQUE, multi-column UNIQUE | Row-level security |
Composite FOREIGN KEY (a,b) REFERENCES t(c,d) | Interactive BEGIN … COMMIT with app logic inside |
CHECK constraints | SELECT … FOR UPDATE, SKIP LOCKED |
Partial unique indexes (WHERE …) | EXCLUDE constraints |
Expression indexes (lower(email)) | SET ROLE, roles, grants |
ON CONFLICT … DO UPDATE (upsert) | Schemas |
RETURNING (D1 supports it) | gen_random_uuid(), now() |
Two consequences worth stating because they cost code:
- Ids and timestamps come from the application. Every insert supplies its own
idandcreated_at. That is also what makes an insert idempotent at the boundary: the caller decides the key, so a retry can reuse it. EXCLUDEbecomes a partial unique index. "One active résumé per owner" isCREATE UNIQUE INDEX … ON resumes(owner_id) WHERE is_active = 1, which permits zero active résumés and refuses two. Same guarantee, different mechanism.
2.3 The two access classes
Not a schema feature, but a schema-level rule because it is about this data:
| Class | API | Used for | Guarantee |
|---|---|---|---|
withPrimary | env.DB (no session) | every owner-scoped read and write, caps, state machines, auth, read-after-write | primary only |
withCorpus | env.DB.withSession() | corpus_* reads only | sequential within the session; replicas allowed |
A corpus read may be seconds stale. Nothing else may be.
2.4 What S2 changed in this document
Spike S2 ran Q1–Q18 against real D1 (spikes/d1-integrity). The mechanisms survived; four
statements did not. Each correction below is proven by the test that failed without it.
| Finding | The claim that was wrong | Correction |
|---|---|---|
| DM-23 | §5.3: "statement 3 is only reached if statement 2 matched" — false inside a batch() | guard the ledger insert with changes() = 1 |
| DM-24 | §5.3: refunding is idempotent because released_at is set once — a replay re-satisfies EXISTS | guard the decrement with changes() = 1 |
| DM-25 | §3.5/§3.6/§3.17: composite ON DELETE SET NULL "preserves owner_id" — it nulls it, or refuses the delete | plain single-column FK + same-owner triggers |
| DM-26 | §5.7: the claim predicate accepts parked, while the same section says parked means "held" | exclude parked from the claim |
Plus one platform fact with schema consequences: a TEXT PRIMARY KEY in SQLite is
nullable unless declared NOT NULL, so every such key is now written NOT NULL
explicitly. Without that, DM-25's failure mode is worse than an error — it orphans the row.
Final run (revision 3.2). The corrected document was re-tested end to end: twice on
local D1 and twice on a remote Cloudflare D1 preview database (served_by: v3-prod,
region APAC). 31 assertions per target, all green; the four legacy statements still fail
when run deliberately (DM23R/DM23R2/DM24R), so the corrections are proven by contrast
rather than asserted. One remote-only platform fact surfaced: D1 refuses
PRAGMA table_info on its internal _cf_* tables (SQLITE_AUTH) while still listing
them in sqlite_master, so table enumeration filters them explicitly (DM-28).
3. Product tables (23)
Every table below carries owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE
unless stated, and every parent that children point at carries UNIQUE (id, owner_id).
3.0 Composite ownership checklist
Parent (needs UNIQUE (id, owner_id)) | Children referencing it compositely |
|---|---|
profiles | — (1:1, no children) |
resumes | searches, profile_dossiers |
profile_dossiers | profile_sources |
searches | search_results, ops_worker_tasks |
saved_jobs | — (applications use a plain nullable FK, see 3.10) |
email_accounts | email_events, email_drafts |
email_events | email_classifications |
email_drafts | email_draft_attachments |
blobs | email_draft_attachments, user_preferences |
outreach_targets | outreach_contacts, discovery_runs, outreach_fetched_pages |
outreach_contacts | email_drafts, outreach_suppressions |
corpus_companies | company_notes (inverted: its PK is (owner_id, company_id)) |
3.1 There is no users table
Identity is Better Auth's. Ownership anchors directly on it:
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADENo duplicated email/name/avatar copy to drift, no creation cycle between a user and
an avatar blob. What the app needs from identity is read through one view.
Cost: the product schema depends on Better Auth's table names. Accepted, because the alternative — a duplicated email column that silently disagrees with the login identity — is a correctness bug wearing a decoupling costume.
3.2 profiles
CREATE TABLE profiles (
owner_id TEXT PRIMARY KEY REFERENCES auth_user(id) ON DELETE CASCADE,
headline TEXT,
summary TEXT,
location TEXT,
links TEXT NOT NULL DEFAULT '[]', -- JSON array
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);3.3 resumes
CREATE TABLE resumes (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
label TEXT NOT NULL,
is_active INTEGER NOT NULL DEFAULT 0 CHECK (is_active IN (0,1)),
blob_id TEXT,
byte_size INTEGER,
content_type TEXT,
text_blob_id TEXT, -- extracted text lives in R2, not in the row
text_chars INTEGER,
parsed_at INTEGER,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id)
);
CREATE UNIQUE INDEX resumes_one_active ON resumes(owner_id) WHERE is_active = 1;Résumé text is 30–60 KB of prose; keeping it in-row inflates every scan and collides with the 2 MB row limit once a PDF is text-heavy. It goes to R2; the row keeps the pointer.
3.4 profile_dossiers, profile_sources
CREATE TABLE profile_dossiers (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
resume_id TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','ready','failed')),
dossier TEXT, -- JSON
model TEXT,
built_at INTEGER,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
FOREIGN KEY (resume_id, owner_id) REFERENCES resumes(id, owner_id) ON DELETE CASCADE
);
CREATE TABLE profile_sources (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
dossier_id TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('resume','link','manual')),
url TEXT,
blob_id TEXT,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
FOREIGN KEY (dossier_id, owner_id)
REFERENCES profile_dossiers(id, owner_id) ON DELETE CASCADE
);profile_sources is the table revision 1 got wrong: two independent FKs let a source row
parent onto another owner's dossier. The composite key makes that fail at insert.
3.5 user_preferences
CREATE TABLE user_preferences (
owner_id TEXT NOT NULL PRIMARY KEY REFERENCES auth_user(id) ON DELETE CASCADE,
outreach_enabled INTEGER NOT NULL DEFAULT 0 CHECK (outreach_enabled IN (0,1)),
application_automation_enabled INTEGER NOT NULL DEFAULT 0
CHECK (application_automation_enabled IN (0,1)),
avatar_blob_id TEXT,
ai_provider TEXT NOT NULL DEFAULT 'workers-ai'
CHECK (ai_provider IN ('workers-ai','groq','local')),
theme TEXT,
updated_at INTEGER NOT NULL,
-- DM-25: a SINGLE column, so SET NULL cannot touch owner_id.
FOREIGN KEY (avatar_blob_id) REFERENCES blobs(id) ON DELETE SET NULL
);
-- Ownership on a pointer edge is enforced by a trigger, because SQLite has no
-- "composite FK that nulls only one column" (S2/Q13 proved both alternatives fail).
CREATE TRIGGER user_preferences_avatar_owner_ins
BEFORE INSERT ON user_preferences
WHEN NEW.avatar_blob_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM blobs
WHERE id = NEW.avatar_blob_id AND owner_id = NEW.owner_id)
BEGIN SELECT RAISE(ABORT, 'avatar blob does not belong to this owner'); END;
CREATE TRIGGER user_preferences_avatar_owner_upd
BEFORE UPDATE OF avatar_blob_id ON user_preferences
WHEN NEW.avatar_blob_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM blobs
WHERE id = NEW.avatar_blob_id AND owner_id = NEW.owner_id)
BEGIN SELECT RAISE(ABORT, 'avatar blob does not belong to this owner'); END;Why not the composite form (S2/Q13). FOREIGN KEY (avatar_blob_id, owner_id) … ON DELETE SET NULL is implemented by SQLite as "set every column of the key to NULL". With
owner_id nullable that orphans the row (invisible to every owner-scoped read and to
erasure); with owner_id NOT NULL the parent delete is refused outright, so a user could
never delete an avatar. The column-list form ON DELETE SET NULL (avatar_blob_id) is not
accepted by D1's SQLite (near "(": syntax error). The plain FK plus two triggers gives the
wanted behaviour and still refuses a cross-owner pointer — both observed.
Both preference flags default to 0 and fail closed: a missing row is treated as
false, so outreach_enabled being absent refuses a send rather than allowing one.
ai_provider is an explicit choice — there is no default that implies consent to send
content to a third party.
3.6 searches
CREATE TABLE searches (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
resume_id TEXT,
query TEXT NOT NULL,
location TEXT,
remote INTEGER NOT NULL DEFAULT 0 CHECK (remote IN (0,1)),
expanded_keywords TEXT NOT NULL DEFAULT '[]', -- JSON array (max 3)
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued','running','complete','failed','held')),
held_reason TEXT,
result_count INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
-- DM-25: single column, or SET NULL would take owner_id with it.
FOREIGN KEY (resume_id) REFERENCES resumes(id) ON DELETE SET NULL
);
CREATE TRIGGER searches_resume_owner_ins
BEFORE INSERT ON searches
WHEN NEW.resume_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM resumes WHERE id = NEW.resume_id AND owner_id = NEW.owner_id)
BEGIN SELECT RAISE(ABORT, 'resume does not belong to this owner'); END;3.7 search_results
CREATE TABLE search_results (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
search_id TEXT NOT NULL,
job_id TEXT NOT NULL,
rank INTEGER,
score REAL,
matched_by TEXT NOT NULL CHECK (matched_by IN ('keyword-mvp','ai-rank')),
explanation TEXT,
created_at INTEGER NOT NULL,
UNIQUE (search_id, job_id),
FOREIGN KEY (search_id, owner_id) REFERENCES searches(id, owner_id) ON DELETE CASCADE,
FOREIGN KEY (job_id) REFERENCES corpus_jobs(id) ON DELETE CASCADE
);
CREATE INDEX search_results_page ON search_results(search_id, score DESC, job_id);Pagination uses (score DESC, job_id ASC), never rank. Rank is recomputed by the
ranker, so a LIMIT/OFFSET page taken across a re-rank can skip or repeat rows; job_id
is immutable, so the cursor is a total order.
job_id references ownerless corpus data. That is not an ownership hole: the edge is
owned (by search_id), the target is public reference data. Note the corpus FK is the
one edge that would break if corpus is split into a second database (§D.5 of the system
design) — and it is tolerable, because a search can be re-run.
3.8 saved_jobs
CREATE TABLE saved_jobs (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
job_id TEXT,
snapshot TEXT NOT NULL, -- survives corpus pruning; the honest fallback
note TEXT,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
UNIQUE (owner_id, job_id),
FOREIGN KEY (job_id) REFERENCES corpus_jobs(id) ON DELETE SET NULL
);UNIQUE (owner_id, job_id) permits several snapshot-only saves because SQLite treats
NULLs as distinct — which is the intended behaviour, not an oversight.
3.9 applications — manual tracking only
AutoApply is out of scope. No worker claims from here; no engine writes here. Columns are preserved in meaning from the Convex table.
CREATE TABLE applications (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
saved_job_id TEXT,
job_id TEXT,
draft_id TEXT,
stage TEXT NOT NULL DEFAULT 'applied'
CHECK (stage IN ('applied','screening','interview','offer',
'rejected','withdrawn')),
applied_at INTEGER NOT NULL,
notes TEXT,
snapshot TEXT, -- JSON
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
FOREIGN KEY (saved_job_id) REFERENCES saved_jobs(id) ON DELETE SET NULL,
FOREIGN KEY (draft_id) REFERENCES email_drafts(id) ON DELETE SET NULL,
FOREIGN KEY (job_id) REFERENCES corpus_jobs(id) ON DELETE SET NULL
);Why these are plain FKs rather than composite ones. A composite FK with
ON DELETE SET NULL would null owner_id as well, violating NOT NULL. Mixed cascade
semantics inside a composite key are not safe to reason about, so survival edges use a
plain nullable FK and their ownership is guaranteed by applications.owner_id plus the
write path's single-owner guard. Recorded as limitation L-2.
3.10 email_accounts
CREATE TABLE email_accounts (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
provider TEXT NOT NULL DEFAULT 'gmail' CHECK (provider = 'gmail'),
email_address TEXT NOT NULL,
is_active INTEGER NOT NULL DEFAULT 0 CHECK (is_active IN (0,1)),
token_secret_reference TEXT NOT NULL, -- POINTER: 'better-auth:account:<id>'
scopes TEXT NOT NULL DEFAULT '[]',
sync_cursor TEXT,
last_sync_at INTEGER,
last_sync_status TEXT CHECK (last_sync_status IN ('ok','error')),
last_sync_error TEXT,
created_at INTEGER NOT NULL,
revoked_at INTEGER,
UNIQUE (id, owner_id)
);
CREATE UNIQUE INDEX email_accounts_one_active ON email_accounts(owner_id) WHERE is_active = 1;
CREATE UNIQUE INDEX email_accounts_addr ON email_accounts(owner_id, lower(email_address));token_secret_referenceholds a pointer, never a token. The refresh token lives only inauth_account. This is the invariant the send path depends on and spike S1 must not break.email_sync_stateis absorbed, removing a table and a 1:1 join.
3.11 outreach_targets, outreach_contacts
CREATE TABLE outreach_targets (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
label TEXT NOT NULL,
website TEXT,
role_preset TEXT CHECK (role_preset IN ('ceo','founder','cto','hr',
'manager','sales','marketing')),
custom_role TEXT,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id)
);
CREATE TABLE outreach_contacts (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
target_id TEXT,
full_name TEXT,
headline TEXT,
bio TEXT,
email TEXT NOT NULL,
email_verified INTEGER NOT NULL DEFAULT 0 CHECK (email_verified IN (0,1)),
source_url TEXT,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
FOREIGN KEY (target_id, owner_id) REFERENCES outreach_targets(id, owner_id)
ON DELETE CASCADE
);
CREATE UNIQUE INDEX outreach_contacts_email ON outreach_contacts(owner_id, lower(email));Leads are deduped by email per owner, exactly as importLeadsAs does today.
3.12 outreach_fetched_pages, discovery_runs
CREATE TABLE outreach_fetched_pages (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
target_id TEXT NOT NULL,
url TEXT NOT NULL,
http_status INTEGER,
fetched_at INTEGER NOT NULL,
content_blob_key TEXT, -- R2 key; bodies are not in D1
UNIQUE (id, owner_id),
UNIQUE (target_id, url),
FOREIGN KEY (target_id, owner_id) REFERENCES outreach_targets(id, owner_id)
ON DELETE CASCADE
);
CREATE TABLE discovery_runs (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
target_id TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued','running','complete','failed','held')),
leads_found INTEGER NOT NULL DEFAULT 0,
pages_fetched INTEGER NOT NULL DEFAULT 0,
held_reason TEXT,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
FOREIGN KEY (target_id, owner_id) REFERENCES outreach_targets(id, owner_id)
ON DELETE CASCADE
);Caps preserved: 20 targets × 5 pages per run; ≤50 leads per run (default 20).
3.13 email_drafts and the state graph
The complete graph — revision 1 listed states with no transitions and made approved
unreachable:
discarded (terminal) ◄── from draft | approved
draft ──approve──► approved ──claim+charge──► sending
├──► sent (terminal)
├──► sent_unrecorded (terminal)
├──► failed (terminal; cap refunded)
└──► unknown ──resolve──► sent | failedqueued is removed: it belonged to the retired Python queue that had no consumer.
CREATE TABLE email_drafts (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
contact_id TEXT NOT NULL,
email_account_id TEXT NOT NULL,
subject TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'draft'
CHECK (status IN ('draft','approved','sending','sent',
'sent_unrecorded','unknown','failed','discarded')),
send_started_at INTEGER,
send_attempt INTEGER NOT NULL DEFAULT 0,
provider_message_id TEXT,
outcome_reason TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
CHECK (status <> 'sending' OR send_started_at IS NOT NULL),
FOREIGN KEY (contact_id, owner_id) REFERENCES outreach_contacts(id, owner_id)
ON DELETE CASCADE,
FOREIGN KEY (email_account_id, owner_id) REFERENCES email_accounts(id, owner_id)
ON DELETE CASCADE
);
CREATE INDEX email_drafts_stuck ON email_drafts(send_started_at) WHERE status = 'sending';
CREATE INDEX email_drafts_unknown ON email_drafts(owner_id) WHERE status = 'unknown';Only the sending ⇒ send_started_at edge is a CHECK. The rest is enforced by a single
guarded transition function that every writer must call, plus a test that attempts each
illegal edge and expects refusal (L-3). sending is not terminal: a reconciler moves
any sending older than 5 minutes to unknown, because that is precisely what unknown
means.
3.14 email_draft_attachments — the array becomes a table
CREATE TABLE email_draft_attachments (
draft_id TEXT NOT NULL,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
blob_id TEXT NOT NULL,
position INTEGER NOT NULL CHECK (position >= 0),
created_at INTEGER NOT NULL,
PRIMARY KEY (draft_id, position),
UNIQUE (draft_id, blob_id),
FOREIGN KEY (draft_id, owner_id) REFERENCES email_drafts(id, owner_id) ON DELETE CASCADE,
FOREIGN KEY (blob_id, owner_id) REFERENCES blobs(id, owner_id) ON DELETE RESTRICT
);An array of ids can never be a foreign key — in Postgres or in SQLite. This table delivers
four things the array could not: draft ownership, blob ownership, attachment order, and
duplicate prevention. RESTRICT on the blob means an attached object cannot vanish.
3.15 email_events, email_classifications
CREATE TABLE email_events (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
email_account_id TEXT NOT NULL,
draft_id TEXT,
provider_message_id TEXT,
event_type TEXT NOT NULL CHECK (event_type IN ('outbound','inbound','bounce','reply')),
occurred_at INTEGER NOT NULL,
payload TEXT, -- JSON
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
FOREIGN KEY (email_account_id, owner_id) REFERENCES email_accounts(id, owner_id)
ON DELETE CASCADE
);
CREATE UNIQUE INDEX email_events_dedupe
ON email_events(email_account_id, provider_message_id, event_type)
WHERE provider_message_id IS NOT NULL;
CREATE TABLE email_classifications (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
email_event_id TEXT NOT NULL,
category TEXT NOT NULL CHECK (category IN ('interested','not_interested','question',
'out_of_office','unsubscribe','other')),
confidence REAL,
decided_by TEXT NOT NULL CHECK (decided_by IN ('model','keyword')),
model TEXT,
created_at INTEGER NOT NULL,
UNIQUE (email_event_id),
FOREIGN KEY (email_event_id, owner_id) REFERENCES email_events(id, owner_id)
ON DELETE CASCADE
);The event uniqueness index is partial, because a sent_unrecorded/unknown outcome has
no provider message id. A non-partial unique index would be wrong either way: SQLite, like
Postgres, treats NULLs as distinct, so it would permit unlimited duplicates while looking
like a guarantee.
decided_by records whether the model or the keyword rule classified — so a model
regression is visible rather than invisible.
3.16 notifications, exports, company_notes
CREATE TABLE notifications (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('reply','system','cap')),
title TEXT NOT NULL,
body TEXT,
link TEXT,
read_at INTEGER,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id)
);
CREATE TABLE exports (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('jobs','applications','outreach')),
blob_id TEXT,
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued','ready','failed','expired')),
expires_at INTEGER,
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id)
);
CREATE TABLE company_notes (
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
company_id TEXT NOT NULL,
owner_notes TEXT,
enriched TEXT,
updated_at INTEGER NOT NULL,
PRIMARY KEY (owner_id, company_id),
FOREIGN KEY (company_id) REFERENCES corpus_companies(id) ON DELETE CASCADE
);company_notes carries ownership in its primary key — an inverted composite: a user
cannot have two note rows for one company and cannot attribute a note to someone else,
because owner_id is part of the key.
3.17 outreach_suppressions
Cold outreach at 50/day from the owner's own Gmail needs a record of "this person asked not
to be contacted". The current schema has none, so the reply classifier can detect
unsubscribe and the next discovery run re-imports and re-mails the address. That is a
compliance problem (CAN-SPAM §7704(a)(4)) and a correctness problem.
CREATE TABLE outreach_suppressions (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
email TEXT NOT NULL,
contact_id TEXT,
reason TEXT NOT NULL CHECK (reason IN ('unsubscribe','bounce','manual','complaint')),
created_at INTEGER NOT NULL,
UNIQUE (id, owner_id),
-- DM-25: single column; the trigger below enforces the owner.
FOREIGN KEY (contact_id) REFERENCES outreach_contacts(id) ON DELETE SET NULL
);
CREATE TRIGGER outreach_suppressions_contact_owner_ins
BEFORE INSERT ON outreach_suppressions
WHEN NEW.contact_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM outreach_contacts
WHERE id = NEW.contact_id AND owner_id = NEW.owner_id)
BEGIN SELECT RAISE(ABORT, 'contact does not belong to this owner'); END;
CREATE UNIQUE INDEX outreach_suppressions_email
ON outreach_suppressions(owner_id, lower(email));Three mandatory write points, enforced by one assertNotSuppressed(owner, email) call:
classification unsubscribe, an inbound bounce, and the send path — checked in the same
batch as the cap charge, so it cannot be raced. importLeadsAs skips suppressed addresses.
3.18 blobs — an upload lifecycle, not just a row
CREATE TABLE blobs (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
r2_key TEXT NOT NULL, -- u/<owner_id>/<purpose>/<id>; never reused
purpose TEXT NOT NULL CHECK (purpose IN ('resume','resume-text','avatar',
'page','export','attachment')),
content_type TEXT NOT NULL,
bytes INTEGER NOT NULL CHECK (bytes > 0),
sha256 TEXT,
state TEXT NOT NULL DEFAULT 'pending'
CHECK (state IN ('pending','ready','missing','deleted')),
created_at INTEGER NOT NULL,
verified_at INTEGER,
UNIQUE (id, owner_id)
);
CREATE UNIQUE INDEX blobs_key ON blobs(r2_key);
CREATE INDEX blobs_erasure ON blobs(owner_id) WHERE state <> 'deleted';state is what makes verification possible: pending = intent, object may or may not
exist; ready = a HEAD confirmed size and type; missing = the HEAD found nothing and the
row is a lie the UI must not repeat; deleted = object gone, tombstone kept for audit.
ops_upload_intents (§5.10) records the presigned upload so an object can never appear with
no metadata.
4. Corpus tables (5)
No owner_id, no cascade from users. Read through withCorpus (replicas allowed); written
by the scraper through the API.
4.1 corpus_jobs and canonical identity
UNIQUE (canonical_url) is not canonical job identity — it only prevents the same URL
twice. Two boards list the same role at different URLs; one employer mirrors a posting on
three aggregators. The constraint that looks like dedupe and is not is the most expensive
kind, because it stops people looking.
CREATE TABLE corpus_jobs (
id TEXT PRIMARY KEY,
canonical_url TEXT NOT NULL,
title TEXT NOT NULL,
company_id TEXT,
company_name TEXT,
location TEXT,
remote INTEGER NOT NULL DEFAULT 0 CHECK (remote IN (0,1)),
employment_type TEXT,
description TEXT,
salary TEXT, -- JSON
posted_at INTEGER,
fingerprint TEXT NOT NULL, -- sha256(company||normalized title||location)
merged_into_id TEXT,
first_seen_at INTEGER NOT NULL,
last_seen_at INTEGER NOT NULL,
UNIQUE (canonical_url),
CHECK (merged_into_id IS NULL OR merged_into_id <> id),
FOREIGN KEY (company_id) REFERENCES corpus_companies(id) ON DELETE SET NULL,
FOREIGN KEY (merged_into_id) REFERENCES corpus_jobs(id) ON DELETE SET NULL
);
CREATE INDEX corpus_jobs_fingerprint ON corpus_jobs(fingerprint) WHERE merged_into_id IS NULL;
CREATE INDEX corpus_jobs_live ON corpus_jobs(last_seen_at DESC) WHERE merged_into_id IS NULL;| Mechanism | Guarantees | Does not |
|---|---|---|
UNIQUE (canonical_url) | No identical URL twice | Dedupe across sources |
fingerprint index | Same role on two boards are findable as candidates | Prove they are the same |
merged_into_id | A merge is recorded and reversible | Perform the merge |
Dedupe is a merge procedure, not a constraint. Find fingerprint candidates → decide →
set merged_into_id on the loser and move its corpus_job_sources rows to the winner →
readers filter merged_into_id IS NULL. Stated as a procedure because expressing it as a
constraint would be a lie.
description and the 2 MB row limit: a job description is 2–10 KB, so it stays in-row.
If a real corpus is ever found to exceed that, description moves to R2 — that is open
question D1, gated on a measurement (R3).
4.2 corpus_sources, corpus_job_sources — provenance
CREATE TABLE corpus_sources (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
base_url TEXT,
kind TEXT NOT NULL CHECK (kind IN ('api','html','feed')),
created_at INTEGER NOT NULL,
UNIQUE (name)
);
CREATE TABLE corpus_job_sources (
job_id TEXT NOT NULL REFERENCES corpus_jobs(id) ON DELETE CASCADE,
source_id TEXT NOT NULL REFERENCES corpus_sources(id) ON DELETE CASCADE,
source_job_id TEXT NOT NULL,
url TEXT NOT NULL,
first_seen_at INTEGER NOT NULL,
last_seen_at INTEGER NOT NULL,
fetch_count INTEGER NOT NULL DEFAULT 1,
PRIMARY KEY (job_id, source_id, source_job_id),
UNIQUE (source_id, source_job_id)
);Revision 1 gave corpus_jobs a single source_id, which says a posting came from one
board. It did not. UNIQUE (source_id, source_job_id) is also what makes scraper ingest
idempotent: replaying a batch cannot create a second observation.
4.3 corpus_companies, corpus_yc_companies
CREATE TABLE corpus_companies (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
domain TEXT,
created_at INTEGER NOT NULL
);
CREATE UNIQUE INDEX corpus_companies_domain ON corpus_companies(lower(domain))
WHERE domain IS NOT NULL;
CREATE TABLE corpus_yc_companies (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
batch TEXT,
website TEXT,
one_liner TEXT,
updated_at INTEGER NOT NULL,
UNIQUE (name, batch)
);Company identity is shared; everything a user authored about a company lives in
company_notes. The ycIndexShards shard dimension is dropped — it existed to keep Convex
documents small, and a row per company is the natural shape.
5. Operational tables (13)
5.1 ops_worker_tasks — the lease
Revision 1's claim SQL referenced a column named queue while the table declared
queue_name, and declared a delayed status with no column that could make a delayed task
claimable — a permanently stuck row in the table that exists to prevent stuck rows.
CREATE TABLE ops_worker_tasks (
id TEXT PRIMARY KEY,
owner_id TEXT REFERENCES auth_user(id) ON DELETE CASCADE, -- NULL = global
queue_name TEXT NOT NULL CHECK (queue_name IN ('scrape','discover','ai','export')),
task_type TEXT NOT NULL,
search_id TEXT, -- typed column, NEVER a payload key
priority INTEGER NOT NULL DEFAULT 100,
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued','claimed','completed','failed','cancelled')),
attempt INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 3,
available_at INTEGER NOT NULL,
payload TEXT NOT NULL DEFAULT '{}',
result TEXT,
last_error TEXT,
lease_id TEXT,
leased_by TEXT,
lease_expires_at INTEGER,
heartbeat_at INTEGER,
created_at INTEGER NOT NULL,
completed_at INTEGER,
CHECK (status <> 'claimed'
OR (lease_id IS NOT NULL AND lease_expires_at IS NOT NULL)),
FOREIGN KEY (search_id, owner_id) REFERENCES searches(id, owner_id) ON DELETE CASCADE
);
CREATE INDEX ops_worker_tasks_claim ON ops_worker_tasks(queue_name, status, available_at, priority);status='delayed' is gone: delayed work is status='queued' AND available_at > now().
One concept instead of two that disagree.
Claim — one statement, no locks needed because D1 serialises writes:
UPDATE ops_worker_tasks
SET status='claimed', lease_id=?1, leased_by=?2,
lease_expires_at=?3, heartbeat_at=?3, attempt=attempt+1
WHERE id = (SELECT id FROM ops_worker_tasks
WHERE queue_name=?4 AND status='queued' AND available_at <= ?3
ORDER BY priority, created_at LIMIT 1)
AND status='queued'
RETURNING *;Zero rows = another worker won. No read-then-write, no lock, no retry loop.
search_id is structural, not validated. The current backend once accepted
search_id from the request body, letting a token holder write results into another
user's search (V-04). Here the task carries a typed, owner-checked search_id; the ingest
reads it from the row it fenced, and the request body has no field for it. There is nothing
to validate because there is nothing to accept.
Lifecycle, every transition guarded:
| Phase | Statement | Guarantee |
|---|---|---|
| Heartbeat | UPDATE … SET lease_expires_at=? WHERE id=? AND lease_id=? AND status='claimed' AND lease_expires_at > ? | 0 rows → lease gone → discard the batch, write nothing |
| Ingest | bounded ≤200 rows / ≤900 KB, ON CONFLICT DO NOTHING on both natural keys | Retried batch is a no-op |
| Completion | UPDATE … SET status='completed' WHERE id=? AND lease_id=? AND status='claimed' AND lease_expires_at > ? — after the idempotent ingest | An expired lease cannot write even before reclaim |
| Reaper | claimed + expired beyond a 2-minute grace → queued, available_at = now + attempt minutes | Progress or release, never neither |
| Max attempts | attempt >= max_attempts → failed, fail closed | Preserves today's 3-strikes behaviour |
| Cancellation | cancelled is terminal and excluded by the claim predicate | A cancelled task cannot be claimed by a racing worker |
Completion is ordered after the effect (§1 rule 4). If the ingest commits and the completion fails, the reaper re-queues and the retry re-ingests as a no-op — no work lost, no duplicate rows. The reverse order would mark a task done whose rows never landed.
5.2 ops_scraper_executions, ops_ai_runs
CREATE TABLE ops_scraper_executions (
id TEXT PRIMARY KEY,
task_id TEXT REFERENCES ops_worker_tasks(id) ON DELETE SET NULL,
source_id TEXT REFERENCES corpus_sources(id) ON DELETE SET NULL,
started_at INTEGER NOT NULL,
finished_at INTEGER,
status TEXT NOT NULL CHECK (status IN ('ok','partial','failed','held')),
fetched INTEGER NOT NULL DEFAULT 0,
inserted INTEGER NOT NULL DEFAULT 0,
held_reason TEXT,
error_class TEXT
);
CREATE TABLE ops_ai_runs (
id TEXT PRIMARY KEY,
owner_id TEXT REFERENCES auth_user(id) ON DELETE CASCADE,
purpose TEXT NOT NULL CHECK (purpose IN ('profile','dossier','rank','planner',
'drafter','classify','assistant','expand')),
provider TEXT NOT NULL,
model TEXT NOT NULL,
prompt_tokens INTEGER,
output_tokens INTEGER,
latency_ms INTEGER,
status TEXT NOT NULL CHECK (status IN ('ok','error','rate_limited','timeout')),
error_class TEXT,
created_at INTEGER NOT NULL
);Neither stores prompt or completion bodies. error_class is a category, never a provider
message — provider messages can echo user content into a table shaped like a log.
5.3 Caps: the guarded update, and why the old form was wrong
Revision 1 proposed:
INSERT INTO cap_ledger (...)
SELECT ... WHERE (SELECT count(*) FROM cap_ledger WHERE ...) < 4;and called it race-free. It is not: the subquery reads a snapshot, so two writers can both see "4 of 5". On D1 the risk shape changes — writes serialise, so the interleaving is much narrower — but a read-then-write is still a read-then-write, and the design must not depend on the writer being single. The guard belongs inside the write.
CREATE TABLE ops_cap_quota (
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
day TEXT NOT NULL, -- 'YYYY-MM-DD', UTC
kind TEXT NOT NULL CHECK (kind IN ('email_send','apply')),
used INTEGER NOT NULL DEFAULT 0,
limit_value INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (owner_id, day, kind),
CHECK (used >= 0),
CHECK (used <= limit_value) -- database backstop
);
CREATE TABLE ops_cap_ledger (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL,
day TEXT NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('email_send','apply')),
operation_id TEXT NOT NULL, -- draft_id / application_id
op_key TEXT NOT NULL, -- 'email_send:<draft_id>' — the idempotency key
charged_at INTEGER NOT NULL,
released_at INTEGER,
release_nonce TEXT, -- which attempt released the slot; evidence, never the guard
release_reason TEXT CHECK (release_reason IN ('send_failed','cancelled','manual')),
UNIQUE (owner_id, op_key),
CHECK ((released_at IS NULL) = (release_reason IS NULL)),
FOREIGN KEY (owner_id, day, kind) REFERENCES ops_cap_quota(owner_id, day, kind)
ON DELETE CASCADE
);Reserve — one batch(), atomic, with both guards inside the statements:
-- statement 1: seed the quota row (no-op if it exists)
INSERT INTO ops_cap_quota (owner_id, day, kind, used, limit_value, updated_at)
VALUES (?1, ?2, ?3, 0, ?4, ?5)
ON CONFLICT (owner_id, day, kind) DO NOTHING;
-- statement 2: the charge, guarded by BOTH the cap and the idempotency key
UPDATE ops_cap_quota
SET used = used + 1, updated_at = ?5
WHERE owner_id = ?1 AND day = ?2 AND kind = ?3
AND used < limit_value
AND NOT EXISTS (SELECT 1 FROM ops_cap_ledger
WHERE owner_id = ?1 AND op_key = ?6)
RETURNING used, limit_value;
-- statement 3: record the operation ONLY if statement 2 matched.
-- DM-23: every statement in a batch() runs, so the "only reached if" comment was
-- false. changes() returns statement 2's row count on the same connection.
INSERT INTO ops_cap_ledger (id, owner_id, day, kind, operation_id, op_key, charged_at)
SELECT ?7, ?1, ?2, ?3, ?8, ?6, ?5
WHERE changes() = 1;Three properties, each provable rather than asserted:
| Property | Why |
|---|---|
| Never exceeds the cap | used < limit_value is evaluated inside the UPDATE, on the row being written; plus CHECK (used <= limit_value) refuses a bug outright |
| Never charges the same operation twice | NOT EXISTS (…) op_key = ? in the same statement as the increment, plus UNIQUE (owner_id, op_key) |
| Batch is all-or-nothing | batch() is a SQL transaction; if statement 3 violates the unique key, statements 1–2 roll back too — so a double-charge cannot survive a failed ledger write |
| No phantom charge (S2/Q9) | Without WHERE changes() = 1, a refusal at the cap still inserted a ledger row: 45 of 45 refused reservations left one. Those rows are refundable, and refunding them lowered used — 8 sends on a 5/day cap (Q9b). The guard is what makes a refusal leave no trace |
Return behaviour: statement 2 returns zero rows in two distinct cases — cap reached, or
already charged. Because the batch just committed and no partial state exists, a follow-up
read distinguishes them and the API answers with the right code (CAP_REACHED vs an
idempotent success). The refusal charges nothing, satisfying "neither refusal charges a cap
slot".
Refund — also guarded, also idempotent:
UPDATE ops_cap_ledger
SET released_at = ?5, release_nonce = ?6, release_reason = 'send_failed'
WHERE owner_id = ?1 AND op_key = ?2 AND released_at IS NULL;
-- DM-24: guard on the release statement's own row count, not on released_at.
UPDATE ops_cap_quota
SET used = used - 1, updated_at = ?5
WHERE owner_id = ?1 AND day = ?3 AND kind = ?4 AND used > 0
AND changes() = 1;Why not EXISTS (… released_at = ?5) (S2/Q11/Q12). released_at stays set forever, so a
replay — the same timestamp, which is exactly what an idempotent retry sends — satisfies the
condition again. Starting from used = 2, eight concurrent duplicate refunds produced two
decrements in both the released_at and the release_nonce form, and exactly one in the
changes() form. Sequential replay from used = 1 had appeared to pass only because the
used > 0 floor absorbed the second decrement; the floor is not a guard.
release_nonce is still written: it is useful evidence of which attempt released the slot,
and it is not used as the guard.
Day boundary: day is the UTC calendar date. The cap resets at 00:00 UTC; a user in
UTC−8 sees it reset at 16:00 local. Documented behaviour, not an accident. Changing the
zone can over-grant on the boundary day — over-grant, never over-charge (L-4).
Adversarial tests (S2):
| # | Test | Expected |
|---|---|---|
| Q1 | 50 concurrent distinct ops, cap 5 | exactly 5 succeed, used = 5 |
| Q2 | Same op_key 10× concurrently | 1 ledger row, used moves by 1 |
| Q3 | Charge → release → charge with a new key | succeeds |
| Q4 | Release twice, concurrently | decremented once |
| Q5 | Charge either side of 00:00 UTC | two day rows, independent caps |
| Q6 | Lower limit_value below used | rejected by the guard |
| Q7 | Q1 with 200 attempts and injected latency | never 6 |
| Q8 | Statement 3 forced to conflict after statement 2 succeeded | whole batch rolls back; used unchanged |
Q8 is the one that proves batch() atomicity rather than assuming it.
5.4 ops_rate_windows — AI budget, same discipline
CREATE TABLE ops_rate_windows (
scope TEXT NOT NULL CHECK (scope IN ('global','user')),
owner_id TEXT,
window_kind TEXT NOT NULL CHECK (window_kind IN ('rpm','tpm')),
window_start INTEGER NOT NULL, -- truncated to the minute
used INTEGER NOT NULL DEFAULT 0,
limit_value INTEGER NOT NULL,
PRIMARY KEY (scope, owner_id, window_kind, window_start),
CHECK ((scope = 'global') = (owner_id IS NULL))
);Same guarded increment, same reason: "count the rows then call the provider" produces a provider 429 where a clean refusal belonged. Defaults preserved (30 rpm / 15k tpm global, 6 rpm / 6k tpm per user).
5.5 ops_audit_events
CREATE TABLE ops_audit_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
occurred_at INTEGER NOT NULL,
actor_kind TEXT NOT NULL CHECK (actor_kind IN ('user','worker','system','operator')),
owner_id TEXT, -- nullable: pseudonymised on erasure
action TEXT NOT NULL, -- stable verb, e.g. 'email.send.attempted'
subject_type TEXT,
subject_id TEXT,
outcome TEXT NOT NULL CHECK (outcome IN ('ok','refused','error','uncertain')),
detail TEXT, -- identifiers and enums only, never bodies
request_id TEXT
);
CREATE INDEX ops_audit_owner ON ops_audit_events(owner_id, occurred_at DESC);Erasure versus an append-only log is a genuine contradiction. Deleting the row destroys
evidence that a send or an erasure happened; keeping owner_id leaves the erasure
incomplete. Resolution: pseudonymise. owner_id := NULL, detail rewritten to
{"pseudonymised":true,"erasure_job":"…"}. Action, outcome and time survive; the subject
link does not. owner_id is deliberately not a foreign key — a cascade would delete the
evidence. This is the one table with no FK to auth_user, and the reason is written here so
it does not read as an oversight.
5.6 ops_outbox — publication is a lease
CREATE TABLE ops_outbox (
id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
aggregate_type TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
owner_id TEXT,
payload TEXT NOT NULL DEFAULT '{}', -- ids and enums ONLY
publish_state TEXT NOT NULL DEFAULT 'pending'
CHECK (publish_state IN ('pending','claimed','published','parked')),
publish_claim_id TEXT,
publish_claimed_at INTEGER,
publish_attempts INTEGER NOT NULL DEFAULT 0,
available_at INTEGER NOT NULL,
published_at INTEGER,
last_error_class TEXT,
created_at INTEGER NOT NULL,
CHECK (publish_state <> 'claimed'
OR (publish_claim_id IS NOT NULL AND publish_claimed_at IS NOT NULL))
);
CREATE INDEX ops_outbox_due ON ops_outbox(available_at)
WHERE publish_state IN ('pending','claimed');Claim commits before the Queue publish — no transaction or lease is held across a network call:
UPDATE ops_outbox
SET publish_state='claimed', publish_claim_id=?1, publish_claimed_at=?2,
publish_attempts=publish_attempts+1
WHERE id IN (SELECT id FROM ops_outbox
WHERE publish_state='pending' AND available_at <= ?2
ORDER BY created_at LIMIT 50)
AND publish_state='pending'
RETURNING *;Then sendBatch() outside any transaction, then a confirm guarded by publish_claim_id, and
a 5-minute reaper that returns orphaned claims to pending. A crash between publish and
confirm re-publishes — at-least-once, deliberately, which is why the consumer is idempotent
by state.
5.7 ops_consumer_deliveries — states, not a flag
Revision 1's processed_events inserted event_id first, then did the work, then
acked. A crash after the insert made redelivery conclude "already processed" and ack —
losing the work, with the dedupe table as the instrument of the loss.
CREATE TABLE ops_consumer_deliveries (
event_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
source_queue TEXT NOT NULL CHECK (source_queue IN ('outreach','jobs','io')),
state TEXT NOT NULL DEFAULT 'received'
CHECK (state IN ('received','processing','completed',
'failed','dead','parked')),
attempt INTEGER NOT NULL DEFAULT 0,
lease_id TEXT,
lease_expires_at INTEGER,
received_at INTEGER NOT NULL,
completed_at INTEGER,
error_class TEXT,
CHECK (state <> 'processing'
OR (lease_id IS NOT NULL AND lease_expires_at IS NOT NULL))
);
CREATE INDEX ops_deliveries_stuck ON ops_consumer_deliveries(lease_expires_at)
WHERE state = 'processing';Claim:
INSERT INTO ops_consumer_deliveries
(event_id, event_type, source_queue, state, attempt, lease_id, lease_expires_at, received_at)
VALUES (?1, ?2, ?3, 'processing', 1, ?4, ?5, ?6)
ON CONFLICT (event_id) DO UPDATE
SET state='processing', attempt=attempt+1, lease_id=?4, lease_expires_at=?5
WHERE state IN ('received','failed') -- DM-26: 'parked' is NOT claimable
OR (state = 'processing' AND lease_expires_at < ?6)
RETURNING state;DM-26 (S2/Q17). The first version listed parked among the claimable states, while the
same section defined parked as "operator holds it". A parked delivery was claimed
(claimed: 1, state → processing), so an operator's hold lasted exactly until the next
redelivery. The predicate above was verified to leave it parked.
| Result | Meaning | Action |
|---|---|---|
| Row returned | We hold the lease | Do the work |
No row, state completed | Already done | Ack — the only short-circuit |
No row, processing, lease live | Someone else is working | Throw (do not ack) |
Ordering: effect first (idempotent), then
UPDATE … SET state='completed' WHERE event_id=? AND lease_id=? AND state='processing'.
A crash between them leaves the effect applied and unrecorded, and the redelivery re-applies
it as a no-op before completing. That is the §1 rule 4, and it is why D1's lack of
interactive transactions does not lose work here.
Failure: state='failed' then throw (the claim predicate accepts failed). attempt > 5
→ dead, and a cron writes an incident. parked = operator holds it.
5.8 ops_dlq_incidents
CREATE TABLE ops_dlq_incidents (
id TEXT PRIMARY KEY,
source_queue TEXT NOT NULL,
event_id TEXT,
event_type TEXT,
outbox_id TEXT REFERENCES ops_outbox(id) ON DELETE SET NULL,
attempts INTEGER NOT NULL DEFAULT 0,
first_failure_at INTEGER NOT NULL,
last_failure_at INTEGER NOT NULL,
error_class TEXT,
payload_keys TEXT NOT NULL DEFAULT '[]', -- field NAMES, never values
status TEXT NOT NULL DEFAULT 'open'
CHECK (status IN ('open','replayed','resolved','ignored')),
resolution_note TEXT
);No queue body is ever stored here. A payload can contain a draft's subject and body, a
contact's address, or a reply's full text; an incident table is the last place to duplicate
it. Identifiers plus field names are enough to replay, because ops_outbox still holds the
work.
Two independent writers — the recovery path:
- The DLQ consumer writes an incident; if the write fails it does not ack, so the
message is redelivered (
max_retriesis a normal budget, never0). - The outbox reconciler (cron) writes incidents straight from
ops_outboxwhenpublish_attempts > 5, with no queue involved.
Writer 2 is what makes the system recoverable when the queue and the DLQ are unavailable, because it reads the database, which is where the work actually is.
Retention bounds discovery: Queues Free retention is 24 h and not configurable; Paid is 4 days by default, up to 14. An incident only discoverable by reading the DLQ is invisible after 24 h on Free — one of the reasons Paid is recommended, and the reason the reconciler exists.
5.9 ops_upload_intents — the missing lifecycle
CREATE TABLE ops_upload_intents (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL REFERENCES auth_user(id) ON DELETE CASCADE,
r2_key TEXT NOT NULL,
purpose TEXT NOT NULL,
declared_bytes INTEGER NOT NULL,
content_type TEXT NOT NULL,
state TEXT NOT NULL DEFAULT 'pending'
CHECK (state IN ('pending','finalized','expired','abandoned')),
expires_at INTEGER NOT NULL, -- now + 15 minutes
blob_id TEXT REFERENCES blobs(id) ON DELETE SET NULL,
created_at INTEGER NOT NULL,
UNIQUE (r2_key)
);| Event | Behaviour |
|---|---|
| Intent issued | Row pending; presigned URL TTL ≤ expires_at |
| Uploaded + finalised | HEAD verifies size/type, then one batch: blobs → ready, intent → finalized |
| Upload ok, finalise failed | Intent expires; cleanup deletes an object with no blobs row |
| Metadata exists, object gone | Reconciler HEADs and sets blobs.state='missing'; download returns 410 |
| Upload in flight during erasure | Erasure fences first (refuses new intents), waits for expiry, then sweeps |
| Partial delete | The pass repeats; completion means a listing pass returned zero objects |
A presigned URL is not single-use, and the design says so rather than implying it. Keys contain a fresh UUID, so a stale URL cannot serve a different later object.
5.10 ops_erasure_jobs
CREATE TABLE ops_erasure_jobs (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL, -- deliberately NOT an FK: must outlive the user
requested_at INTEGER NOT NULL,
state TEXT NOT NULL DEFAULT 'fencing'
CHECK (state IN ('fencing','draining','listing','deleting',
'verifying','complete','failed')),
r2_prefix TEXT NOT NULL, -- u/<owner_id>/
objects_deleted INTEGER NOT NULL DEFAULT 0,
passes INTEGER NOT NULL DEFAULT 0,
last_error_class TEXT,
completed_at INTEGER,
evidence TEXT -- counts and pass numbers, never content
);5.11 ops_table_policy — a registry, not a SQL executor
Revision 1 described this table as driving erasure dynamically. Metadata cannot express a
cascade, cannot know that ops_audit_events must be pseudonymised rather than deleted, and
cannot know that R2 must be swept. A dynamic executor built on it is either incomplete or an
arbitrary-SQL surface.
CREATE TABLE ops_table_policy (
table_name TEXT PRIMARY KEY,
retention_days INTEGER, -- NULL = keep
strategy TEXT NOT NULL
CHECK (strategy IN ('cascade','delete','pseudonymise','retain','r2-sweep')),
external_cleanup TEXT,
notes TEXT
);Its value is that it can be checked, not executed: a test reads
sqlite_master/PRAGMA table_info, finds every table with an owner_id column, and fails
the build if one has no policy row. The enumeration filters name NOT LIKE '_cf_%':
remote D1 refuses PRAGMA on its own internal tables (DM-28) while still listing them.
strategy selects one of five hand-written routines, each with its own test.
6. Cross-cutting rules
6.1 Deletion by strategy
| Strategy | Tables | Mechanism |
|---|---|---|
cascade | every product table with owner_id → auth_user | ON DELETE CASCADE from auth_user |
cascade | corpus_* | never owner-scoped; untouched by erasure |
pseudonymise | ops_audit_events | owner_id := NULL, detail rewritten |
retain | ops_erasure_jobs, ops_table_policy, ops_dlq_incidents | kept |
r2-sweep | blobs, resumes.text_blob_id, exports.blob_id | prefix listing repeated until empty |
6.2 Erasure sequence (order matters)
- Fence — write
ops_erasure_jobs(state='fencing'); new upload intents and sends are refused by a check in the same batch as their guard. - Drain — void pending upload intents; wait out any live intent's
expires_at(≤15 min) so no in-flight PUT lands after the sweep. - Sweep R2 — list
u/<owner_id>/to exhaustion, delete, repeat until a pass returns zero objects. - Verify — a final listing must be empty; otherwise
state='failed'and retry. Do not proceed to row deletion, because rows are the only map back to the objects. - Pseudonymise audit.
- Delete rows —
DELETE FROM auth_user WHERE id = ?(cascades product rows). - Record —
state='complete'with counts and pass numbers.
Step 3 before step 6 is what makes "row-driven deletion cannot find orphans" moot: the prefix is the source of truth for objects, and it is swept while the rows still exist.
6.3 What this model refuses to do
- No array pretending to be a foreign key.
- No "canonical" claim without a merge procedure.
- No dynamic SQL over policy metadata.
- No
owner_idinferred by a join — every child carries it and is constrained by it. - No counter table without a
CHECKbackstop. - No
queuedemail draft — the queue it described no longer exists. - No duplicated identity columns —
usersis Better Auth's. - No query against an owner-scoped table outside the repository layer.
6.4 Deliberately not carried forward
| Dropped | Why |
|---|---|
users | identity belongs to auth_user |
cachedJobs | a cache is not a table |
outreachCampaigns | one insert, no reader, no route |
proxyProviders / proxyEndpoints / proxyAssignments / browserSessions | AutoApply infrastructure; AutoApply is out of scope |
logLines | logs do not belong in the OLTP database |
7. Open questions
| ID | Question | Why it cannot be answered here | How it closes |
|---|---|---|---|
| D1 | Is corpus_jobs.description in-row or in R2? | The 2 MB row limit makes it a measurement, not a preference | Measure the real description distribution (R3) |
| D2 | Does search_results need an FTS index at cutover? | SQLite FTS5 availability on D1 is unverified | spike S2 probe |
| D3 | Is ops_rate_windows hot enough to need sharding? | Request volume unknown (R4) | measure |
| D4 | Seed corpus_companies from corpus_yc_companies? | Product decision | owner |
| D5 | Partition email_events by month? | Needs observed inbound volume | defer; append-only table |
| D6 | When does corpus split into its own D1 database? | Trigger defined in §D.5 of the system design (4 GB or overload) | monitoring |
8. Table inventory (computed, not counted)
The table below is generated by tools/check_table_inventory.py, which reads the 42
defineTable declarations out of server/convex/schema.ts (read-only) and the 41
CREATE TABLE statements out of this document. Hand arithmetic is what produced revision
1's "36 tables" from 42 declarations; the script is the fix.
python3 tools/check_table_inventory.py # render
python3 tools/check_table_inventory.py --verify # fail the build on drift| Convex table | Outcome | D1 table(s) |
|---|---|---|
users | DROP | — |
profiles | KEEP | profiles |
resumes | KEEP | resumes |
profileDossiers | KEEP | profile_dossiers |
profileSources | KEEP | profile_sources |
aiRateWindows | MERGE | ops_rate_windows |
userPreferences | KEEP | user_preferences |
searches | KEEP | searches |
searchResults | KEEP | search_results |
jobs | MOVE | corpus_jobs |
cachedJobs | DROP | — |
savedJobs | KEEP | saved_jobs |
applications | KEEP | applications |
scraperSources | MOVE | corpus_sources |
scraperExecutions | KEEP | ops_scraper_executions |
workerTasks | MOVE | ops_worker_tasks |
aiRuns | KEEP | ops_ai_runs |
jobMatchResults | MERGE | search_results |
emailAccounts | KEEP | email_accounts |
outreachTargets | KEEP | outreach_targets |
outreachContacts | KEEP | outreach_contacts |
outreachFetchedPages | KEEP | outreach_fetched_pages |
discoveryRuns | KEEP | discovery_runs |
outreachCampaigns | DROP | — |
emailDrafts | KEEP | email_drafts |
emailEvents | KEEP | email_events |
emailClassifications | KEEP | email_classifications |
emailSyncState | MERGE | email_accounts |
uploadClaims | MOVE | blobs |
dailyUsage | SPLIT | ops_cap_quota + ops_cap_ledger |
proxyProviders | DROP | — |
proxyEndpoints | DROP | — |
proxyAssignments | DROP | — |
browserSessions | DROP | — |
notifications | KEEP | notifications |
exports | KEEP | exports |
auditEvents | KEEP | ops_audit_events |
logLines | DROP | — |
companies | SPLIT | corpus_companies + company_notes |
ycIndexShards | KEEP | corpus_yc_companies |
accountErasures | MOVE | ops_erasure_jobs |
rateLimits | MERGE | ops_rate_windows |
Convex declarations: **42** — KEEP 23 · MOVE 5 · MERGE 4 · SPLIT 2 · DROP 8
Tables derived from the schema: **33**
Tables declared new: **8**
product: 23
corpus: 5
ops: 13
**TARGET TOTAL: 41** (net -1 vs Convex)
`CREATE TABLE` statements in the proposal: 418.1 The eight tables with no Convex ancestor
| Table | Why it is new | What breaks without it |
|---|---|---|
email_draft_attachments | the attachment array had no FK | SD-06: a draft can reference a deleted or foreign blob |
outreach_suppressions | "do not contact" had nowhere to live | the next run re-mails an unsubscriber |
corpus_job_sources | one posting, many boards | a job has exactly one source, which is false |
ops_outbox | publication needs a lease | a crash between write and publish loses the event |
ops_consumer_deliveries | "processed" as a flag loses work | a crash between insert and work acks un-done work |
ops_dlq_incidents | dead messages need a durable record | a DLQ message expires after 24 h and vanishes |
ops_upload_intents | presigned uploads need a lifecycle | an aborted upload orphans an object forever |
ops_table_policy | erasure strategy needs to be checkable | a new owner table is silently excluded from erasure |
8.2 Net effect
42 → 41 (−1), despite adding 8 tables. The eight new tables buy correctness; the
count falls because users is deleted (Better Auth owns identity), four AutoApply
infrastructure tables and one log table are dropped, two cache/campaign tables go, and
four pairs merge.
9. Findings register
Every finding from the revision-1 audit, its status, and what closed it. Severity: C = data loss / security, H = correctness under load, M = maintainability.
| ID | Sev | Finding | Status | Closed by |
|---|---|---|---|---|
| DM-01 | C | attachment was an array of ids with no FK | FIXED | §3.14 join table, composite FKs both ends |
| DM-02 | H | one job, one source_id | FIXED | §4.2 corpus_job_sources |
| DM-03 | C | users.email duplicated identity, could drift | FIXED | §3.1 no users; owner_id → auth_user |
| DM-04 | C | daily cap counted then inserted (race) | FIXED | §5.3 guarded UPDATE … WHERE used < limit + CHECK |
| DM-05 | C | outbox published with no lease | FIXED | §5.6 claim-commit → publish → confirm, reaper |
| DM-05b | C | consumer inserted "processed" before working | FIXED | §5.7 state machine, completed is the only short-circuit |
| DM-05c | H | DLQ had no durable record and one writer | FIXED | §5.8, two independent writers |
| DM-06 | C | user↔avatar creation cycle | FIXED | §3.5 user_preferences.avatar_blob_id |
| DM-07 | M | email_sync_state was a 1:1 join | FIXED | merged into email_accounts |
| DM-08 | H | draft states declared, transitions impossible | FIXED | §3.13 explicit graph, queued removed |
| DM-09 | H | provider-id uniqueness absent | FIXED | §3.15 partial unique index |
| DM-10 | M | one companies table mixed public and private | FIXED | §4.3 + §3.16 split |
| DM-11 | H | blob had no state, so no verification | FIXED | §3.18 state + HEAD reconciler |
| DM-11b | H | presigned upload had no lifecycle | FIXED | §5.9 ops_upload_intents |
| DM-12 | C | no suppression list | FIXED | §3.17, three enforced write points |
| DM-13 | H | "canonical_url unique" claimed dedupe | FIXED | §4.1 fingerprint + merge procedure |
| DM-14 | M | row-per-message shard dimension | FIXED | corpus_yc_companies |
| DM-15 | H | offset pagination over a mutable rank | FIXED | §3.7 keyset on (score, job_id) |
| DM-16 | C | audit log vs erasure contradiction | FIXED | §5.5 pseudonymise, no FK to auth_user |
| DM-17 | H | erasure policy described as dynamic SQL | FIXED | §5.11 registry + CI check, 5 named routines |
| DM-18 | M | 36 was hand-counted from 42 | FIXED | §8 generated by script, --verify in CI |
9.1 Findings from the S2 spike (real D1, Q1–Q18)
Evidence: spikes/d1-integrity/results/RESULTS.md and results/raw-*.json. Every FAIL below
carries the corrected statement that passed on the same data.
| ID | Sev | Finding | Status | Closed by |
|---|---|---|---|---|
| DM-23 | C | Statement 3 of the cap batch runs even when statement 2 matched zero rows: 45/45 refusals inserted a phantom ledger row (Q9) | FIXED | WHERE changes() = 1 on the ledger insert |
| DM-23b | C | Phantom rows are refundable, so refusals convert into free slots: 8 sends on a 5/day cap (Q9b) | FIXED | the same guard (0 phantom rows, 0 extra sends) |
| DM-24 | C | Refund guard EXISTS(… released_at = ?) is replayable: 8 concurrent duplicate refunds decremented twice (Q12) | FIXED | changes() = 1 guard on the decrement |
| DM-25 | C | Composite ON DELETE SET NULL nulls owner_id too — orphaning the row when the key is nullable, refusing the parent delete when it is NOT NULL (Q13) | FIXED | plain single-column FK + same-owner triggers, demonstrated |
| DM-26 | H | Consumer claim predicate accepts parked, so a "held" delivery is auto-claimed (Q17) | FIXED | state IN ('received','failed') |
| DM-27 | H | A TEXT PRIMARY KEY is nullable in SQLite unless declared NOT NULL, so several ownership keys were not the constraint they appeared to be | FIXED | NOT NULL written explicitly on every key |
9.1b Final S2 run — acceptance and one remote-only finding
| ID | Sev | Finding | Status |
|---|---|---|---|
| DM-28 | M | Remote D1 refuses PRAGMA table_info on internal _cf_* tables (SQLITE_AUTH) although sqlite_master lists them, so ownership-coverage enumeration must exclude them | FIXED — filter in §1.1 and §5.12; verified by R0 on both targets |
| — | — | The attack matrix has 15 ownership edges (13 composite FKs + 2 pointer edges), not the 17 previously stated; all 15 are rejected, and Q13 covers the third pointer edge's insert trigger | corrected |
9.2 D1 retarget findings
| ID | Sev | What the retarget changed | Residual |
|---|---|---|---|
| DM-19 | C | RLS removed. Ownership isolation is now a code invariant, not a database guarantee | L-D1-1 — a bug inside a repository function can still leak. Mitigated by composite FKs, a single access layer, and a per-table two-owner test. Not eliminable |
| DM-20 | H | No interactive transactions. Logic that was one BEGIN…COMMIT is now guarded statements, batch(), or a compensating step | L-1 — a multi-step flow has a visible intermediate state instead of an invisible one |
| DM-21 | M | No schemas → prefixes; no uuid/now() → application-supplied ids and timestamps | an insert is no longer self-sufficient: the caller must supply the key |
| DM-22 | M | EXCLUDE → partial unique index; arrays → join tables; jsonb → TEXT + json_extract | no partial-index arithmetic, so "exactly one" is "at most one" plus a write rule |
10. Limitations, stated rather than solved
| ID | Limitation | Consequence |
|---|---|---|
| L-D1-1 | No RLS: an owner-scoped read that omits owner_id returns other owners' rows | The largest regression in the retarget; the whole repository layer exists because of it |
| L-1 | No interactive transactions between app-side steps | A crash can leave "effect applied, state not flipped". Recovered by the ordering rule, not by atomicity |
| L-2 | Survival edges (saved_jobs.job_id, applications.job_id/saved_job_id/draft_id) use plain nullable FKs | Their ownership is not structurally guaranteed; it rests on the single-owner write path |
| L-3 | Draft transitions other than sending ⇒ send_started_at are not database-enforced | One guarded transition function plus a test that attempts every illegal edge |
| L-4 | The cap day is UTC | A non-UTC user sees the reset mid-afternoon; a timezone change can over-grant on one boundary day, never over-charge |
| L-5 | 10 GB per database | A size ceiling with a split trigger, not a capacity plan (system design §D.5) |
| L-6 | One writer at a time | A shared write throughput ceiling; no connection pooling can raise it (R4) |
| L-7 | batch() gives atomicity, not isolation between concurrent batches | Two batches can interleave at statement boundaries; every guard is therefore inside a single statement, and a guard that depends on a previous statement's effect must use changes() = 1 |
| L-8 | Pointer edges (user_preferences.avatar_blob_id, searches.resume_id, outreach_suppressions.contact_id) rely on triggers for same-owner enforcement, not on a composite FK | A trigger can be dropped; a composite FK cannot. A test asserts the three triggers exist and fire |
| L-9 | changes() is a per-connection implicit state, and D1 allows it (verified) while blocking sqlite_version() and PRAGMA user_version/compile_options | Relying on it couples the guards to that behaviour; S2 records the observation rather than assuming it |
| L-10 | S2 proved the mechanisms on a preview D1 database (temporary account, 22-table slice, ≤200 in-flight requests), not under production traffic or at production size | The guards are falsified; latency and behaviour at scale are not measured — Phase 12 re-checks on a real deployment |
| L-11 | Pointer-edge ownership lives in triggers, and remote D1 refuses introspection of its own system tables, so the CI test enumerates design tables only | A dropped trigger is caught by the six-trigger assertion, not by a database constraint |
11. What this model asks to be approved for
Nothing is implemented. Approval buys the right to run spikes S1, S2, S6 against this design — the three that test the parts most likely to be wrong:
- S2 tries to break §5.3 (cap), §5.1 (lease), §5.7 (consumer) and §3.0 (composite ownership) under real concurrency on real D1.
- S1 tries to break §3.1 and §3.10 (identity, token pointer) with the real auth library.
- S6 tries to break §3.18 and §5.9 (object lifecycle, verified erasure).
If S2 is red, the cap and lease mechanisms return for redesign — within Cloudflare. If S1 is red, the migration stops. If S6 is red, erasure is not implemented as designed, and A8 says that is not negotiable.