Skip to content

Architecture

RAG is a Temporal worker. The Go API is the Temporal client that starts these workflows; RAG executes them, and the API surfaces their progress by watching Temporal and streaming status over its …/watch SSE endpoints (which the app consumes as tRPC subscriptions).

The worker (app/temporal/worker.py) connects with the deployment environment as its Temporal namespace and polls a single task queue, rag (TEMPORAL_TASK_QUEUE_RAG; the code default was a stale rag-tasks until huddlesurety/rag#164). It registers 6 workflows and 23 activities (23 since #159 split render_detect into detect_blanks + validate_blanks).

  • Most activities are synchronous (def, not async def) and run on a ThreadPoolExecutor — the heavy work (PDF rendering, OCR, embeddings, DB) is blocking and CPU/IO-bound. terminate_stale_fills is the exception: it is async def because it drives the Temporal client to cancel superseded fills. Admission is resource-based: WorkerTuner.create_resource_based admits activities against memory/CPU targets (worker_target_memory 0.8, worker_target_cpu 0.9), bounded by configurable slot caps (worker_activity_slots_min 8, worker_activity_slots_max 200; workflow slots capped at 500), and the thread pool is sized to the activity-slot max — not a fixed count. (Resource-based slots replaced the old fixed max_concurrent_* settings; the SDK can’t combine the two.)
  • Workflows run in Temporal’s sandbox, with sniffio and opentelemetry passed through (the httpx-based API SDK’s async-client garbage-collector finalizers run on arbitrary threads where a lazy import sniffio inside httpcore would crash, and the OTel imports don’t survive the sandbox otherwise).
  • The worker also runs a minimal background health server (start_health_server, port 8080, GET → 200 "ok") in a daemon thread, for the Railway platform healthcheck. It is not the source of the status signal — that comes from a Temporal poller metric, not an HTTP probe.
  • Services are imported lazily inside activities, not at module top, to keep the workflow sandbox’s import graph small and defer heavy deps (fitz, numpy, Voyage) off the startup path.
Workflow Arg What it does
ParseDocumentWorkflow document_id Parse → clean → chunk → embed → mark-parsed
GenerateFieldWorkflow field_id Retrieve → rerank → LLM extract (cited passages) → anchor + dedupe → evidence rows + page images
FindBondWorkflow request_id Locate the bid/final bond form(s) in the docs
FillBondWorkflow bond_id Detect blank fields (vision-LM + PDF geometry) and fill them (vision-LM)
DeleteDocumentWorkflow document_id Remove a document’s chunks/elements
ProcessBondRequestWorkflow request_id Parent — orchestrates the above

Each stage is a separate activity with its own timeout and retry, so a failure resumes at the failed stage rather than re-running the whole chain.

ProcessBondRequestWorkflow is the durable, server-side replacement for what used to be a fire-and-forget chain kicked off in the browser (which died on a page refresh). It takes only a request_id and spawns the others as child workflows:

graph TD
    P[ProcessBondRequestWorkflow] --> R[resolve_process activity<br/>→ docs to parse + fields to generate]
    R --> PH1{Phase 1 — parse, strict}
    PH1 --> PD1[child: ParseDocumentWorkflow ×N]
    PH1 --> PH2{Phase 2 — find + generate, best-effort}
    PH2 --> FB[child: FindBondWorkflow]
    PH2 --> GF[child: GenerateFieldWorkflow ×M]
    PH2 --> PH3{Phase 3 — fill, best-effort}
    PH3 --> TS[terminate_stale_fills activity]
    TS --> FL[child: FillBondWorkflow ×K]
  • Phase 1 (parse — strict): one ParseDocumentWorkflow child per unparsed document, gathered concurrently. It drains all children first (each completed one is durably marked parsed), then fails the run if any failed — so a resubmit re-parses only the failures.
  • Phase 2 (find + generate — best-effort): once parsing succeeds, it spawns FindBondWorkflow plus one GenerateFieldWorkflow per generated field, all concurrently. Individual child failures are logged but don’t sink the rest. Which fields are generated, and with which retrieval and generation queries, comes from the request org’s bond request spec (get_bond_request_spec(org_id, bond_type); a contractor org gets its agency’s spec, #184). A ref the spec doesn’t mark as generated is skipped as not_generated.
  • Phase 3 (fill — best-effort): once find + generate finish, the parent fills every located form (FindBondWorkflow’s fillable_form_ids). Fill must run last because its data_prep reads both the Bond records find wrote and the freshly generated field values. Since a child start can’t carry a conflict policy, the parent first runs the terminate_stale_fills activity to kill any in-flight FillBondWorkflow with the same derived ID (e.g. a wizard-triggered fill whose data_prep ran before all generated values landed), then spawns one FillBondWorkflow child per fillable form. A child already running under the same ID is handed off (not double-filled), and one terminated by a Go-side re-trigger is treated as superseded, not fatal.
graph LR
    A[Download PDF<br/>presigned URL] --> B{Scanned?}
    B -->|text layer| C[PyMuPDF blocks]
    B -->|scanned| D[Tesseract OCR<br/>ProcessPool per page]
    C --> E[Store elements]
    D --> E
    E --> F[Clean + chunk]
    F --> G[Embed<br/>Gemini · LiteLLM]
    G --> H[Store chunks<br/>pgvector]
  • Parser (parser.py): downloads the PDF via a presigned URL, samples pages to decide scanned vs. text-layer. Text PDFs use PyMuPDF get_text("dict") blocks; scanned PDFs render each page to PNG and OCR in parallel via a ProcessPoolExecutor (one process per page — Tesseract isn’t thread-safe). Output is DOMElements with normalized [x1,y1,x2,y2] bboxes.
  • Clean + chunk: OCR noise (single-char runs, dot/dash leaders, U+FFFD) is stripped. The parser marks section headings across the whole document (headings.py: font size against body text, bold, caps, numbering, and run-in headings on text PDFs; text shape only on OCR) and types them Title. The chunker then cuts at those headings into sections of 1600–3200 characters (CHUNK_MIN_CHARS / CHUNK_MAX_CHARS). A section closes at a heading once it holds the minimum, or before it would pass the maximum. Chunks don’t overlap. Each one keeps its source element_ids for grounding, and element ids follow parse order, so ORDER BY page_number, id reads the document in order. This used to read “~1000-char chunks (1500 max, 200 overlap)”; that fixed-size chunker was replaced in #177.
  • Embed: the EmbeddingService embeds via litellm.embedding (gemini/gemini-embedding-001, 1536 dims, task_type="RETRIEVAL_DOCUMENT") in parallel batches with a shared token-bucket rate limiter; only rows with a NULL embedding are embedded, so it resumes cleanly. Calls route through the LiteLLM gateway and carry the requester org / workflow as x-litellm-customer-id / x-litellm-tags headers for per-org, per-workflow spend attribution.
  • Mark parsed (mark_parsed): the final step flips the document’s parsed flag via update_document. Because that call replaces the whole document, the activity reads the current row first and passes uploaded_at back unchanged (the SDK Document no longer carries uploaded_by) — marking a document parsed must not clear its upload timestamp.
graph LR
    A[Fetch agency's field spec<br/>from API] --> B[Embed query]
    B --> C[Hybrid search<br/>dense + BM25 → RRF]
    C --> D[Rerank<br/>Voyage]
    D --> E[LLM extract<br/>strict JSON schema]
    E --> F[Anchor citations<br/>+ dedupe]
    F --> G[Update field<br/>+ evidence row & PNG per page]
  • Embed query (EmbeddingService.embed_query, task_type="RETRIEVAL_QUERY"): the query vector is served from a Postgres query-embedding cache (query_embedding_cache) before any API call — a hit returns in-process, spending no tokens and skipping the rate-limit bucket. Only a miss embeds through the gateway and back-fills the row.
  • Hybrid retrieval (vectorstore.hybrid_search): a dense arm (pgvector cosine, <=>) and a BM25 arm (ParadeDB pg_search) run on separate pooled connections and are combined with Reciprocal Rank Fusion (with optional anchor-term boosting).
  • Rerank: Voyage rerank-2.5-lite via litellm.rerank, routed through the gateway (the alias voyage/rerank-2.5-lite the proxy declares) and gated by the rerank_enabled flag — no longer by the presence of a Voyage key, since the worker no longer holds one.
  • Prepend: chunks from each document’s first RAG_PREPEND_PAGES pages (rag_prepend_pages, default 8) that retrieval didn’t already return are put ahead of the reranked results. Cover-page and early-spec facts reach the model even when they rank low. Earlier versions of this page left the step out.
  • LLM extraction: a Gemini chat model (VERTEX_MODEL, default gemini/gemini-3.8-flash, via litellm.completion) with strict JSON-schema structured output (additionalProperties: false, reasoning_effort="low"), under an explicit per-call timeout. It used to run at "minimal"; Gemini 3.8 Flash rejects that level (#160), so the extractor and the bid-bond finder moved to "low" (the final-bond finder already used it). Confidence is a weighted blend of vector score and the model’s self-reported confidence.
  • Evidence (rag_extractor._locate_evidence, grounding.py, evidence_dedupe.py; #186, #187): the model cites every passage the answer depends on as a chunk plus a verbatim quote. Each citation is anchored to an element of the chunk it cites (pick_anchor): the smallest element containing the quote, else the one holding most of it, provided some element reaches rapidfuzz ≥ 85. Citations that can’t be anchored are dropped. dedupe_evidence drops repeated quotes and extra quotes that only restate the answer, then, if two or more remain, one Jev (TypeSafe) request drops citations that add nothing or are blank-form wording (score below 0.3). That call is a single 10 s try; if it fails every citation is kept, and EVIDENCE_JEV_DEDUPE=false skips it. evidence_update writes value and confidence with update_bond_request_field, replaces the field’s bond_request_field_evidence rows with one row per (document, page), then renders each page at 150 DPI with the cited lines highlighted (line_boxes) and uploads the PNG to a presigned URL keyed by the evidence ID (one retry on a 5xx). The workflow result still reports only the first citation. This bullet used to describe one quote grounded to one page and bbox, with the evidence reference written on the field itself.
  • Find (bond_finder.py, final_bond_finder.py): a fast scan pass produces page references only (no page text crosses the activity boundary — a recurring memory-hygiene rule), then an LLM refine pass re-fetches just those pages to pick the winning document and consecutive page span. The final-bond finder dedups against any bid bond already found. A best-effort find_bid_bond_percent activity runs concurrently with the refine pass to extract the bid-bond penalty percentage; it degrades to 0.0 on failure. Since #191 it first sends the LLM every chunk that names bid security and states a percentage (up to 40, no embedding or rerank). It falls back to hybrid search + rerank top 5 only when no chunk matches or the LLM finds no requirement. Percentages are a strict-number schema coerced through a shared services/pct.py (coerce_pct) and clamped to [0, 100], while performance/payment specs are forced to 100%. write_bonds centralizes a delete-then-insert for idempotency and maps internal refs to the SDK’s bond_type (bid/final). It creates every form with attachments=[] — RAG never attaches documents to a form.
  • Fill (bond_filler.py): blank detection (below) yields field boxes, then a vision-LM fill pass (fill_write) fills values from known contractor data. Penal sums and their word forms are computed in Python, not by the model. Surety details (name/address/phone) are fetched live from the API by org_id in data_prep rather than hardcoded (phone falls back to a default if the fetch fails). For a bid bond, data_prep also emits a sibling today block — the signing date resolved in America/Los_Angeles via services/timezone.py (today_parts) — and the bid fill prompt dates execution / notary / witness blanks from it, while bid-date blanks still come from bidBondRequest.bid_date. The final-bond prompt is unchanged: every date blank, notary included, comes from finalBondRequest.contract_date. (These refs were camelCase, bidDate / contractDate, until #185 moved field refs to snake_case.)
  • Standard forms (AIA, EJCDC, and federal SF 24 / 25 / 25-A): detect_blanks identifies the form family from the PDF text layer and passes it on to fill_write. Family forms get extra prompt rules and run the fill at low reasoning effort only. With STANDARD_FORM_PATH=template (the default), fill_write then calls fill_router.route, which merges three sources: AcroForm widgets (AIA and EJCDC only), label-anchored template slots (template_fill.py, no LLM), and the vision fields. Where they overlap, a widget wins over a template slot, and a template slot over a vision field. If the router fails, the fill falls back to the vision fields. Values are formatted (December 23, 2026, $300,000.00) and drawn at 8 pt (#180). They used to start at 10 pt and shrink to fit; now DM Sans widths only decide where a block wraps and when an EJCDC or federal address collapses to two lines, and text that still overflows at 8 pt is clipped on export. prompt keeps the rules and the low effort but skips the router, and off sends every form through the general path.

FillBondWorkflow runs get_context, then detect_blanks in parallel with data_prep, then validate_blanks, then fill_write. The two detection steps are separate activities (3-minute timeout each) so each LLM step shows on the Temporal timeline with its own retries; each re-downloads and re-renders the PDF, and only small JSON crosses the boundary.

  • detect_blanks — the vision-LM detect pass (bond_filler.detect_blanks, schema blank_detection) proposes labelled boxes from the rendered pages.
  • validate_blanks → blank_hybrid.merge_blanks fuses those boxes with a PDF geometry oracle (blank_geometry.py), which reads blank rules straight from the PDF — thin filled rects, horizontal stroked lines, and underscore runs — merges collinear fragments, and drops rules that already have text on them.
    • On pages with rule geometry, LM and geometry boxes are paired (same_slot). An agreed box takes the geometry box and the LM’s label.
    • Boxes only one side found go to one validator call per form (FILL_BOND_VALIDATE_PROMPT, schema blank_validation, "low" effort only). It sees each box as a numbered crop and answers keep/reject, naming geometry-only boxes. It never returns coordinates.
    • If the validator fails, LM-only boxes are kept and unnamed geometry-only boxes are dropped. Pages with no rule geometry keep the LM output unchanged.
    • Each field carries a source (agreed / geo / lm). denormalize_fields draws agreed/geo boxes rule-exact: the PDF’s x-span and baseline, one line tall, with no padding or underline repair.
  • Field pages are form-relative (#162): fill_write writes each field’s page as the model’s 0-based index within the form’s own pages and sends no attachment_id, so every field anchors to the form segment rather than an attachment.

Everything goes through the git-installed huddlesurety-api SDK, built by get_huddle_client() on a custom httpx.Client:

  • Auth: a request hook adds requester_headers() — Authorization: Bearer <workflow token> — to requests to the API host only. The token is the one the API minted for the user who started the workflow (see below), so RAG’s calls are authorized and audited as that user. There is no service key; an activity without a token sends no credential and gets a 401.
  • Timeout: an explicit httpx.Timeout(10s, connect=10s) — set wider than httpx’s 5s default because some API calls (e.g. synchronous PDF trimming) take longer than a couple of seconds.
  • The client is instrumented so RAG → API calls emit a CLIENT span and inject traceparent, producing the RAG → API edge in the service graph.

Baggage doesn’t cross the Temporal boundary, so RAG carries the requester itself via worker interceptors (app/o11y/identity.py):

  • The inbound workflow interceptor reads the requester headers off the workflow header; the outbound interceptor re-injects them onto every child workflow and activity (mirroring the Go API’s propagator, which doesn’t run on the Python side).
  • The activity interceptor reads them back into current_token / current_org_id context vars and stamps workflow.type on the OTel span. Nothing identifies the requester on spans.

The headers are x-huddle-token (the workflow token, read by requester_headers()) and x-huddle-org-id (read by gateway_headers() for LiteLLM), JSON-encoded to match the API’s propagator. Traces export on a 5s interval (metrics on 15s) so app → api → rag traces assemble quickly in Grafana. The detection activities add child spans per step: download, render, and lm_detect in detect_blanks, and merge_blanks (with geometry and validate children) in validate_blanks. Every complete_json attempt in the filler gets its own llm_call span with llm.schema, llm.effort, token counts, and an llm.outcome of ok / timeout / truncated. The matching log lines carry per-step *_ms timings. Custom rag.* metrics record LLM/embedding tokens, call duration (rag.llm.call.duration, which also has an optional call label: the filler’s schema name, such as blank_detection, blank_validation, or bond_fill), and USD cost per model, plus a rag.embedding.cache counter with a three-way result (hit/miss/error) and an op (read/write) so a dead cache reads as error, never as a cold-but-healthy miss. Note that provider-side spend and latency now live in the LLM gateway’s own dashboard, not in Tempo — RAG spans end at the litellm call.

Schema document, migrated by goose (app/db/):

  • document.chunk — id, document_id, project_id, org_id, raw, embedding vector(1536), element_ids UUID[], plus a BM25 index (USING bm25 … WITH (key_field='id')) for ParadeDB search. The embedding dimension is substituted into the migration from EMBEDDING_DIMENSION.
  • document.element — raw text blocks with bbox, page_number, element_type.
  • document.query_embedding_cache — query_hash (PK), query, model, dimensions, embedding. Caches query-side embeddings keyed on a SHA-256 of (model, dimensions, task_type, query), so a model swap or EMBEDDING_DIMENSION change misses into fresh rows rather than needing invalidation. Every read/write failure degrades to a miss — a cache outage looks exactly like the pre-cache path plus a log line.

A process-wide psycopg3 ConnectionPool (db_pool_min_size 2 / db_pool_max_size 30, sized independently of the activity-slot cap) is shared across activities. Vectors are passed as pgvector text literals; IDs convert between ULID (Go/S3) and UUID (DB) via idconvert.