> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Research architecture and pipeline

> Portable Research ports, Cloudflare storage, and the pipeline stop and recovery procedures.

## Boundaries

Research turns uploaded or generated documents into facts, a graph with evidence, and gold review data. The Cloudflare PoC handles synthetic data for the regulated domain (compliance and finance). Each project policy chooses `cloudflare-test`, `our-machines`, or `client-machines`, and names the allowed model and serving-host pairs and the apps that can embed Research widgets. The allowlist stores an upstream host ID, display name, and kind with each model ID. Settings groups entries with `groupAllowlistByHost(policy)`. Audio transcription uses explicit model and host entries. The Cloudflare pipeline accepts only `cloudflare-test` projects. Boundary changes close its current execution epoch.

The seven portable ports in `@tuturuuu/research-core` are `Store`, `BlobStore`, `Queue`, `VectorIndex`, `ModelRouter`, `Clock`, and `Identity`. `PipelineStore` adds atomic execution-control operations for queue and Workflow adapters. In-memory implementations live at `@tuturuuu/research-core/memory`. The boundary test rejects dependencies outside the core source tree, including framework, runtime, and Cloudflare modules.

| Runtime | Adapter layout |
| - | - |
| Cloudflare | D1 control and project databases, R2, Vectorize, Queues and Workflows, and provider-qualified open models through a dedicated AI Gateway HTTPS endpoint. |
| On premises | Inject Postgres, an S3-compatible blob store, a Postgres-backed queue, pgvector or Qdrant, and local inference through the same ports. The OpenAI-compatible adapter accepts a trusted GPU node endpoint and checks that the configured host matches the project's boundary and allowlist. |

The public Worker HTTP endpoint returns 404. Bind `ResearchPipelineIngress` only from a trusted server that has already checked the workspace's `research_app` flag and the caller's project grant. The Worker's `RESEARCH_APP` switch, the project's enabled state, its policy, and the D1 stop fence also gate execution. Configure the separate `ResearchPipelineControl` entrypoint only for operations. The platform owns workspace grants and their audit. The control database owns Research audit events, without a copy of those grants.

## Documents and reviews

Ingest produces a SHA-256 hash and stores the original bytes in a project-scoped immutable R2 object. Unknown types stay visible with an `unknown-type` flag. The PoC reads raw UTF-8 text and CSV directly. Other recognized types use an immutable prepared JSON artifact of `SourcePage[]` saved under `Document.preparedBlobKey`. PDF extraction, OCR, attachment traversal, and other format readers prepare that artifact separately. A recognized document without preparation ends with `preparation-required` and can be submitted once its source revision changes.

Each evidence span carries the file ID, one-based page, and inclusive start and exclusive end as zero-based UTF-16 offsets. An optional OCR box uses normalized page coordinates. Text-only extraction accepts a verbatim quote that occurs once on its page. Facts and edges carry their own evidence, confidence, model ID, prompt version and review status.

`Store.saveReview` atomically keeps an answer and its gold label, copying provenance from the reviewed fact or edge. It retains reviewer, time, uncertainty, and any corrected value. Overlap uses the latest answer from each distinct reviewer for the same project and item. An individual answer records that reviewer's judgment. A review surface owns the final item status and group decisions.

## Ingestion

`@tuturuuu/research-ingest` prepares documents for the pipeline. It detects the real format from content, reads it into normalized pages and segments, and stores everything through the same `Store` and `BlobStore` ports:

* The original bytes go to `files/<sha256>`. Unknown formats keep an `unknown-type` flag, and recognized formats whose reader fails keep `unreadable`. The pipeline skips both.
* The full reader output goes to `normalized/<documentId>/<readerVersion>.json`. Each segment's span (file ID, page, UTF-16 offsets, optional box) indexes its page text exactly.
* The pipeline input is a content-addressed `prepared/<sha256>.json` of `SourcePage[]`, trimmed to the core input limits with page numbers unchanged, and saved as `Document.preparedBlobKey`.
* Attachments and archive members are ingested as their own documents, named `<parent>!/<member>`, within shared run, depth, entry and decompression caps.

OCR and transcription go through a separate `RecognitionRouter` port with explicit `ocr` and `transcribe` allowlist entries. `BoundedRecognizer` checks the model and host pair, a per-document page budget, a per-run call budget, a retry cap, and the project's `PipelineStore` fence before every call. A closed fence leaves pages pending. `@tuturuuu/research-generator` produces the synthetic files with ground truth, splits and the held-out guard. The [`ttr research` reference](https://docs.tuturuuu.com/reference/packages/cli-research) covers the CLI, formats and limits.

## Bench and quality

`@tuturuuu/research-bench` measures a model and pipeline configuration against one split of a generated dataset. It is framework-free and runs on injected ports: a `ModelRouter`, the project's `PipelineStore` fence, and a `Clock`. `ttr research bench run` wires it to local in-memory adapters. No Worker binding, route or web adapter reaches it.

Each document's prepared pages go to the model, and `linkEvidence` keeps only candidates whose quote occurs exactly once on the cited page. Scoring then compares the result with the ground truth:

| Metric | Definition |
| - | - |
| Fact accuracy ("right") | Predicted facts that cite a truth mention (at least half its key fragments in the cited span) and state its values correctly (linked entity names, amount digits, date parts, reference), over all predicted facts. |
| Fact recall | Truth facts on scored documents recovered correctly, over all of them. Unreadable or unscored documents count as missed. |
| Groundedness ("sticks to its sources") | Candidates whose cited span exists and contains every anchor of the claim (each number of three or more digits and each code-like token), over all candidates. |
| Entity F1, link F1 | Micro F1 over normalized entity names, and over unordered entity-name pairs, per document. |
| Agreement | Cohen's kappa for the reviewer pair with the most shared items, and Fleiss' kappa over every item with two or more reviewers, from `goldOverlap`. |
| Throughput | Documents per hour of bench wall-clock time. |
| Cost | Operation counts (calls, input and output text units at four per token, artifact reads and writes, result writes) times a checked-in price table. Our own GPU nodes and client machines carry no per-token price. A gateway model without a table entry is reported as unpriced, never guessed. There is no provider readback. |

Names compare after removing diacritics, case and punctuation, so scanned uppercase ASCII and Vietnamese renderings match. Numbers compare by digits, so `1,234,567` and `1.234.567` are one amount.

The "How good is Lumen" score is a weighted mean of five rates scaled to 0–100:

```
score = round(100 × (0.4 × fact accuracy + 0.2 × groundedness + 0.2 × fact recall
                     + 0.1 × entity F1 + 0.1 × link F1))
```

Accuracy carries the most weight because a wrong fact costs a reviewer the most. Speed and cost are shown beside the score, never inside it.

Every mistake (a wrong value, a missed fact or an unsupported prediction) is tagged with its document format, language, channel, wrong field and noise. Clusters over those facets drive "Where it struggles". Each item is one of the largest distinct clusters with one fixing action: a `ttr research generate --focus …` command for targeted examples, or the ingest models config when the files need a reading model.

Held-out data is evaluation-only. A dev run selects truth with the tuning purpose, refuses any held-out case, document or file, and is the only source of clusters and actions. A held-out run yields aggregate metrics only, and `errorClusters` and `whereItStruggles` refuse a held-out report.

Runs are bounded. Each configuration is checked against the allowlist and its pinned host before the run and before every call. A run-wide call budget, a document budget, two attempts per document, the core page and text caps, and the `PipelineStore` fence at the run's opening epoch apply. A closed fence or an exhausted budget stops the run, marks the remaining documents `not-run` and keeps what was scored.

Review answers become gold through `Store.saveReview`. `goldAgreement` reports inter-annotator agreement, and `goldAccuracy` reports the reviewers' majority verdict per item. The model comparison (`compareModels`) lists only models the project allows today, grouped by their serving host with its real name.

## Cloudflare storage and shard capacity

The D1 `research-control` database owns project records, policy, shard routing, audit, and the pipeline admission ledger. Each project maps to a configured D1 binding for documents, facts, entities, edges, reviews, gold, and pipeline scores. R2 stores original and prepared inputs in a separate area from pipeline artifacts. A shared 1,024-dimensional cosine Vectorize index uses a separate namespace and physical ID derivation per project.

Apply the control and project D1 migrations to their respective databases. Pre-migration control state holds admissions closed. Missing bindings or project schemas surface as storage unavailable. A change to shard write admission, project, or policy closes the current fence.

D1 caps a paid database at 10 GB and a Free database at 500 MB. Track database bytes including indexes. For a paid project shard, start planning a split at 7.5 GB and close shard write admission at 8 GB. For Free rehearsals, use 300 MB and 350 MB respectively. These are operator thresholds. Threshold monitoring and migration execution belong to operations. [D1 limits](https://developers.cloudflare.com/d1/platform/limits/)

For a project that needs more than one shard, split along a stable document partition such as train, dev and held-out, followed by a hash partition if a split still grows. Keep each document and its facts, per-document edges, reviews and gold together. Keep entity IDs stable across shards and join cross-shard views by those IDs. Extend routing and prove readback and graph traversal before moving records. Close writes, copy and verify statement-level counts and hashes, switch the shard map, and open a fresh epoch only after readback. The PoC maps one writable database per project.

## Pipeline and durable stop

The queue carries only a deterministic run ID. A Workflow with the same ID advances `read → extract → link → score`. A run pins the project's epoch, document revision, model and host IDs and prompt version. Each stage writes a stable checkpoint under its attempt key. The successful attempt selects the canonical R2 artifact. Result records and the pipeline score use stable IDs and one idempotent project D1 transaction. Read measurements through the scoped `scores` collection. A repeated Vectorize upsert uses the same logical vector ID. A result-write failure can leave a vector before its matching D1 score is available.

D1 atomically exchanges a finite project budget for each new run. It admits each operation only while the run's epoch and lease are current and each stage-attempt operation can be spent once. Closures take effect at this atomic admission. A binding operation already admitted while the fence was open can finish. An old epoch cannot admit another operation, including after the project is enabled again.

1. Read the project's current epoch with the private control binding.
2. Call `stop(projectId, expectedEpoch)` and confirm the returned fence is disabled with a higher epoch. If a concurrent change wins the compare-and-set, read the fence again before repeating the stop.
3. Check the stored Queue, Workflow and stage permit counts for the stopped epoch. Confirm that a delayed delivery cannot acquire new permits. Terminal runs schedule no follow-up jobs.
4. Open a new bounded epoch only from authorized operations after the project policy, workspace flag, resource bindings and gateway policy are verified.

A closed fence stops a stage unconditionally. A handler failure, an unspent retry budget or a claim still awaiting its lease never schedules another attempt once the fence is closed. Each stop is recorded once in the control store's `audit` table as `pipeline.fence-tripped`, with actor `system:research-pipeline` and the run ID as subject. Check those events in step 3.

The read stage skips a document flagged `unreadable` or `unknown-type` before reading its source, so no extraction model sees it. The document and its flag stay stored. Before the score stage embeds or writes anything, it checks that the score and every entity, fact and edge name the run's project, and every fact the run's document. `writePipelineResult` repeats that check, so a mismatched row fails the run and writes nothing.

Inference endpoints use HTTPS. Plain HTTP is accepted only for a loopback host (`127.0.0.0/8`, `::1`, `localhost`). A base URL with credentials, a query or a fragment is refused, including a bare `?` or `#`.

The checked-in Worker config uses placeholder resources and starts disabled. The HTTPS router uses a fixed DeepInfra route for Qwen3-VL 30B extraction and multilingual BGE-M3 embeddings. It checks the model and serving host against the project policy before each call. The dedicated gateway account, gateway ID, and token are supplied by `RESEARCH_GATEWAY_ACCOUNT_ID`, `RESEARCH_GATEWAY_ID`, and `RESEARCH_GATEWAY_TOKEN`. The AI Gateway custom provider must point to DeepInfra's canonical HTTPS endpoint. Verify that route and its model policy before opening a project epoch. The example gateway policy and its provider configuration require Security Desk ACK before application. [Cloudflare AI Gateway custom providers](https://developers.cloudflare.com/ai-gateway/configuration/custom-providers/), [AI Gateway policy evaluation](https://developers.cloudflare.com/ai-gateway/features/policies/), [DeepInfra model catalog](https://deepinfra.com/models/embeddings)

## Operation limits

The pipeline admits up to 100 runs per manually opened project epoch. The D1 ledger atomically records each operation against an enabled project epoch and stage attempt. A stop also prevents delivery and later lease claims. Project, policy and shard-routing changes close admissions. Terminal runs schedule no more work, and a new epoch cannot revive prior work. Local operation-count and mutation tests exercise the per-step fences. Hosted gateway and stop readback are pending while the placeholder deployment configuration stays disabled.

| Operation | Per run | Per activated project epoch |
| - | -: | -: |
| Reserved jobs | 1 | At most 100 |
| Queue sends | At most 2 | At most 200 |
| Workflow creation requests | At most 2, one stable instance ID | At most 200 |
| Stage attempts | At most 8 | At most 800 |
| Stage operation permits | At most 24 | At most 2,400 |
| Inference HTTPS calls | At most 4, one provider attempt per call | At most 400 |
| Vectorize upsert calls | At most 2, one vector per call | At most 200 |

The extraction input is bounded at 24 pages, 12,000 UTF-16 units and 128 KiB per artifact. Extraction asks for at most 2,048 output tokens and accepts at most 12 candidates, each with at most three entities and three relations. Embedding uses at most 1,500 UTF-16 units. A successful score transaction writes at most 85 rows. Gateway cache, collection of request logs, and nested provider retries are disabled. Queue and Workflow retries have fixed limits. There are no recurring triggers or automatic budget renewals.

## Loopback verification

From the repo root, use the installed CLI and a disposable, private directory.

```sh theme={null}
umask 077
research_scratch="$(mktemp -d)"
ttr resources run -- node apps/research-pipeline/tests/runtime-smoke.mjs \
  node_modules/.bin/wrangler "$research_scratch"
```

The harness applies the checked-in migrations to isolated Miniflare databases, binds on loopback, verifies a complete Queue → Workflow → D1/R2 run, stops a second run after embedding, then restarts the Worker and redelivers both messages. It exercises the real Workflows, Queues, D1 and R2 local runtimes. The inference calls use an in-memory model router, and Vectorize uses an in-process fixture behind the namespace adapter. Separate tests verify the HTTPS adapter's request shape and rejection paths with a fake transport. Hosted Gateway policy enforcement, remote Vectorize visibility and production billing need separately authorized acceptance. The exact-run ledger and output are stored in the supplied private directory. [Cloudflare local development support](https://developers.cloudflare.com/workers/local-development/)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.