quarry-rag

module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2026 License: MIT

README

Quarry

CI CodeQL OpenSSF Scorecard Go Version Go Reference Release

Quarry (quarry-rag) is a domain-agnostic retrieval-augmented generation (RAG) microservice written in Go. It provides HTTP endpoints for backend applications and distributed services to ingest textual documents (raw JSON or multipart PDF, DOCX, DOC files), generate vector embeddings, persist document metadata, and answer natural-language queries grounded in the indexed corpus.

Features

  • Durable document ingestion: Accepts text or PDF, DOCX, DOC and UTF-8 or UTF-16 plain text uploads into PostgreSQL before responding, with content verification, atomic deduplication, parallel processing, leased retries and restart recovery.
  • Adaptive retrieval: Evaluates query complexity and similarity signals to route between LOCAL and GLOBAL vector search using the configured backend.
  • Optional reranking: Bedrock reranking orders retrieved evidence before synthesis context selection.
  • Tenant and document filtering: Supports metadata filtering by document type and query-time document ID allowlists enforced before synthesis.
  • Grounded synthesis: Generates answers in the language of the incoming question using Bedrock or OpenAI-compatible chat models when evidence is available; see the query API for empty results.
  • Offline development mode: Runs fully offline with deterministic in-memory vector storage and mock model providers via GO_RAG_FAKE_MODE.
  • Service authentication: Restricts operational and query routes with constant-time X-Service-Token verification.
  • Tracing: optional OpenTelemetry export over OTLP/HTTP, including LangSmith, for requests, pipeline stages, model calls and storage operations.
  • MCP server: quarry-mcp exposes ingestion, queries and document management to MCP clients over stdio.

Architecture Overview

Requirements

  • Go at the version in go.mod to build from source; the badge shows it, and CONTRIBUTING.md lists the tool versions.
  • Docker for the full test suite and image builds.
  • See the deployment prerequisite matrix for database, vector store, provider and optional service requirements.

Installation

  • Container image: docker pull ghcr.io/victoroide/quarry-rag:<version>, where <version> is a release number such as 0.2.0, for linux/amd64 and linux/arm64.
  • Release archives: quarry-server for Linux and macOS, and quarry-mcp for Linux, macOS and Windows, each for amd64 and arm64. Releases describes checksum and provenance verification.
  • MCP server: install quarry-mcp with go install or from a release archive; see Local MCP Server.
  • From source: go build -o bin/server ./cmd/server with the Go version in go.mod.

Quick Start

Offline Fake Mode

Follow the offline entry in the deployment prerequisites. See offline mode internals for the local components.

  1. Start a local PostgreSQL instance:
docker run --detach --name rag-dev-db \
  --env POSTGRES_DB=rag \
  --env POSTGRES_USER=rag \
  --env POSTGRES_PASSWORD=rag \
  --publish 127.0.0.1:5432:5432 \
  postgres:16.13-alpine3.23
  1. Run the service from source:
export GO_RAG_FAKE_MODE=true
export DATABASE_URL="host=127.0.0.1 port=5432 user=rag password=rag dbname=rag sslmode=disable"
export SERVICE_TOKEN="dev-token"
go run ./cmd/server
  1. In another terminal, check readiness:
curl localhost:8081/readyz

The response is {"status":"ready"}.

Docker Execution

To run the containerized application using Docker Compose:

  1. Copy the example configuration:
cp .env.example .env

Use the deployment prerequisite matrix to select and provision the vector store, model providers and optional features. Set the selected services' variables in .env. For non-fake deployments, also set at least one service token using SERVICE_TOKEN or SERVICE_TOKENS. Compose starts the application container.

  1. Start the container in detached mode:
docker-compose up --build -d

Usage

Ingest a Document
curl -X POST localhost:8081/ingest \
  -H "X-Service-Token: dev-token" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "The storage engine distributes records across replicated partitions for fault tolerance.",
    "doc_type": "technical_spec"
  }'
Check Ingestion Status

Replace <document_id> with the identifier returned by ingestion:

curl "localhost:8081/documents/<document_id>" -H "X-Service-Token: dev-token"

Ingestion is asynchronous: query after status changes from processing to completed; failed documents report last_error.

Query the Corpus
curl -X POST localhost:8081/query \
  -H "X-Service-Token: dev-token" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "How does the storage engine achieve fault tolerance?",
    "mode": "auto"
  }'

For incremental answers, see streamed query answers.

Configuration

The service reads configuration only from environment variables. Configuration lists every variable with its default and bounds, and .env.example is a starting point for Docker Compose.

Operations

GET /livez and GET /readyz serve liveness and readiness probes, and GET /health reports dependency status. Setting METRICS_ADDR starts a separate Prometheus-format metrics listener. Logs are JSON on stderr and carry each request's X-Request-ID. Deployment covers logging, probes, metrics, shutdown and token rotation, and Tracing covers optional trace export, including LangSmith, sampling and content capture.

Limits

JSON ingestion accepts at most 1,000,000 bytes of decoded content. Its request-body cap is 8,097,152 bytes, allowing sixfold JSON escaping plus metadata overhead; queries accept a 1 MiB body. Every upload format enforces the same decoded-text limit. PDF extraction also enforces an 8 MiB decoded-stream budget. Oversized bodies return 413; parser extraction-limit failures return 422. See the API reference for image-only and mixed PDF OCR.

The runtime image uses numeric UID/GID 10001:10001. A failed automatic routing probe falls back to GLOBAL retrieval.

Limitations

  • Scanned PDF pages need optional OCR. Without OCR_PROVIDER=textract, image-only PDFs return 422 with no_text. The default image_only mode extracts embedded text when present. Enable mixed PDF OCR to recover scans in PDFs that also contain digital pages.
  • PDF layout fidelity depends on the mode. Plain-text extraction (PDF_LAYOUT_MODE=plain) does not reconstruct table structure or guarantee reading order and spacing in complex layouts. Enable PDF layout analysis (PDF_LAYOUT_MODE=textract) when layout and tables carry meaning.
  • Encrypted DOC files and Word 6/95 binaries are unsupported. The DOC reader returns 422 with encrypted or unsupported_version, and the API accepts no decryption password. Convert these documents before uploading them.
  • Hosted-index documents can take a moment to become searchable. Completion waits up to INDEX_VISIBILITY_TIMEOUT for the hosted index to return a document's last written vector. If the wait ends first, the document completes anyway, the service logs a warning and counts it, and the document becomes searchable once the index catches up. The PostgreSQL vector store has no visibility delay after completion. After deletion, the PostgreSQL visibility check excludes the document from new answers even if vectors remain in the hosted index temporarily.
  • Ingestion processing is at least once. Expired leases can cause an attempt to repeat, and a crash between external writes and cleanup can leave orphaned vectors in the hosted index. PostgreSQL and the hosted index do not share a transaction; vectors without a completed document are excluded from answers. The PostgreSQL vector store writes embeddings in the completion transaction and cascades document deletion, leaving no orphan vectors. With ingestion paused, make reconcile previews eligible cleanup; deletion requires ARGS="-apply" and preserves processing documents and retryable jobs.
  • Retrieved text can still steer answers. Excerpt markers, sanitization and synthesis instructions reduce prompt injection, and optional Bedrock Guardrails (BEDROCK_GUARDRAIL_ID) add prompt-attack and grounding checks. Hostile text in authorized documents can still influence an answer.
  • Token counts are estimated by default. Chunk estimates and the 30,000-byte cap bound input size. Configure an embedding input profile to enforce model-specific limits.
  • Synthesis uses a bounded part of the evidence. Under the default ranked setting of SYNTHESIS_CONTEXT_POLICY, excerpts are added in retrieval order, reranked when enabled, while they fit SYNTHESIS_CONTEXT_TOKENS estimated tokens, skipping chunks below SYNTHESIS_RELATIVE_SCORE_FLOOR of the best vector score; diverse instead packs complementary excerpts within the same budget and floor. Chunks left out are returned without an excerpt number, and a cut excerpt is marked truncated.
  • Citation checks. Requested citations report lexical overlap with the excerpts sent to synthesis. Deployments can enable calibrated semantic assessment.
  • Individual-user authorization belongs to the caller. Service credentials authenticate trusted applications. Those applications must supply each user's allowed_document_ids; REQUIRE_DOCUMENT_ALLOWLIST can require that field, but the service does not determine which documents a user may read.
  • Content deduplication can reveal that identical content exists within a collection. A collection-mode upload without document_id can reveal the ID of a document registered for shared matching in that collection. See document identity.
  • Concurrency limits apply per replica. Query admission, embedding and extraction limits are process-local; calculate per-replica caps as described in Deployment.
  • No-evidence answers are fixed messages. See the query API for language selection and the configuration guide for adding translations.
  • Document allowlists have size limits. MAX_ALLOWED_DOCUMENT_IDS and the 1 MiB query-body cap limit request size and the number of vector queries needed for large scopes. Use collection to scope large document sets with a single filter.
  • Offline mode does not measure hosted behavior. Its vector writes are immediately consistent and its answer generator echoes prompt context. It exercises contracts and storage limits, while answer quality and hosted-index latency require external-service testing.

Documentation

Document Description
Architecture Package organization, sequence diagrams, database entity-relationship model, and runtime lifecycles
API Reference Route definitions, authentication headers, request and response structures, and HTTP status codes
OpenAPI Description Machine-readable HTTP API contract
MCP Server Local stdio command, client setup, tools and Go client package
Configuration Environment variables, validation constraints, default parameters, and database schema migrations
Deployment Container image build, non-root user execution, external service requirements, and token rotation
Development Repository directory structure, unit and integration test suites, continuous integration workflows, operational scripts, and fake mode mechanics

Contributing

Read CONTRIBUTING.md and CODE_OF_CONDUCT.md before opening a pull request.

With the prerequisites listed in CONTRIBUTING.md available, run the full host checks and build:

make ci

make test runs the full race suite and needs a Docker daemon for isolated database tests. The Docker test stage runs the short suite without a daemon. Delete explicit documents with make cleanup IDS="<uuid> <uuid>".

Security

Report vulnerabilities privately as described in SECURITY.md, which also states the deployment boundaries the service relies on.

License

MIT

Directories

Path Synopsis
Package client provides a typed HTTP client for ingestion, queries and document management.
Package client provides a typed HTTP client for ingestion, queries and document management.
cmd
quarry-mcp command
Package main serves document tools to Model Context Protocol clients over stdio.
Package main serves document tools to Model Context Protocol clients over stdio.
server command
Package main is the entry point for the Quarry microservice.
Package main is the entry point for the Quarry microservice.
internal
api
Package api assembles the HTTP router with all handlers and middleware.
Package api assembles the HTTP router with all handlers and middleware.
api/handler
Package handler contains HTTP handler functions that translate between the transport layer and domain logic.
Package handler contains HTTP handler functions that translate between the transport layer and domain logic.
api/middleware
Package middleware provides HTTP middleware for logging and recovery.
Package middleware provides HTTP middleware for logging and recovery.
awsconf
Package awsconf configures shared AWS credentials and retries.
Package awsconf configures shared AWS credentials and retries.
chunker
Package chunker splits raw documents into token-bounded chunks with semantic-boundary awareness.
Package chunker splits raw documents into token-bounded chunks with semantic-boundary awareness.
citationsupport
Package citationsupport assesses claims against the exact excerpts used for synthesis.
Package citationsupport assesses claims against the exact excerpts used for synthesis.
cleanup
Package cleanup removes documents and their stored data.
Package cleanup removes documents and their stored data.
config
Package config handles environment-based configuration loading and validation.
Package config handles environment-based configuration loading and validation.
credential
Package credential reads bounded local credential material and compact JWT data.
Package credential reads bounded local credential material and compact JWT data.
domain
Package domain defines the core data types shared across the RAG pipeline.
Package domain defines the core data types shared across the RAG pipeline.
embedder
Package embedder provides embedding generation using AWS Bedrock Titan Embed V2.
Package embedder provides embedding generation using AWS Bedrock Titan Embed V2.
embeddinginput
Code generated from the Unicode 16.0.0 DerivedGeneralCategory and PropList data.
Code generated from the Unicode 16.0.0 DerivedGeneralCategory and PropList data.
evaluation
Package evaluation defines the purpose-written, versioned evidence fixture shared by the staging diagnostic and the evaluation executable.
Package evaluation defines the purpose-written, versioned evidence fixture shared by the staging diagnostic and the evaluation executable.
extractor
Package extractor provides text extraction from various file formats.
Package extractor provides text extraction from various file formats.
llm
Package llm provides synthesis routing, Bedrock Converse calls and an OpenAI-compatible chat client.
Package llm provides synthesis routing, Bedrock Converse calls and an OpenAI-compatible chat client.
logctx
Package logctx correlates structured logs with HTTP requests.
Package logctx correlates structured logs with HTTP requests.
metrics
Package metrics collects and writes Prometheus text metrics.
Package metrics collects and writes Prometheus text metrics.
ocr
Package ocr detects text in documents stored in S3.
Package ocr detects text in documents stored in S3.
pipeline
Package pipeline implements the decomposed ingestion and retrieval pipeline as a sequence of discrete, composable stages.
Package pipeline implements the decomposed ingestion and retrieval pipeline as a sequence of discrete, composable stages.
retriever
Package retriever implements LOCAL/GLOBAL adaptive retrieval using scoped vector search.
Package retriever implements LOCAL/GLOBAL adaptive retrieval using scoped vector search.
store/memory
Package memory provides an in-memory domain.VectorStore implementation for GO_RAG_FAKE_MODE (offline QA).
Package memory provides an in-memory domain.VectorStore implementation for GO_RAG_FAKE_MODE (offline QA).
store/pinecone
Package pinecone provides the Pinecone vector store client.
Package pinecone provides the Pinecone vector store client.
store/postgres
Package postgres provides chunk metadata and document fingerprint storage.
Package postgres provides chunk metadata and document fingerprint storage.
store/s3
Package s3 provides file storage using AWS S3.
Package s3 provides file storage using AWS S3.
subjectauth
Package subjectauth verifies delegated access tokens against local trust data.
Package subjectauth verifies delegated access tokens against local trust data.
testutil
Package testutil provides fixtures for service tests.
Package testutil provides fixtures for service tests.
testutil/docxtest
Package docxtest builds WordprocessingML package fixtures.
Package docxtest builds WordprocessingML package fixtures.
testutil/pgtest
Package pgtest provides empty PostgreSQL databases for tests.
Package pgtest provides empty PostgreSQL databases for tests.
textutil
Package textutil provides text normalization helpers used by the ingestion pipeline.
Package textutil provides text normalization helpers used by the ingestion pipeline.
tracing
Package tracing configures optional trace export and instruments service operations.
Package tracing configures optional trace export and instruments service operations.
wordprocessingml
Package wordprocessingml defines the schema identifiers used by Word packages.
Package wordprocessingml defines the schema identifiers used by Word packages.
worker
Package worker processes durable ingestion jobs under renewable leases.
Package worker processes durable ingestion jobs under renewable leases.
scripts
citationsupport command
Command citationsupport reports whether held-out calibration meets the live gate.
Command citationsupport reports whether held-out calibration meets the live gate.
cleanup command
Package main deletes, inspects, quarantines and releases document identities, and performs the explicit activation of checkpointed deletion.
Package main deletes, inspects, quarantines and releases document identities, and performs the explicit activation of checkpointed deletion.
evidenceeval command
Command evidenceeval measures scoped retrieval against an opted-in deployment.
Command evidenceeval measures scoped retrieval against an opted-in deployment.
fuzz command
Command fuzz lists the Go fuzz targets in the root module.
Command fuzz lists the Go fuzz targets in the root module.
grant-catalog command
Command grant-catalog prepares the metadata schema or imports operator entitlements.
Command grant-catalog prepares the metadata schema or imports operator entitlements.
langeval command
Lightweight evaluation harness comparing query outputs against a fixed representative set.
Lightweight evaluation harness comparing query outputs against a fixed representative set.
reconcile command
Package main reconciles stored vectors and original files with document ownership.
Package main reconciles stored vectors and original files with document ownership.
reindex command
Package main stages, verifies and activates vector generations without changing document identities.
Package main stages, verifies and activates vector generations without changing document identities.
simulate command
Package main exercises document ingestion, filtering and deletion against a running service.
Package main exercises document ingestion, filtering and deletion against a running service.
validate command
Package main validates document retrieval queries against the live server.
Package main validates document retrieval queries against the live server.
test
integration
Package integration exercises service boundaries and persistent storage.
Package integration exercises service boundaries and persistent storage.
tools
imagecheck command
Command imagecheck verifies the runtime image that `docker buildx build --output type=oci` writes.
Command imagecheck verifies the runtime image that `docker buildx build --output type=oci` writes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL