Schema Designed
The SQL for the LLM Extraction service's tables, in the extraction schema. No other service can read them.
-- LLM Extraction service, version 1. Schema: extraction.
-- IDs are UUIDv7 values generated by the service.
-- Checked with `npm run schema:check`: runs on PGlite, and every sample row passes every constraint.
create schema if not exists extraction;
create table extraction.jobs (
id uuid primary key,
owner_id uuid not null,
file_id uuid not null,
schema text not null,
reference text,
status text not null default 'queued',
step text,
attempt smallint not null default 1,
model text not null,
prompt_version text not null,
pages smallint,
fields_total smallint,
fields_flagged smallint,
tokens_in integer,
tokens_out integer,
cost_usd numeric(10,6),
duration_ms integer,
error_code text,
error_message text,
started_by text not null default 'person',
held_by text,
released_at timestamptz,
created_at timestamptz not null default now(),
started_at timestamptz,
finished_at timestamptz,
constraint jobs_schema_check check (schema in ('invoice-v1')),
constraint jobs_reference_check check (length(reference) between 1 and 200),
constraint jobs_started_by_check check (started_by = 'person' or started_by ~ '^service:[a-z][a-z0-9-]*$'),
constraint jobs_held_by_check check (held_by ~ '^service:[a-z][a-z0-9-]*$'),
constraint jobs_released_check check (released_at is null or held_by is not null),
constraint jobs_status_check check (status in ('queued', 'processing', 'extracted', 'failed')),
constraint jobs_step_check
check (step in ('fetching_file', 'reading_text', 'reading_document', 'checking_rules', 'saving')),
constraint jobs_attempt_check check (attempt between 1 and 3),
constraint jobs_model_check check (length(model) between 1 and 100 and length(prompt_version) between 1 and 100),
constraint jobs_error_code_check check (error_code in
('file_unavailable', 'document_unreadable', 'no_text_found', 'model_unavailable', 'output_invalid', 'timed_out')),
constraint jobs_failed_check check (
(status = 'failed') = (error_code is not null)
and (error_code is null) = (error_message is null)
),
constraint jobs_finished_check check ((status in ('extracted', 'failed')) = (finished_at is not null)),
constraint jobs_extracted_check check (
status <> 'extracted'
or (fields_total is not null and fields_flagged between 0 and fields_total
and tokens_in is not null and tokens_out is not null
and cost_usd is not null and duration_ms is not null)
),
constraint jobs_numbers_check check (
(pages is null or pages between 1 and 10)
and coalesce(fields_total, 0) >= 0 and coalesce(tokens_in, 0) >= 0
and coalesce(tokens_out, 0) >= 0 and coalesce(cost_usd, 0) >= 0
and coalesce(duration_ms, 0) >= 0
),
constraint jobs_dates_check check (
(started_at is null or started_at >= created_at)
and (finished_at is null or finished_at >= coalesce(started_at, created_at))
)
);
-- One running job per file and schema: a second request returns the first.
create unique index jobs_active_file_idx on extraction.jobs (file_id, schema)
where status in ('queued', 'processing');
-- A user's jobs; the admin's recent jobs; the sweep of jobs left queued.
create index jobs_owner_id_idx on extraction.jobs (owner_id, created_at desc);
create index jobs_created_at_idx on extraction.jobs (created_at desc);
create index jobs_queued_idx on extraction.jobs (created_at) where status = 'queued';
create table extraction.fields (
id uuid primary key,
job_id uuid not null,
name text not null,
line_index smallint,
value jsonb,
model_confidence numeric(3,2) not null,
confidence numeric(3,2) not null,
source_page smallint,
source_quote text,
flagged boolean not null default false,
flag_reasons text[] not null default '{}',
created_at timestamptz not null default now(),
constraint fields_job_id_fkey foreign key (job_id)
references extraction.jobs (id) on delete cascade,
constraint fields_job_name_line_key unique nulls not distinct (job_id, name, line_index),
constraint fields_name_check check (name in ('vendor_name', 'vendor_address', 'vendor_tax_id', 'invoice_number', 'invoice_date', 'due_date', 'bill_to_name', 'bill_to_address', 'currency', 'subtotal', 'tax_total', 'total', 'payment_terms', 'description', 'quantity', 'unit_price', 'amount')),
constraint fields_line_index_check check (
(name in ('description', 'quantity', 'unit_price', 'amount')) = (line_index is not null)
and (line_index is null or line_index >= 0)
),
constraint fields_confidence_check check (
model_confidence between 0 and 1
and confidence between 0 and 1
and confidence <= model_confidence
),
constraint fields_evidence_check check (
(value is null) = (source_quote is null)
and (source_quote is null) = (source_page is null)
),
constraint fields_quote_check check (length(source_quote) between 1 and 500),
constraint fields_flagged_check check (flagged = (cardinality(flag_reasons) > 0))
);
-- The fields a person must check, for the review queue.
create index fields_flagged_idx on extraction.fields (job_id) where flagged;
-- The text of each page, for the quote check. Deleted with the job.
create table extraction.page_texts (
job_id uuid not null,
page smallint not null,
source text not null,
text text not null,
created_at timestamptz not null default now(),
constraint page_texts_pkey primary key (job_id, page),
constraint page_texts_job_id_fkey foreign key (job_id)
references extraction.jobs (id) on delete cascade,
constraint page_texts_page_check check (page between 1 and 10),
constraint page_texts_source_check check (source in ('text_layer', 'ocr')),
constraint page_texts_text_check check (length(text) <= 100000)
);
create table extraction.inbound_events (
event_id uuid primary key,
type text not null,
created_at timestamptz not null default now(),
constraint inbound_events_type_check check (length(type) between 1 and 100)
);
-- The service's database login reaches only this schema. Fields are deleted only
-- with their owner's account; audit events can be added and read, never changed.
grant usage on schema extraction to extraction_service;
grant select, insert, update on extraction.jobs to extraction_service;
grant select, insert, delete on extraction.fields, extraction.page_texts to extraction_service;
grant select, insert on extraction.inbound_events to extraction_service;
grant select, insert on extraction.audit_events to extraction_service;
Schema level: enforced by the database, whatever the code does
- One running job per file and schema, enforced by a partial unique index.
- A field name appears once per job, and once per line item for line-item fields (nulls not distinct).
- A failed job always has an error code and message; a finished job always has an end time; an extracted job always has its counts, tokens, cost and duration.
- Final confidence can never exceed the model's own; a flagged field always has a reason.
- A value that is present always has its page and quote.
- Extraction's database login can reach only the
extraction schema, and cannot delete jobs.
Constraints and indexes by table
extraction.jobs
jobs_pkey: primary key (id)jobs_schema_check: schema is invoice-v1jobs_status_check, jobs_step_check, jobs_error_code_check: only the listed valuesjobs_started_by_check: started_by is person or like service:<name>jobs_held_by_check: held_by is like service:<name>jobs_released_check: released_at only when held_by is setjobs_attempt_check: attempt between 1 and 3jobs_failed_check: error_code and error_message are set exactly when status is failedjobs_finished_check: finished_at is set exactly when status is extracted or failedjobs_extracted_check: an extracted job has fields_total, fields_flagged, tokens, cost and duration, and fields_flagged ≤ fields_totaljobs_numbers_check: pages 1 to 10; counts, tokens, cost and duration never negativejobs_dates_check: started_at not before created_at; finished_at not before started_atjobs_active_file_idx: unique (file_id, schema) where status in (queued, processing), so the same file is never read twice at oncejobs_owner_id_idx: index on (owner_id, created_at desc), for a user's jobsjobs_created_at_idx: index on (created_at desc), for the admin's recent jobsjobs_queued_idx: partial index on (created_at) where status = 'queued', for the sweep
extraction.fields
fields_pkey: primary key (id)fields_job_id_fkey: foreign key (job_id) references extraction.jobs on delete cascadefields_job_name_line_key: unique (job_id, name, line_index) with nulls not distinct, so a header field cannot appear twice in one jobfields_name_check: name is one of the invoice v1 fieldsfields_line_index_check: line_index is set exactly for line-item fields, and is not negativefields_confidence_check: both confidences between 0 and 1, and confidence ≤ model_confidencefields_evidence_check: a present value has source_page and source_quote; an absent one has neitherfields_quote_check: source_quote 1 to 500 charactersfields_flagged_check: flagged is true exactly when flag_reasons is not emptyfields_flagged_idx: partial index on (job_id) where flagged, for the review queue
extraction.page_texts
page_texts_pkey: primary key (job_id, page)page_texts_job_id_fkey: foreign key to extraction.jobs, delete cascadespage_texts_page_check, page_texts_source_check, page_texts_text_check
extraction.inbound_events
inbound_events_pkey: primary key (event_id)inbound_events_type_check: type is 1 to 100 characters
Sample data
extraction.inbound_events
Common queries
Start a job, or find the running one (`POST /jobs`)
insert into extraction.jobs (id, owner_id, file_id, schema, reference, model, prompt_version)
values ($1, $2, $3, $4, $5, $6, $7)
on conflict (file_id, schema) where status in ('queued', 'processing')
do nothing
returning *;
-- no row returned: a job is already running; read it and answer 200
The fields a person must check (`GET /jobs/{jobId}/fields?flagged=true`)
select f.*
from extraction.fields f
join extraction.jobs j on j.id = f.job_id
where f.job_id = $1 and j.owner_id = $2 and f.flagged
order by f.confidence;
Recent jobs and failure rate (`GET /admin/jobs`)
select id, status, model, prompt_version, pages, tokens_in, tokens_out, cost_usd, duration_ms, error_code
from extraction.jobs
order by created_at desc
limit 100;
Schema on GitHub →