Skip to content

QA plan: Answer similarity eval — BERTScore and SentenceTransformers (#78)

Story: Answer similarity eval: BERTScore + SentenceTransformers (#78)
Feature: Retrieval-quality eval harness (#75)
Capability: Retrieval & generation API (#11)
Spec: specs/retrieval.md

TypeCoverage
Unit/query is called for each eval row the script does not skip, up to 3 attempts per row; the response’s answer and cited document ids are extracted correctly
UnitA question longer than /query’s 2,048-character limit is skipped without a call
UnitBERTScore F1 is computed per question; bert_f1_mean and bert_f1_median are floats in [0.0, 1.0]
UnitSentenceTransformers cosine similarity is computed per question; sentence_bert_cosine_mean and sentence_bert_cosine_median are floats in [0.0, 1.0] (raw scores below 0 are clamped to 0)
UnitOutput JSON contains at least the fields commit_sha, timestamp, bert_f1_mean, bert_f1_median, sentence_bert_cosine_mean, sentence_bert_cosine_median, evaluated_count, and per_question_results (per-question breakdown array)
UnitPer-question breakdown includes question, ground_truth_answer, generated_answer, bert_f1, sentence_bert_cosine for each row
Unitcollect exits 1 with a descriptive message when /query returns a non-200 status other than 502/503/504 (a 429 or 500 is a hard failure, not retried), or an HTTP 200 whose body is not a QueryResponse
UnitA question whose /query call times out, fails to connect, or returns 502/503/504 on every attempt is left unscored; score exits 0 when at least one question is scored
UnitAfter 3 consecutive unavailable questions, the remaining questions are marked unavailable without a /query call and a WARNING is logged; any question that gets an HTTP 200 from /query (an answer or a no-match result) resets the count, and a question skipped as too long does not
Unitscore exits 1 when no question is scored
UnitThe script runs as two steps: collect writes the rows and answers to an answers file, and score reads that file and writes the report; score exits 1 on a malformed answers file, and either step exits 1 when it cannot write its output file
Unit--api-url must be https:// (plain http:// only for localhost or 127.0.0.1), and --count is bounded to 1-100
UnitThe script mints an API key for the run with a quota covering every attempt and a one-day expiry, and revokes it when the queries finish, including after a failure
Unitcollect exits 1 when the eval table is empty
IntegrationAgainst a stubbed /query returning deterministic answers: output JSON is valid, bert_f1_mean, bert_f1_median, and sentence_bert_cosine_mean are in [0.0, 1.0], and two runs give reports that differ only in timestamp
Integrationcollect then score against local Postgres: the report file is valid JSON for the run’s commit, and the per-run key is live with its quota during collect and gone afterwards
IntegrationWith the pinned models on CPU, scoring the same pairs twice gives identical scores in [0.0, 1.0]
CI checkNo job with id-token: write installs or runs the eval group (Workflow Checks workflow, check_credential_free_builds.py); the score job has no environment and no id-token grant

Note: backend/eval/eval_answers.py is a CI script outside backend/src/rag_sample/. Coverage floors from RAG006 do not apply. Tests assert output format, metric range bounds, and repeatability, not specific score values.

  • Story #76 (corpus setup) merged; eval table seeded with ground-truth answers
  • QA document corpus ingested, including the eval rows’ contexts, so /query can retrieve them
  • Story #77 (retrieval eval) merged (establishes the reports/<commit-sha>/<timestamp>-<kind>.json key layout reused here)
  • /query endpoint deployed and accessible in QA env, or stubbed for local tests
  • bert-base-uncased and all-MiniLM-L6-v2 model weights reachable from the CI runner (Hugging Face at the pinned revisions, or the CI cache)
  • The QA eval CI role rag-sample-qa-eval-role and the rag-sample-eval bucket applied through infra/bootstrap, and the qa-eval GitHub environment holding secrets AWS_QA_EVAL_ROLE_ARN and QA_DB_SECRET_ARN and variables QA_DB_CLUSTER_ARN, QA_DB_NAME, and QA_API_URL (the QA api_endpoint)
  • All unit tests pass
  • The models-marked tests pass, not skip, when run by hand as part of a model upgrade, per the eval-answers runbook in rag-sample-app
  • Integration: script produces a valid JSON report with its metric fields in range against a stubbed /query
  • The Workflow Checks credential-free-builds check passes
  • collect exits 1 on an empty eval table and on a /query non-200 status other than 502/503/504; score exits 1 when no question is scored
  • QA env run: the collect, score, and upload jobs of eval-answers.yml run end to end against the deployed /query endpoint, and the report lands under s3://rag-sample-eval/reports/<commit-sha>/ ending -answers.json with content type application/json
  • Model download in CI completes within the job timeout

Unit and integration: local (integration tests also need local Docker Postgres, make db-up, for the eval rows and a real api_keys row), with a fake /query transport returning deterministic answers and the models either mocked or loaded from cache. The QA env run uses the live /query endpoint and real S3. No CI hard-fail on eval score.

pytest, unittest.mock for /query HTTP calls and the models. bert-score, sentence-transformers, and CPU-only torch in the backend’s eval dependency group; tests that load the real models carry the models marker and skip when the group is not installed. Docker Postgres is not required for unit tests (eval rows come from fixtures). In the QA env run, the collect job uses the QA eval CI role over OIDC for the eval rows and the run’s API key, the score job holds no credentials, and the upload job uses the role for the S3 report write with the runner’s AWS CLI. No job makes a direct Bedrock call; /query does.

  • Golden eval rows: three EvalRow instances, one whose ground-truth document is cited, one whose context is ingested but not cited, and one whose context is not ingested
  • Fake /query transport: a patched HTTP request function returning {"answer": "Fake answer.", "citations": [...]} per question, or answer: null with reason: "no_relevant_results"
  • Fake scorer: a mock AnswerScorer returning a fixed PairScore per pair
  • Answers file: the golden rows and answers written with collected_document
  • Commit SHA constant "abc1234", set as COMMIT_SHA for score
def test_score_writes_report_with_required_fields(score_wired) -> None:
# Given score wired to the golden answers file and a fake scorer
# When score runs
code = ea.main(score_wired["args"])
# Then it exits 0 and writes a report with every required field
assert code == 0
report = json.loads(score_wired["output"].read_text(encoding="utf-8"))
assert REQUIRED_FIELDS <= set(report)
assert len(report["per_question_results"]) == 3
assert 0.0 <= report["bert_f1_mean"] <= 1.0
assert 0.0 <= report["sentence_bert_cosine_mean"] <= 1.0
  • BERTScore and SentenceTransformers download about 510 MB of model weights on first use. The models are pinned to Hugging Face commit revisions and cached in CI under a key that changes with the pins; a cache miss adds the download to the job time.
  • Scores are repeatable on CPU at the pinned revisions for fixed answers, but a pair’s score can shift by about 1e-7 when batch composition changes. Do not use a specific score as a regression gate in CI.
  • Generated answers are only as repeatable as the generation model’s sampling settings, so live runs are compared by their means and medians, not per-question values.
  • The /query endpoint requires a valid bearer token. The script mints a per-run key; a rejected key (HTTP 401/403) must cause a clear non-zero exit, not a silent empty-answer result.