TRAIL Search keeps all of its state in MongoDB, modelled with Beanie documents. The schema is shaped by one question asked of every collection: what must never be true of this data, and what in the database stops it? Application code that promises to check first is not an answer, because two processes can both check and both proceed.
Collections

| Area | Collection | What it holds |
|---|---|---|
| Tenancy | workspaces, users, workspace_members | the tenant, its people and their roles |
| Tenancy | api_keys | a key’s hash, scope, expiry and revocation time |
| Measurement | brands | a brand, its markets and observed engines, with a revision counter |
| Measurement | tracked_prompts, prompt_sets | the questions asked for a brand; the second mirrors the first for older readers |
| Measurement | tracking_schedules | cadence, repeats, the next due time |
| Measurement | run_batches | one run: status, plan, idempotency keys, lease, counts, settlement |
| Measurement | engine_runs | one attempt for one cell: answer text, citations, observation axes |
| Measurement | mentions | an entity named in an answer, with rank and whether it was cited |
| Measurement | sov_snapshots | per-entity rates for one run, with sample and integrity fields |
| Billing | credit_accounts, credit_transactions | the stored balance and the append-only ledger |
| Billing | billing_payments, billing_payment_methods, billing_subscriptions | card payments, the saved card reference, the plan state |
| Billing | billing_daily_runs, billing_free_uses | once-a-day job gates and free allowances |
| Audits | site_audits, audit_reports | a crawl-and-score job and its result |
Every document carries a workspace_id. Routes take it from the session or from the API key and never from the request body, so a caller cannot name someone else’s workspace in a payload.
Tenancy and roles
A workspace id is derived from its owner’s user id, so the owner needs no membership row. Other people join through workspace_members with the role editor or viewer. The active workspace comes from a request header, and a header that names a workspace where the caller has no active seat falls back to the caller’s own workspace instead of failing, so a stale browser tab cannot lock a person out or let them into someone else’s data.
Routes declare the access they need through one of three dependencies.
| Dependency | Roles allowed | Used for |
|---|---|---|
get_workspace_id | owner, editor, viewer | reads |
require_write_workspace_id | owner, editor | anything that changes data or spends credits |
require_owner_workspace_id | owner | card, subscribe, cancel, resume and top-up |
Billing is owner-only at the route, not in the interface. An editor who calls a billing route directly gets a 403 that says the action needs the owner. One test lists every route with the gate it is expected to carry, and a second fails when a route that is not a GET is added without a gate or a written excuse, so a new endpoint cannot ship ungated by accident.
Indexes that enforce a rule
An index in this schema is rarely about speed. Most of them exist so that the database refuses a write the application must never make.
| Index | Type | The rule it enforces |
|---|---|---|
batch_request_key_unique on (workspace_id, idempotency.request_key) | unique, partial: only where the key is a string | one run per client request |
batch_schedule_claim_unique on idempotency.schedule_claim | unique, partial: only where the claim is a string | one run per schedule, slot and settings version |
batch_lease_expiry on (status, lease.expires_at) | compound | lets the reaper find expired runs without scanning |
tracked_prompt_live_key on (workspace_id, brand_id, norm_key) | unique, partial: only where archived_at is null | no duplicate live prompt, while an archived one can be added again |
brand_unique on tracking_schedules.brand_id | unique | one schedule per brand |
ws_unique on credit_accounts.workspace_id | unique | one balance per workspace |
refund_ref_unique on (ref, workspace_id, kind) | unique, partial: only where kind is refund and ref is not empty | one refund row per charge |
order_unique on billing_payments.order_id | unique | a payment row is reserved before the charge, so the same order cannot be charged twice |
free_use_unique on (workspace_id, action, subject) | unique | a free allowance cannot be claimed twice |
job on billing_daily_runs | unique | a daily job is claimed once per day |
key_hash on api_keys | unique | lookup by hash; the plaintext is not stored |
ws_email_unique on workspace_members | unique | one seat per person per workspace |
Partial unique indexes carry most of the weight. A plain unique index on an optional field treats every missing value as the same value, so the second document without a request key would be rejected. The partial filter restricts the rule to documents that have the field, which is exactly the set the rule is about.
The in-memory database used by most tests ignores partial filters. The test configuration patches it to honour them, and a separate set of tests runs against a real MongoDB to confirm the indexes exist and behave as the code assumes. Without the patch the idempotency tests would pass against a database that enforces nothing.
Data that expires
| Index | Lifetime | Why |
|---|---|---|
runs_ttl_90d on engine_runs.fetched_at | 90 days | raw answers are large and age out; the mentions and snapshots derived from them stay |
serp_cache_ttl_2d | 2 days | cached search result pages, kept only briefly because the pages change |
expires_at_ttl on one-time codes and login hand-offs | at the stored time | secrets that must not outlive their purpose |
The 90-day expiry is a product decision as much as a storage one. The derived numbers are what customers compare over months. The raw text is what lets a result be re-checked, and after a quarter the engines have changed enough that a re-check would not reproduce it anyway.
Compare-and-set
Where a unique index cannot express the rule, a conditional update does. The filter states what the writer believes is true, and the write happens only if it is.
| Where | Condition | What it prevents |
|---|---|---|
start on a run | status is queued | starting a run twice |
heartbeat, finish | status is running and the lease owner is this process | a worker that lost its lease writing a result |
claim_interrupt | status is active and the lease expired | the reaper closing a live run, or two reapers closing one |
claim_settling | not yet settled and no live settlement claim | two refunds for one run |
charge | each credit bucket holds at least what is taken | a balance below zero |
| refund | the marker for this reference is not yet applied | crediting a refund twice |
| daily gate | the stored day is not today | a daily job running twice |
audit finalize | status is not already ready or error | a reaped audit being overwritten by its late worker |
| brand fields, topics | revision equals the revision the editor read | a background re-read overwriting a value a person just corrected |
The last row is optimistic locking. A brand’s fields can be edited by a person in the dashboard and refreshed by a background job that re-reads the brand’s site. Both read a revision number and write with that number in the filter. The loser gets a conflict and the route answers 409. A person’s correction therefore survives a refresh that started before it.
One primitive for existing documents
The ODM’s save() writes the whole document and inserts it if the id is missing. For a background job that is the wrong default twice over. It can overwrite fields that changed while the job ran, and it can bring back a document that was deleted while the job ran.
All such writes go through save_existing, which lives in its own shared package. It updates by id, accepts extra guard fields, and never inserts. If the document is gone, the write matches nothing and the job learns that from the return value. An import-linter contract keeps that package free of any domain import, so every domain can depend on it without creating a cycle.
What I would change
The balance is stored on the account and the ledger is the explanation. A nightly job that recomputes each balance from the ledger and reports any difference would turn “the two agree by construction” into “the two were checked last night”. The data to do it is already there.
