TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
13.2 kB
"""Project-wide settings: paths, model names, retrieval knobs and eval cost weights.
Everything tunable lives here so experiments change one file, and the README can
point at a single place when explaining a number.
"""
import os
from pathlib import Path
from dotenv import load_dotenv
# --- Paths -------------------------------------------------------------------
# Repo root = two levels above this file (src/coveragecheck/config.py).
# COVERAGECHECK_ROOT overrides it, e.g. inside the Docker image.
ROOT = Path(os.environ.get("COVERAGECHECK_ROOT", Path(__file__).resolve().parents[2]))
DATA_DIR = ROOT / "data"
MANIFEST_PATH = DATA_DIR / "manifest.csv" # committed: the corpus definition
RAW_DIR = DATA_DIR / "raw" # ignored: downloaded PDFs/HTML
PARSED_DIR = DATA_DIR / "parsed" # ignored: cached Docling JSON
INDEX_DIR = DATA_DIR / "index" # ignored: parquet + .npy indexes
EVALS_DIR = ROOT / "evals"
QUESTIONS_PATH = EVALS_DIR / "questions.jsonl" # committed, hand-written gold set
DEV_PROBES_PATH = EVALS_DIR / "dev_probes.jsonl"
HELDOUT_PATH = EVALS_DIR / "heldout.jsonl" # the final test set (owner, 2026-11-23)
# What each question file IS, for the report banner (owner, 2026-11-22: the draft gold
# shaped C's design, so it is a development set; the held-out set is the final test).
QUESTION_SETS = {
"questions.jsonl": (
"development set",
"The question set is the provisional DRAFT gold set, now a DEVELOPMENT set: it "
"shaped System C's design (SPEC: gold exposure log), so C's numbers here are "
"optimistic. The held-out set is the final test.",
),
"heldout.jsonl": (
"held-out set",
"The question set is the HELD-OUT set (249 questions), written and reviewed by "
"Claude Opus 5.5 agents blind to every system output (LLM-written gold, not the "
"owner's) and opened only after A, B and C were frozen: the final test.",
),
} # committed: Step 3 tuning only, never reported
GRADES_PATH = EVALS_DIR / "grades.jsonl" # committed: hand grades are expensive to redo
RUNS_DIR = EVALS_DIR / "runs" # ignored: raw per-run parquet files
REPORT_DIR = EVALS_DIR / "report" # committed: tables and charts for the README
LLM_CACHE_DIR = ROOT / ".cache" / "llm" # ignored: cached LLM replies (llm.py)
# fastembed model files. Not the OS temp dir (its default): cleanup there forces a
# re-download. FASTEMBED_CACHE_PATH overrides it; Docker bakes the models in at build.
MODEL_CACHE_DIR = Path(os.environ.get("FASTEMBED_CACHE_PATH", ROOT / ".cache" / "fastembed"))
EMBED_CACHE_DIR = ROOT / ".cache" / "embeddings" # ignored: one vector per (model, text)
# --- Models ------------------------------------------------------------------
EMBED_MODEL = "BAAI/bge-small-en-v1.5"
RERANK_MODEL = "Xenova/ms-marco-MiniLM-L-6-v2"
# --- Chunking ----------------------------------------------------------------
MAX_CHUNK_TOKENS = 400 # HybridChunker limit (System B/C)
NAIVE_CHUNK_CHARS = 800 # fixed-size chunks (System A)
NAIVE_CHUNK_OVERLAP = 100
NAIVE_COVER_MIN_CHARS = 40 # eval only: a window "covers" a section if it holds this much
# --- Retrieval ---------------------------------------------------------------
RRF_K = 60 # Reciprocal Rank Fusion: score = sum(1 / (RRF_K + rank))
NAIVE_TOP_K = 5 # System A: dense top-5
CANDIDATE_K = 30 # B/C: candidates per retriever before fusion
MAX_XREF_EXPANSION = 4 # B/C: extra chunks added by cross-reference expansion
# B/C: a cited section longer than this (full subtree text) is not expanded: "Section 7
# of the policy" (18.8k chars) points at no particular rule, and its most query-similar
# chunk is just one more dense hit. Threshold from the 2d audit (set before Step 6);
# 6a measured: 80 of 212 expansions were such targets, none held a gold section.
XREF_MAX_TARGET_CHARS = 8000
XREF_MAX_RANGE = 15 # "sections 5 to 11": at most this many targets from one range
XREF_TITLE_MIN_RATIO = 90 # rapidfuzz ratio for a quoted OAP 1 Section title in an OPCF
RERANK_TOP_K = 8 # B/C: chunks kept after cross-encoder rerank
# B/C: how many fused (RRF) candidates the cross-encoder scores. Step 6a, dev probes
# (owner's rule: probes tune, gold only confirms): depth 15 and 20 tie (hit@8 1.00,
# MRR .73/.72) and beat no rerank (.91/.68) and reranking all (.96/.69, which lets
# long off-topic chunks back in); 15 is cheaper (~70 ms per candidate on this laptop).
RERANK_DEPTH = 15
# C (Step 7): one LLM "judge" call replaces the cross-encoder (owner decisions 3-4).
# Depth 20: the fused top-20 holds 44 of 53 gold sections (top-15 43, B shipped 42);
# ~25k chars (~11k tokens) median. 7b measures 15 vs 20 on the dev probes only.
JUDGE_DEPTH = 20
JUDGE_KEEP = 8 # passages kept before expansion, as B's RERANK_TOP_K
# Grades 1-3 (TREC/UMBRELA-style): 3 states a needed rule, 2 a needed condition or
# context, 1 on topic but not needed. Kept: >= this. 1 = recall first (the answer model
# can ignore an extra passage, not use a missing one): a PRIOR, not a measured result.
# 7b evidence is thin (n=1): on 1 of 23 dev probes min grade 2 dropped a needed section
# the judge graded 1; grade 1 adds ~1 passage per question (14 of 15 were filler).
# The grade is then mainly a sort key. Median shown 5 (B: 11).
JUDGE_MIN_GRADE = 1
MAX_REQUIREMENTS = 5 # the judge prompt asks for 1 to 5; more are dropped (a repair)
MAX_SUBQUERIES = 3 # second round: at most this many queries (uncovered requirements)
RESEARCH_DEPTH = 20 # second round: at most this many NEW candidates judged
# --- Lexical index (BM25, Step 3a) ---------------------------------------------------
BM25_DIR = INDEX_DIR / "bm25_b" # System B's BM25 over chunks.embed_text
BM25_K1 = 1.5 # bm25s defaults (Lucene variant); term-frequency saturation
BM25_B = 0.75 # length normalization
BM25_DOTTED_ANCESTORS = False # "6.2.1" also emits "6.2" and "6"; decided on dev probes (3d)
# --- Dense index (embeddings, Step 3b) -------------------------------------------------
DENSE_B_DIR = INDEX_DIR / "dense_b" # System B: chunks.embed_text
DENSE_A_DIR = INDEX_DIR / "dense_a" # System A: naive_chunks.text
# 1 = no padding. fastembed pads a batch to its longest text; measured on this CPU
# (192 texts): batch 256 69.5 s, 16 40.8 s, 1 21.9 s, identical vectors.
EMBED_BATCH_SIZE = 1
EMBED_SAVE_EVERY = 128 # new vectors between cache saves (an interrupted build keeps them)
# bge's query instruction ("Represent this sentence for searching relevant passages: ")
# is NOT added by fastembed. "" = off; 3d decides on the dev probes. Never on passages.
EMBED_QUERY_PREFIX = ""
# --- Answer LLM (Step 5a: llm.py) ----------------------------------------------
# Owner's decision (5a): a fast, modest model so the retrieval design shows, not the
# model. Benchmarked on 5 real System A prompts (2026-11-22): gemini-4-hydrogen
# 127-256 s/call; gemini-3.8-flash 13/13 x 503; gemini-3.5-flash 21-35 s (700-2,900
# thinking tokens) and confidence 0.95 on every answer; Claude Haiku 5.5 2-8 s, 0
# transient errors in 10 calls, confidence 0.4-0.9. The model name is pinned in .env
# (ANTHROPIC_MODEL), read by llm_model().
# Haiku 5.5 always thinks a little; "low" vs "medium" measured the same latency
# (~5 s) with ~20% fewer output tokens.
LLM_EFFORT = "low"
# Haiku 5.5 list prices, USD per million tokens (owner, Step 5): cost estimates and the
# spend reports (7b judge_probes). Not the eval's cost metric (COST_WEIGHTS).
LLM_PRICE_IN_PER_MTOK = 0.10
LLM_PRICE_OUT_PER_MTOK = 0.50
LLM_MAX_TOKENS = 4000 # longest benchmark reply: 1,634 tokens (effort medium)
LLM_TIMEOUT_S = 60.0 # per HTTP request; the slowest benchmark call took 8.2 s
LLM_MAX_REASKS = 1 # after an invalid reply, ask again once with the error (2 calls max)
LLM_API_RETRIES = 4 # transient errors (429, 5xx, connection) retried with backoff
LLM_RETRY_BASE_S = 2.0 # backoff: 2, 4, 8, 16 s ...
LLM_RETRY_MAX_S = 30.0 # ... capped here
# JSON-schema keywords the API rejects in structured outputs (measured: "For 'number'
# type, properties maximum, minimum are not supported"). They are removed from the
# schema SENT; Pydantic still enforces them on the reply (a breach -> reask).
LLM_UNSUPPORTED_SCHEMA_KEYS = frozenset(
{"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf"}
)
# --- Citation check ----------------------------------------------------------
CITATION_MIN_RATIO = 90 # rapidfuzz partial_ratio threshold
CITATION_MIN_QUOTE_CHARS = 30 # shorter quotes match almost anything, so flag them
# --- Web app (Step 9: FastAPI + React; web/ holds the frontend) ----------------
WEB_DIST_DIR = ROOT / "web" / "dist" # ignored: `npm run build` output, served by the API
WEB_SYSTEMS = ("a", "b", "c") # offered in the app (the dummy never is)
WEB_LLM_TIMEOUT_S = 30.0 # per request (evals: 60 s); a visitor should not wait minutes
WEB_LLM_API_RETRIES = 1 # evals: 4 (worst case ~5.5 min per call: 5b handoff)
WEB_CACHE_ENTRIES = 256 # LLM replies kept IN MEMORY only: visitors' questions never hit disk
WEB_MAX_RUNNING = 2 # questions answered at once on the 2-core box; more get "busy"
WEB_DEADLINE_S = 150.0 # a question still running after this ends with an error event
WEB_PING_S = 10.0 # keep-alive event while a step runs (proxies drop silent streams)
WEB_DAILY_QUESTIONS = 100 # per UTC day: ~$0.33 worst case at C's cost (owner, 10b; was 300)
WEB_CLIENT_RUNNING = 1 # per visitor (9a audit: one visitor could hold every slot)
WEB_CLIENT_DAILY = 30 # per visitor per UTC day (nor spend the whole day's budget)
WEB_HOST = "127.0.0.1" # the HOST / PORT environment variables win (Docker: 0.0.0.0)
WEB_PORT = 8000
WEB_SHUTDOWN_S = 10 # graceful shutdown cap: open streams would hold it to the deadline
WEB_MAX_QUESTION_CHARS = 1000
WEB_EXCERPT_CHARS = 1500 # source text shown on each side of a highlighted quote
# Follow-ups (web/followup.py): the rewrite reads the last turns, earlier answers clipped
WEB_HISTORY_TURNS = 4
WEB_HISTORY_ANSWER_CHARS = 1200 # per earlier answer in the rewrite prompt
WEB_HISTORY_MAX_ANSWER_CHARS = 20_000 # rejected above this (a request is untrusted)
WEB_HISTORY_MAX_TURNS = 20 # turns a request may carry (only the last WEB_HISTORY_TURNS are read)
WEB_DATA_DIR = ROOT / "web" / "public" / "data" # committed: JSON the static pages read
# The held-out runs the app's recorded examples and numbers come from (SPEC "Held-out
# results"): the official run of each system, graded.
WEB_HELDOUT_RUNS = {
"a": "a-20261123-195054.parquet",
"b": "b-20261123-174220.parquet",
"c": "c-20261123-182331.parquet",
}
# --- Eval question set ---------------------------------------------------------
# Owner's decision: 63 questions, split by category (SPEC Step 4).
QUESTION_TARGETS: dict[str, int] = {"single": 25, "multi": 20, "date": 8, "unanswerable": 10}
# The held-out set (owner, 2026-11-23): planned 60/90/40/50 = 240, written and reviewed
# by Opus agents; review may drop questions, so the check is a floor, not exact counts.
HELDOUT_MIN_QUESTIONS = 200
# --- Eval harness dummy (Step 4b: a retrieval-only System B, no LLM) ------------
DUMMY_ABSTAIN_BELOW = 0.9 # abstain when top RRF score / best possible is below this
DUMMY_QUOTE_CHARS = 200 # the dummy cites the first N characters of its top chunk
# --- Hand grading (Step 4c) ------------------------------------------------------
GRADE_SHUFFLE_SEED = 4 # blind grading: answers from all runs mixed in a fixed order
# --- Metrics (Step 4d) -----------------------------------------------------------
BOOTSTRAP_RESAMPLES = 10_000 # 10k paired resamples of 63 questions: ~8 ms
BOOTSTRAP_SEED = 0
THRESHOLD_STEP = 0.05 # threshold curve: t = 0, 0.05, ..., 1
# Declared BEFORE any result (4d audit): the comparisons the README leads with,
# as (new system, baseline). Every other pair is reported too, after these.
PRIMARY_COMPARISONS = [("c", "b"), ("b", "a")]
# --- Eval cost weights (an E&O-loss proxy; see README) -------------------------
# Keys: (answerable, outcome). Lower is better.
COST_WEIGHTS: dict[tuple[bool, str], int] = {
(True, "pass"): 0,
(True, "abstain"): 1, # unhelpful, but the broker just looks it up
(True, "fail_low"): 5, # wrong answer on a low-stakes question
(True, "fail_high"): 20, # wrong answer that could leave a client uncovered
(False, "abstain"): 0, # correctly says "I can't determine"
(False, "answered"): 20, # confidently answers what the documents don't support
}
def llm_model() -> str:
"""Return the pinned answer model (ANTHROPIC_MODEL) from .env or the real environment.
Read on demand, not at import time, so tests and offline steps (download,
parse, index) work without a .env file. load_dotenv never overrides a variable
that is already set, so Docker / Hugging Face secrets take precedence. It also
puts ANTHROPIC_API_KEY into the environment, where the anthropic SDK reads it.
"""
load_dotenv(ROOT / ".env")
model = os.environ.get("ANTHROPIC_MODEL")
if not model:
raise RuntimeError("ANTHROPIC_MODEL is not set; add it to .env (see .env.example).")
return model