An Agent Eval CQRS sketch with a test project to run through.
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Apprehensive Adventurer 7f4d8d4253 Initial commit: eval-gated ingestion sketch
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 23:43:01 +00:00
Evals.Tests Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00
Ingestion Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00
Ingestion.Functions Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00
Ingestion.Local Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00
.gitignore Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00
README.md Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00
schema.sql Initial commit: eval-gated ingestion sketch 2026-11-22 23:43:01 +00:00

Eval-gated ingestion sketch (C#)

A small example of how the different kinds of evals fit around an LLM step in a data ingestion pipeline (Snowflake / Microsoft Fabric target). It is a sketch, not production code, but it compiles, the offline tests pass, and the live evals have been run against a local Ollama model. The Microsoft.Extensions.AI.Evaluation calls compile against package version 11.0.1.

Layout

The code follows the C# standards in ../coding-standards/csharp: one folder per role, an interface for every service (in Abstractions/), implementations in Services/, records in Models/, options and the single ConfigureServices registration method in Configuration/, primary constructors with PascalCase parameters, and all file access through IFileSystem.

Ingestion/            class library
  Abstractions/           IChunkEnricher, IGroundednessJudge, IGuardrails, IIngestionPipeline,
                          IIngestionMessageHandler, IIngestionSink, IInMemorySink
  Services/               ChunkEnricher (the LLM step), Guardrails (deterministic checks), GroundednessJudge,
                          IngestionPipeline (enrich -> guardrail -> route -> sampled judge),
                          IngestionMessageHandler (raw payload -> validated message -> pipeline), InMemorySink
  Models/                 records: Chunk, EnrichmentResult, EnrichedRecord, QuarantineRecord, EvalScore,
                          JudgeResult, IngestionMessage (the queue message contract)
  Configuration/          IngestionOptions, ConfigureServices(IngestionOptions)
  Exceptions/             InvalidIngestionMessageException
Ingestion.Functions/  Azure Functions (isolated worker) host for the queue
  IngestChunkFunction.cs  queue trigger; passes the raw payload to IIngestionMessageHandler, nothing else
  Program.cs              builds the host and calls ConfigureServices(AppOptions)
  Abstractions/, Services/  IChatClientFactory / ChatClientFactory (Ollama or Azure OpenAI),
                          LoggingIngestionSink (PLACEHOLDER: only logs; replace with Snowflake / Fabric)
  Configuration/          AppOptions (read from app settings), ConfigureServices(AppOptions)
  host.json                      queue settings (retries, batch size)
  local.settings.sample.json     Ollama settings; copy to local.settings.json (git-ignored)
  local.settings.azure.sample.json  the same for Azure OpenAI
Ingestion.Local/      local emulation of queue + function runtime (console app)
  Program.cs              builds the container, resolves IQueueEmulator, runs it
  Abstractions/, Services/  IMessageQueue / InMemoryQueue (FIFO, delivery counts, poison list),
                          IQueueFileLoader / QueueFileLoader (reads the queue JSON via IFileSystem),
                          IQueueRunner / QueueRunner (stands in for the Functions trigger: retries, then poison),
                          IQueueEmulator / QueueEmulator (load, drain, print)
  Models/                 QueueMessage, PoisonMessage, RunReport
  Configuration/          AppOptions (queue file, --max-dequeue), ConfigureServices(AppOptions)
  sample-queue.json       3 valid messages and 3 deliberately bad ones
Evals.Tests/          xUnit project, one <Type>Tests.cs per class under test
  GoldenSetTests.cs                live evals: precision/recall + groundedness thresholds (needs a model)
  IngestionMessageTests.cs         offline: queue contract validation
  IngestionMessageHandlerTests.cs  offline: payload -> pipeline -> sink, and what throws
  IngestionPipelineTests.cs        offline: routing to enriched / quarantine, with a scripted fake model
  SqlSinkTests.cs                  offline: pipeline -> SqlSink -> in-memory SQLite built from schema.sql
  QueueFileLoaderTests.cs          offline: queue file parsing (MockFileSystem)
  QueueRunnerTests.cs              offline: retry, poison and cancellation behavior
  Support/                         ScriptedChatClient (fake model), TestPipelines, SqlSink, TestClients
  golden.json                      hand-labeled examples for the live evals
  ollama.runsettings               local defaults for running the live evals against Ollama
schema.sql            enriched_chunks, quarantine, eval_scores + drift queries

How it fits together

 Source documents
        |
        v
  [ Chunker ]   the producer; not in this repo
        |
        |  IngestionMessage (JSON): schemaVersion, topic, chunkId,
        |  documentId, text   (+ optional correlationId, enqueuedAt)
        +-------------------------------------------------+
        v                                                 v
 +--------------------------------+      +--------------------------------+
 | Azure Storage queue            |      | InMemoryQueue                  |
 | "ingestion-chunks"             | OR   | loaded from queue.json by Main |
 +--------------------------------+      +--------------------------------+
                  |                                       |
   Azure Functions runtime                 QueueRunner (Ingestion.Local)
   retries up to maxDequeueCount           retries up to --max-dequeue
                  |                                       |
                  +-------------------+-------------------+
= COMMAND SIDE =======================|=========================================
                                      v
                      +---------------+---------------+
                      | IngestChunkFunction           |  Ingestion.Functions
                      | thin host: raw payload only   |
                      +---------------+---------------+
                                      v
                      +---------------+---------------+
                      | IngestionMessageHandler       |  Ingestion
                      | parse + validate contract     |  (domain service)
                      +---------------+---------------+
                                      |  invalid payload: throws
                                      |  InvalidIngestionMessageException
                                      v  valid: message.ToChunk()
                IngestionPipeline.ProcessAsync(topic, chunk)
                                      |
                                      v
            ChunkEnricher (IChatClient -> Ollama / Azure OpenAI)
                                      |
                +---------------------+-------------+
                | model error, null output,         | passes
                | or guardrail failure              | guardrails
                v                                   v
      WriteQuarantineAsync                 WriteEnrichedAsync
                |                                   | relevant and ~5% sampled
                |                                   +----------------+
                |                                   |                v
                |                                   |        GroundednessJudge
                |                                   |                v
                |                                   |       WriteEvalScoreAsync
                |                                   |                |
================|= WRITE MODEL (Snowflake / Fabric) |================|==========
                v                                   v                v
         +------------+                   +-----------------+  +-------------+
         | quarantine |                   | enriched_chunks |  | eval_scores |
         +------------+                   +-----------------+  +-------------+
                |                                   |                |
================|= QUERY SIDE (read-only) ==========|================|==========
                v                                   v                v
      quarantine-rate alert                 search / RAG / BI  score-drift alert

How to read it:

  • Command side: the function (or the local emulator), the domain handler and the pipeline. A queue message goes in; rows come out through IIngestionSink. Nothing is returned to the producer.
  • Write model: the three tables in schema.sql. Query side: read-only consumers of those tables. This repo has no query-side code beyond the two monitoring queries at the bottom of schema.sql.
  • Data problems (model error, unparseable output, guardrail failure) are handled inside the pipeline and written to quarantine; the message is consumed.
  • Contract violations (bad JSON, missing field, wrong version) and infrastructure failures (sink down) throw out of the function. The queue retries, then moves the message to the poison queue. Retries are not idempotent yet, so the real sink should upsert on chunk_id + prompt_version.
  • Sinks: the function host registers LoggingIngestionSink (a placeholder that only logs); Ingestion.Local and most tests use InMemorySink; SqlSink writes the schema.sql tables (SQLite in tests).

What the test assets stand in for:

 CI ONLY (not part of the runtime path)

 +-------------+     +----------------+     calls the same ChunkEnricher and
 | golden.json | --> | GoldenSetTests | --> GroundednessJudge against a live
 +-------------+     +----------------+     model; compares with expectedRelevant

 Offline tests (no model): a scripted fake IChatClient drives the same handler,
 pipeline and queue emulator, writing to InMemorySink or to an in-memory SQLite
 database created from schema.sql.

golden.json is a labeled test fixture, not a queue message: its expectedRelevant answer key does not exist at runtime.

Running the tests

Package references are already in the .csproj files; dotnet test restores them.

The projects target net10.0.

Offline tests (no model, no credentials)

cd Evals.Tests
dotnet test --filter "Category!=Eval"
  • IngestionPipelineTests runs the real enricher, guardrails and pipeline against InMemorySink, with a scripted IChatClient in place of the model.
  • SqlSinkTests runs the pipeline into a SQLite in-memory database (Data Source=:memory:) created from schema.sql, then queries the tables and the two monitoring queries. The database lives only for the length of each test. SQLite is not Snowflake: it ignores the Snowflake column types (VARIANT, ARRAY, TIMESTAMP_TZ), and the tests rewrite DATE_TRUNC('day', x) to date(x). They show the sink and schema agree, not that the DDL is valid on Snowflake or Fabric.

Live evals (call a real model)

These are tagged Category=Eval and need a model. TestClients.cs picks the backend from environment variables.

Ollama (used when OLLAMA_ENDPOINT is set). Evals.Tests.csproj points at ollama.runsettings, so a plain dotnet test already uses it. Edit that file first: endpoint and model names.

cd Evals.Tests
dotnet test --filter Category=Eval

The settings in the file override variables already set in your shell. To use a different settings file (for example one for Azure OpenAI), pass it with the --settings option of dotnet test. IDE test runners need the file selected in their own settings.

Variable Meaning
OLLAMA_ENDPOINT e.g. http://localhost:11434
OLLAMA_ENRICH_MODEL model for enrichment (required), must already be pulled
OLLAMA_JUDGE_MODEL model for the judge; defaults to the enrichment model. Use a stronger one if you can

Azure OpenAI (used otherwise):

Variable Meaning
AZURE_OPENAI_ENDPOINT required
AZURE_OPENAI_ENRICH_DEPLOYMENT required
AZURE_OPENAI_JUDGE_DEPLOYMENT required; ideally a stronger model than the enrichment one
AZURE_OPENAI_API_KEY optional; if unset, DefaultAzureCredential is used

Without any of these set, the live evals fail with a message naming the missing variable.

Notes for local models:

  • Structured output: ChunkEnricher needs valid JSON. Small models sometimes fail this, which shows up as a null result in the tests.
  • The groundedness judge expects a specific response format, and weak judges give noisy scores. The thresholds in GoldenSetTests.cs (0.80 precision, 0.80 recall, 4.0 groundedness) may need tuning per model.

Queue ingestion (serverless function)

producer (chunker) --IngestionMessage JSON--> queue --> IngestChunkFunction --> IngestionMessageHandler
                                                                                      |
                                                                    validate contract, map to Chunk
                                                                                      v
                                                                            IngestionPipeline --> sink

The function is a thin host. All logic lives in the Ingestion library so it can be tested without the Functions runtime and hosted elsewhere (Lambda, a worker service).

Message contract (IngestionMessage, schema version 1)

{
  "schemaVersion": 1,
  "topic": "loading data into Snowflake",
  "chunkId": "doc-42#0007",
  "documentId": "doc-42",
  "text": "The passage to classify and summarize...",
  "correlationId": "optional trace id",
  "enqueuedAt": "2026-11-22T10:15:00Z"
}
Field Required Rules
schemaVersion yes must equal 1
topic yes non-empty, at most 500 chars
chunkId yes non-empty, at most 256 chars. Must be stable and unique per chunk: it keys all three tables and is what lets retries be deduped
documentId yes non-empty, at most 256 chars
text yes non-empty, at most 12,000 chars (Azure Storage queue messages are limited to 64 KB)
correlationId, enqueuedAt no carried for tracing; not used by the pipeline yet

Unknown fields are ignored so producers can add fields without breaking consumers. Changing or removing a field, or changing its meaning, needs a new schemaVersion.

golden.json is not this contract. It is a test fixture with an answer key (expectedRelevant) that never exists at runtime.

Failure handling

Failure Where it goes
LLM error, unparseable output, guardrail failure quarantine table; the message is consumed normally
Contract violation (bad JSON, missing field, wrong version) InvalidIngestionMessageException; the runtime retries up to maxDequeueCount (5, in host.json), then moves it to the ingestion-chunks-poison queue
Infrastructure failure (sink down, cancellation) exception; same retry, then poison queue

Contract violations are retried even though retrying cannot help; that is a limit of the queue trigger. If the wasted retries matter, have the function catch the exception, log it, and send the payload to a dead-letter store itself.

Running it locally without Azure (queue emulation)

Ingestion.Local emulates the queue and the Functions runtime in one process, so you can try the whole path with no Azure account, storage emulator or Functions tooling:

dotnet run --project Ingestion.Local -- [path/to/queue.json] [--max-dequeue 5]

Model settings come from Ingestion.Local/appsettings.json (Ollama, qwen2.5-coder-8k), then an optional git-ignored appsettings.local.json, then environment variables (highest priority). For Azure OpenAI, copy appsettings.azure.sample.json to appsettings.local.json and fill it in; its empty OLLAMA_ENDPOINT switches Ollama off.

With no path it uses sample-queue.json. The queue file is a JSON array, one element per queue message:

  • an object is sent as the message body as-is (write it like a producer would);
  • a string is used verbatim as the body, so you can include malformed payloads on purpose.

Main loads the file into an InMemoryQueue, then QueueRunner calls the real IngestChunkFunction for each message and imitates the host.json behavior: a function that returns completes the message; one that throws is retried (back at the end of the queue) until --max-dequeue deliveries, then the message goes to a poison list. It prints each delivery, then what landed in enriched_chunks, quarantine and the poison queue. The exit code is 3 if anything was poisoned.

Differences from the real thing: one message at a time (no batching or concurrency), no visibility-timeout delay between retries, and the sink is an in-memory one that only exists for the run. The Azure binding itself ([QueueTrigger]) is not exercised.

Running the function on Azure Functions

Ingestion.Functions builds with dotnet build but has not been run against a real queue or the Functions host. To try it you need Azure Functions Core Tools and a storage emulator (Azurite) or a storage account:

cd Ingestion.Functions
cp local.settings.sample.json local.settings.json   # Ollama; use local.settings.azure.sample.json for Azure OpenAI
func start

Settings (in local.settings.json locally, app settings when deployed):

Setting Meaning
IngestionQueue storage connection string for the queue (UseDevelopmentStorage=true for Azurite)
OLLAMA_ENDPOINT, OLLAMA_ENRICH_MODEL use Ollama (when the endpoint is set)
AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_ENRICH_DEPLOYMENT, AZURE_OPENAI_API_KEY otherwise Azure OpenAI; the key is optional (managed identity / DefaultAzureCredential)

The sink is LoggingIngestionSink, which only logs, so nothing is persisted until you implement IIngestionSink for Snowflake or Fabric. The sampled groundedness judge is not wired into the function; run it as a separate job. Retries are not idempotent yet: a retry after a partial failure writes the same chunk again, so the real sink should upsert on chunk_id + prompt_version.

The golden set

golden.json has 24 items for the topic "loading data into Snowflake", 12 relevant and 12 not. They are a mix of:

  • clear positives (loading mechanisms: COPY INTO, Snowpipe, Kafka connector, MERGE from CDC, recovery),
  • clear negatives (unrelated company text),
  • borderline negatives that mention Snowflake or loading without being about loading into Snowflake (query tuning, BigQuery loads, cost control, access control).

The labels were drafted by the assistant that built this repo and need a human review. Judgment calls to look at first: g23 (unloading data out of Snowflake, labeled not relevant) and g24 (dbt tests that validate loads, labeled relevant). Relevant passages are deliberately several hundred characters long, because the summary_not_shorter_than_source guardrail cannot pass on one-sentence passages.

When production produces a failure, add it here.

Which eval runs where

Layer Where What
Deterministic checks Every record, at ingestion Guardrails.Check; failures go to quarantine
Reference-based (precision/recall) CI + release gate GoldenSetTests against golden.json
LLM judge (groundedness) CI, plus ~5% sample in production GroundednessJudge; scores go to eval_scores
Human review Periodic Spot-check judge scores and quarantine; add failures to golden.json

Things to do next

  • Implement IIngestionSink for Snowflake or Fabric and register it in Ingestion.Functions/Program.cs (write the three tables in schema.sql). SqlSink is a reference for the column mapping, but it binds simple types for SQLite; bind native types for a real target.
  • Move the sampled judge out of the ingestion path (queue or scheduled job) so it adds no latency.
  • The pipeline-with-judge path (sampled WriteEvalScoreAsync from the pipeline) has no offline test, because GroundednessEvaluator expects a specific response format that is hard to fake.
  • Keep growing golden.json with real failures from production.
  • Alert on the two queries at the bottom of schema.sql (score drift, quarantine rate).