Quest 01 / 02 · CapstoneTier 03 · Monthly

Bounty boards / Monthly · December 2026

Build a two-model patch review workbench with Semgrep, Pydantic AI and MLflow

  • static analysis
  • structured LLM outputs
  • LLM-as-a-judge evaluation
  • experiment tracking
  • reactive Python apps
  • diff parsing
  • CI regression testing
  • Time34 hours
  • Stages11
  • BoardDecember 2026

Overview

Build a local Python patch review service that runs Semgrep Community Edition before asking two Ollama coding models for typed Pydantic AI verdicts. Matching verdicts settle in SQLite while judge disagreements route to a reactive marimo triage app. A local MLflow server records split hashes, prompts, execution traces, latency percentiles, and held-out precision across two review workflows.

  • Reproducible Parquet benchmark splits from CTSSB-1M, 136K Python Problems, and the 1.3M AI Commits dataset with zero patch-ID overlap.
  • Offline Semgrep Community Edition scanner paired with two Ollama coding models returning validated Pydantic AI verdict objects.
  • Local MLflow tracking runs comparing two review workflows on fixed models with full traces, latency percentiles, and schema retry counts.
  • SQLite review ledger and reactive marimo triage notebook that writes human overrides immediately and compares abstention by authorship cohort.
  • Pytest suite, 50-patch deterministic CI fixture enforcing 98 percent schema validity, and a held-out test report with five documented failure classes.
01SETUP2 hoursSet up the repositor...02DATA2 hoursDownload all three K...03DATA4 hoursBuild seeded Parquet...04BUILD3 hoursBuild the offline Se...05BUILD4 hoursBuild the typed Pyda...06BUILD2 hoursPersist verdicts and...07TEST4 hoursCompare two review w...08BUILD4 hoursBuild the reactive m...09TEST3 hoursRun the frozen held-...10TEST3 hoursAdd unit tests, a 50...11SHIP3 hoursPublish the technica...
DATAKaggle DatasetsSTOREParquet SplitsTOOLSemgrep CE ScanMODELTwo Ollama JudgesCODEUnanimous RouterSTORESQLite LedgerUSERmarimo Triage AppTOOLLocal MLflow Serverclean + stratifycandidate patchesdiff + JSON findingstyped PatchVerdictverdict or abstainabstained queuehuman overrideautolog tracesmetrics + params
Candidate Python patches pass through offline Semgrep CE and two local Ollama judges; unanimous calls settle in SQLite while disagreements move to marimo and traces log to MLflow.

Tools

  • Semgrep

    The Community Edition engine uses LGPL-2.1. The AppSec Platform combines commercial analysis and proprietary rules with free and paid hosted plans; AI credits and contributor limits depend on the plan.

  • Ollama

    Ollama's runtime uses the MIT license, while model weights have their own licenses. Local execution has no Ollama usage charge; optional cloud inference uses metered credits, subscriptions and enterprise terms.

  • Pydantic AI

    Pydantic AI uses the MIT license and is free to use. Model providers, deployment infrastructure and optional Pydantic commercial services have separate terms and costs.

  • MLflow

    The MLflow project is free Apache 2.0 software and can run on a local server. Managed hosting, storage and external model calls have separate charges.

  • marimo

    The local marimo notebook is free Apache 2.0 software. Hosted products, optional assistants and remote data services have separate terms; their paid entitlements are not established here.

Datasets

  • CTSSB-1M Dataset Kaggle

    Supplies single-statement Python bug fixes so the workbench can test whether Semgrep and both judges distinguish broken lines from clean repairs.

    MIT · 1.2 GB · updated 2026-08-10

  • 136K Python Problems: Pass/Fail Code Benchmark Kaggle

    Provides pass-and-fail Python coding problems across difficulty tiers for measuring workflow completion rates and two-model judge agreement.

    CC0: Public Domain · 185.8 MB · updated 2026-11-23

  • Who Writes AI Code? 1.3M Open-Source AI Commits Kaggle

    Supplies open-source commit histories with AI coding-agent labels to calibrate metadata risk signals and stratify review load by authorship cohort.

    Attribution 4.0 International (CC BY 4.0) · 304.6 MB · updated 2026-10-01

Before you begin

Python 3.11 or newer

Python is free to install. Check with python --version; the current Kaggle CLI notes Python 3.11+, and Pydantic AI, MLflow, and marimo all support it.

Git and pipx or uv

Git, pipx, and uv are free to install. Use Git to clone the open semgrep-rules repository locally and pipx or uv to install Semgrep Community Edition in an isolated environment.

Ollama local runtime and disk space

Local Ollama execution is free. Reserve about 10 GB of disk space for qwen2.5-coder:7b and deepseek-coder:6.7b, plus 16 GB of RAM recommended (smaller 3B and 1.3B tags work on 8 GB machines).

Kaggle account and API token

A Kaggle account is free. Generate an API token to download the three public benchmark datasets (about 1.7 GB compressed) with the Kaggle CLI.

Python, SQL, and Git basics

No paid tools are needed here. You should be comfortable using virtual environments, reading unified diffs, writing pandas scripts, and running SQLite queries from a terminal.

GitHub repository (optional for CI)

Public repositories receive free standard runner minutes; private repositories draw from account runner-minute quotas.

Stage 01 · setup2 hours

Set up the repository, local models, and offline rules

Create the project layout, install Python dependencies and Semgrep Community Edition, clone open Python rules locally, and pull two coding models in Ollama.

Every tool in this workbench runs on your own machine with zero paid API keys. Keeping the Semgrep rules, model weights, SQLite ledger, and MLflow server local makes every evaluation run reproducible and inspectable.

LayoutProject tree
patch-review-workbench/
  .github/
    workflows/
      ci.yml  # Runs pytest and 50-patch fixture
  app/
    triage_app.py  # Reactive marimo triage notebook
  config/
    dataset_schema.json  # Verified column map from pandas
  data/
    raw/  # Ignored Kaggle downloads
    splits/  # Seeded Parquet splits and hash manifest
  scripts/
    inspect_datasets.py  # Inspects headers before loaders
    build_splits.py  # Builds splits and checks overlap
    run_workflows.py  # Compares two workflows in MLflow
    eval_held_out.py  # Single frozen held-out test pass
  src/
    review_bench/
      splits.py  # Dataset loaders and unified diffs
      semgrep_runner.py  # Offline Semgrep CE wrapper
      models.py  # Pydantic AI verdict schema and judges
      ledger.py  # SQLite review and override store
      pipeline.py  # End-to-end review orchestration
  tests/
    fixtures/
      ci_50_patches.json  # Deterministic CI fixture
    test_workbench.py  # Unit and schema retry tests
  vendor/
    semgrep-rules/  # Ignored local rules clone
  pyproject.toml

Initialize the Git repository, create a Python 3.11+ virtual environment, and install the core packages. Install Semgrep Community Edition with pipx or uv so its CLI stays isolated from your project dependencies.

bashCreate the project, virtual environment, and local rules checkout on macOS and Linux
mkdir -p patch-review-workbench/{app,config,data/raw,data/splits,scripts,src/review_bench,tests/fixtures,vendor,.github/workflows}
cd patch-review-workbench
git init

python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install pydantic-ai mlflow marimo pandas pyarrow pytest kaggle

pipx install semgrep
git clone --depth 1 https://github.com/semgrep/semgrep-rules.git vendor/semgrep-rules
semgrep --version
powershellSame environment setup on Windows PowerShell with UTF-8 enabled for Semgrep
New-Item -ItemType Directory -Force -Path patch-review-workbench\app,patch-review-workbench\config,patch-review-workbench\data\raw,patch-review-workbench\data\splits,patch-review-workbench\scripts,patch-review-workbench\src\review_bench,patch-review-workbench\tests\fixtures,patch-review-workbench\vendor,patch-review-workbench\.github\workflows | Out-Null
Set-Location patch-review-workbench
git init

python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
pip install pydantic-ai mlflow marimo pandas pyarrow pytest kaggle

$env:PYTHONUTF8 = '1'
[System.Environment]::SetEnvironmentVariable('PYTHONUTF8', '1', 'User')
pipx install semgrep
git clone --depth 1 https://github.com/semgrep/semgrep-rules.git vendor/semgrep-rules
semgrep --version

Add a pyproject.toml file so review_bench imports cleanly from scripts and pytest. Add a .gitignore file right away so Kaggle tokens, downloaded datasets, SQLite databases, and MLflow artifacts stay out of Git history.

tomlpyproject.tomlEditable package configuration for src/review_bench
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

[project]
name = "patch-review-workbench"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
  "pydantic-ai",
  "mlflow",
  "marimo",
  "pandas",
  "pyarrow",
  "pytest",
]

[tool.setuptools.packages.find]
where = ["src"]
text.gitignoreKeep raw datasets, credentials, MLflow stores, and cloned rules out of Git
.venv/
__pycache__/
*.pyc
.pytest_cache/
data/raw/
data/splits/*.parquet
vendor/
*.db
*.sqlite
mlartifacts/
mlruns/
.env
kaggle.json
access_token

Create an empty src/review_bench/__init__.py file and install the local package in editable mode. Then pull two coding models from distinct model families in Ollama (qwen2.5-coder:7b and deepseek-coder:6.7b) so your judge panel avoids sharing one training lineage.

bashCreate the package marker, install in editable mode, and pull both Ollama models
python -c "from pathlib import Path; Path('src/review_bench/__init__.py').touch()"
pip install -e .
ollama pull qwen2.5-coder:7b
ollama pull deepseek-coder:6.7b
ollama list
Stage 01 Checkpoint

Run semgrep --version, ollama list, and python -c "import review_bench, pydantic_ai, mlflow, marimo". Confirm both model tags appear in Ollama and vendor/semgrep-rules/python exists on disk.

Stage 02 · data2 hours

Download all three Kaggle datasets and inspect their schemas

Authenticate the Kaggle CLI, fetch all three benchmark datasets into data/raw, inspect their files and column headers with pandas, and record verified column names before writing loaders.

Never hardcode third-party dataset column names before inspecting the files on disk. Downloading all three datasets first and printing their actual filenames, column headers, and sample rows catches schema drift before a single split script runs.

Sign in to Kaggle and generate an API token from your account API settings page. Authenticate with kaggle auth login or set KAGGLE_API_TOKEN in your current terminal session.

bashDownload and unzip all three datasets into data/raw on macOS and Linux
export KAGGLE_API_TOKEN="<your-kaggle-api-token>"
kaggle datasets download -d abdullahalnahianabir/ctssb-1m-dataset -p data/raw/ctssb1m --unzip
kaggle datasets download -d mohitnehete2005/verified-python-problems -p data/raw/python_problems --unzip
kaggle datasets download -d abirambharathisa/who-writes-ai-code-1-3m-open-source-ai-commits -p data/raw/ai_commits --unzip
powershellDownload and unzip all three datasets on Windows PowerShell
$env:KAGGLE_API_TOKEN = '<your-kaggle-api-token>'
kaggle datasets download -d abdullahalnahianabir/ctssb-1m-dataset -p data/raw/ctssb1m --unzip
kaggle datasets download -d mohitnehete2005/verified-python-problems -p data/raw/python_problems --unzip
kaggle datasets download -d abirambharathisa/who-writes-ai-code-1-3m-open-source-ai-commits -p data/raw/ai_commits --unzip

Write an inspection script that scans data/raw for CSV, Parquet, JSONL, and gzipped JSONL files and prints each file's columns and first sample row. Run it once and copy the exact observed column headers into config/dataset_schema.json.

pythonscripts/inspect_datasets.pyInspect folder layouts and column headers across all three Kaggle downloads
from __future__ import annotations

import gzip
import json
from pathlib import Path
import pandas as pd

RAW_ROOT = Path("data/raw")


def preview_jsonl(path: Path, limit: int = 2) -> list[dict]:
    opener = gzip.open if path.suffix == ".gz" else open
    rows: list[dict] = []
    with opener(path, "rt", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            rows.append(json.loads(line))
            if len(rows) >= limit:
                break
    return rows


def inspect_folder(folder: Path) -> None:
    print(f"\n=== {folder} ===")
    for path in sorted(folder.rglob("*")):
        if not path.is_file():
            continue
        size_mb = path.stat().st_size / (1024 * 1024)
        print(f"FILE: {path.relative_to(RAW_ROOT)} ({size_mb:.1f} MB)")
        suffixes = "".join(path.suffixes).lower()
        try:
            if suffixes.endswith(".csv"):
                df = pd.read_csv(path, nrows=3)
                print("  COLUMNS:", list(df.columns))
                print("  SAMPLE:", df.iloc[0].to_dict() if len(df) else {})
            elif suffixes.endswith(".parquet"):
                df = pd.read_parquet(path).head(3)
                print("  COLUMNS:", list(df.columns))
                print("  SAMPLE:", df.iloc[0].to_dict() if len(df) else {})
            elif suffixes.endswith((".jsonl", ".jsonl.gz", ".json.gz", ".ndjson")):
                sample = preview_jsonl(path, limit=1)
                keys = sorted(sample[0].keys()) if sample else []
                print("  KEYS:", keys)
            elif suffixes.endswith(".json"):
                with open(path, "r", encoding="utf-8") as handle:
                    obj = json.load(handle)
                if isinstance(obj, list) and obj and isinstance(obj[0], dict):
                    print("  KEYS:", sorted(obj[0].keys()))
                elif isinstance(obj, dict):
                    print("  TOP KEYS:", sorted(obj.keys()))
        except Exception as exc:
            print(f"  INSPECT ERROR: {exc}")


if __name__ == "__main__":
    for sub in sorted(RAW_ROOT.iterdir()):
        if sub.is_dir():
            inspect_folder(sub)
bashRun the schema inspection script and capture its output
python scripts/inspect_datasets.py
OutputExpected shape of the inspection output (verify every column name against your local run)
=== data/raw/ai_commits ===
FILE: ai_commits/commits_<year>.csv (<mb> MB)
  COLUMNS: ['<repo_col>', '<authorship_col>', '<lines_added_col>', ...]
FILE: ai_commits/repos.csv (<mb> MB)
  COLUMNS: ['<repo_id_col>', ...]

=== data/raw/ctssb1m ===
FILE: ctssb1m/<archive_file> (<mb> MB)
  KEYS: ['after', 'before', 'commit_sha', 'diff', 'file_path', 'likely_bug', 'project', 'sstub_pattern', ...]

=== data/raw/python_problems ===
FILE: python_problems/<data_file> (<mb> MB)
  COLUMNS: ['<id_col>', '<tier_col>', '<code_col>', '<passed_col>', '<error_col>', ...]

Create config/dataset_schema.json using the exact column names and relative file globs printed by scripts/inspect_datasets.py. Storing those mappings in one JSON config file keeps the split builder decoupled from Kaggle filename changes.

jsonconfig/dataset_schema.jsonSchema mapping template; replace placeholder column names with your verified inspect output
{
  "ctssb1m": {
    "glob": "*.jsonl*",
    "id_fields": ["project", "commit_sha", "file_path"],
    "before_col": "before",
    "after_col": "after",
    "diff_col": "diff",
    "file_path_col": "file_path",
    "pattern_col": "sstub_pattern",
    "likely_bug_col": "likely_bug"
  },
  "python_problems": {
    "glob": "*",
    "id_col": "<verified_id_column>",
    "tier_col": "<verified_difficulty_column>",
    "code_col": "<verified_code_column>",
    "passed_col": "passed",
    "prompt_col": "<verified_prompt_column>",
    "error_col": "<verified_error_column>"
  },
  "ai_commits": {
    "glob": "commits_*.csv",
    "repo_col": "<verified_repo_column>",
    "authorship_col": "<verified_authorship_column>",
    "lines_changed_cols": ["<verified_additions_col>", "<verified_deletions_col>"]
  }
}
Stage 02 Checkpoint

Confirm all three subfolders inside data/raw/ contain extracted data files and that every placeholder inside config/dataset_schema.json has been replaced with an exact header printed by scripts/inspect_datasets.py.

Stage 03 · data4 hours

Build seeded Parquet splits and verify zero patch overlap

Sample 2,000 paired CTSSB-1M snippets with unified diffs, stratify 1,000 Python problems by difficulty tier, aggregate AI commit authorship stats, write seeded Parquet splits, and prove zero ID overlap.

Benchmark leakage ruins judge precision numbers. Grouping paired buggy and fixed versions of the same CTSSB-1M commit into the same split prevents the workbench from seeing a repair in validation and its broken twin in test.

Construct two candidate records per sampled CTSSB-1M pair: the buggy before snapshot labeled reject and the repaired after snapshot labeled approve. Build a unified diff for each candidate with difflib.unified_diff. Then draw a stratified sample of 1,000 items across all six tiers of 136K Python Problems, mapping passed == 1 to approve and passed == 0 to reject.

pythonsrc/review_bench/splits.pyDataset loaders for CTSSB-1M pairs, stratified Python problems, and AI commit aggregates
from __future__ import annotations

import difflib
import gzip
import hashlib
import json
import random
from pathlib import Path
import pandas as pd

SEED = 202612


def make_diff(old: str, new: str, fpath: str, ctx: int = 3) -> str:
    return "".join(difflib.unified_diff(old.splitlines(True), new.splitlines(True), f"a/{fpath}", f"b/{fpath}", n=ctx))


def assign_split(key: str, seed: int = SEED) -> str:
    bucket = int(hashlib.sha256(f"{seed}:{key}".encode()).hexdigest()[:8], 16) % 100
    return "train" if bucket < 60 else ("val" if bucket < 80 else "test")


def load_ctssb_pairs(raw_root: Path, cfg: dict, target_pairs: int = 1000) -> pd.DataFrame:
    files = sorted((raw_root / "ctssb1m").rglob(cfg["glob"]))
    if not files:
        raise FileNotFoundError("No CTSSB-1M files matched config glob.")
    rng, reservoir, seen = random.Random(SEED), [], 0
    for path in files:
        opener = gzip.open if path.suffix == ".gz" else open
        with opener(path, "rt", encoding="utf-8") as handle:
            for line in handle:
                row = json.loads(line)
                b, a = str(row.get(cfg["before_col"]) or ""), str(row.get(cfg["after_col"]) or "")
                fp = str(row.get(cfg["file_path_col"]) or "snippet.py")
                if not b or not a or b == a or not fp.endswith(".py"):
                    continue
                seen += 1
                if len(reservoir) < target_pairs:
                    reservoir.append(row)
                else:
                    idx = rng.randint(0, seen - 1)
                    if idx < target_pairs:
                        reservoir[idx] = row
    records: list[dict] = []
    for row in reservoir:
        key = "|".join(str(row.get(k, "")) for k in cfg["id_fields"])
        ph = hashlib.sha256(key.encode()).hexdigest()[:16]
        split = assign_split(ph)
        fp = str(row.get(cfg["file_path_col"]) or "snippet.py")
        b, a = str(row[cfg["before_col"]]), str(row[cfg["after_col"]])
        pat = str(row.get(cfg["pattern_col"]) or "unknown")
        for tag, prev, curr, truth in (("buggy", a, b, "reject"), ("fixed", b, a, "approve")):
            records.append({
                "patch_id": f"ctssb_{ph}_{tag}", "pair_id": ph, "source": "ctssb1m", "split": split,
                "tier": pat, "file_path": fp, "before_code": prev, "candidate_code": curr,
                "unified_diff": make_diff(prev, curr, fp), "ground_truth": truth,
                "patch_lines": len(curr.splitlines()),
            })
    return pd.DataFrame(records)


def load_python_problems(raw_root: Path, cfg: dict, total_items: int = 1000) -> pd.DataFrame:
    files = [p for p in sorted((raw_root / "python_problems").rglob(cfg["glob"])) if p.is_file() and p.suffix.lower() in {".csv", ".parquet", ".jsonl"}]
    if not files:
        raise FileNotFoundError("No Python Problems tabular file found.")
    path = files[0]
    df = pd.read_parquet(path) if path.suffix.lower() == ".parquet" else (pd.read_json(path, lines=True) if path.suffix.lower() == ".jsonl" else pd.read_csv(path))
    tcol, pcol, ccol, icol = cfg["tier_col"], cfg["passed_col"], cfg["code_col"], cfg["id_col"]
    df = df.dropna(subset=[tcol, pcol, ccol]).reset_index(drop=True)
    tiers = sorted(df[tcol].astype(str).unique())
    per_tier = max(1, total_items // len(tiers))
    parts = [df[df[tcol].astype(str) == t].sample(n=min(per_tier, sum(df[tcol].astype(str) == t)), random_state=SEED) for t in tiers]
    picked = pd.concat(parts)
    if len(picked) < total_items:
        rest = df.drop(index=picked.index)
        if len(rest):
            picked = pd.concat([picked, rest.sample(n=min(total_items - len(picked), len(rest)), random_state=SEED)])
    records: list[dict] = []
    for idx, row in picked.reset_index(drop=True).iterrows():
        pid = f"pyprob_{hashlib.sha256(str(row.get(icol, idx)).encode()).hexdigest()[:16]}"
        code = str(row[ccol])
        records.append({
            "patch_id": pid, "pair_id": pid, "source": "python_problems", "split": assign_split(pid),
            "tier": str(row[tcol]), "file_path": f"{pid}.py", "before_code": "", "candidate_code": code,
            "unified_diff": make_diff("", code, f"{pid}.py"),
            "ground_truth": "approve" if int(row[pcol]) == 1 else "reject",
            "patch_lines": len(code.splitlines()),
        })
    return pd.DataFrame(records)


def aggregate_ai_commits(raw_root: Path, cfg: dict) -> pd.DataFrame:
    files = sorted((raw_root / "ai_commits").rglob(cfg["glob"]))
    if not files:
        raise FileNotFoundError("No AI commits CSV files matched config glob.")
    rcol, acol = cfg["repo_col"], cfg["authorship_col"]
    scols = [c for c in cfg.get("lines_changed_cols", []) if c and not c.startswith("<")]
    chunks: list[pd.DataFrame] = []
    for path in files:
        f = pd.read_csv(path, usecols=[rcol, acol] + scols, low_memory=False)
        f["lines_changed"] = f[scols].fillna(0).sum(axis=1) if scols else 0
        f["size_bucket"] = pd.cut(f["lines_changed"], [-1, 10, 50, 200, 10_000_000], labels=["1-10", "11-50", "51-200", "201+"]).astype(str)
        g = f.groupby([rcol, acol, "size_bucket"], dropna=False).size().reset_index(name="commit_count")
        chunks.append(g.rename(columns={rcol: "repo", acol: "authorship_label"}))
    return pd.concat(chunks, ignore_index=True).groupby(["repo", "authorship_label", "size_bucket"], as_index=False)["commit_count"].sum()
pythonscripts/build_splits.pyWrite seeded Parquet splits, SHA-256 manifest, and exit 0 only on zero ID overlap
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path
import pandas as pd

from review_bench.splits import (
    SEED,
    aggregate_ai_commits,
    load_ctssb_pairs,
    load_python_problems,
)

RAW_ROOT = Path("data/raw")
SPLIT_ROOT = Path("data/splits")
SCHEMA_PATH = Path("config/dataset_schema.json")


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with open(path, "rb") as handle:
        for block in iter(lambda: handle.read(65536), b""):
            digest.update(block)
    return digest.hexdigest()


def main() -> int:
    cfg = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
    SPLIT_ROOT.mkdir(parents=True, exist_ok=True)
    all_df = pd.concat(
        [
            load_ctssb_pairs(RAW_ROOT, cfg["ctssb1m"], target_pairs=1000),
            load_python_problems(RAW_ROOT, cfg["python_problems"], total_items=1000),
        ],
        ignore_index=True,
    )
    manifest: dict[str, str] = {}
    split_ids: dict[str, set[str]] = {}
    for name in ("train", "val", "test"):
        part = all_df[all_df["split"] == name].reset_index(drop=True)
        out_path = SPLIT_ROOT / f"{name}.parquet"
        part.to_parquet(out_path, index=False)
        manifest[out_path.name] = sha256_file(out_path)
        split_ids[name] = set(part["patch_id"])

    overlap = (
        (split_ids["train"] & split_ids["val"])
        | (split_ids["train"] & split_ids["test"])
        | (split_ids["val"] & split_ids["test"])
    )
    commits = aggregate_ai_commits(RAW_ROOT, cfg["ai_commits"])
    commits_path = SPLIT_ROOT / "ai_commits_summary.parquet"
    commits.to_parquet(commits_path, index=False)
    manifest[commits_path.name] = sha256_file(commits_path)

    (SPLIT_ROOT / "manifest.json").write_text(
        json.dumps({"seed": SEED, "files": manifest}, indent=2), encoding="utf-8"
    )
    print("Row counts by source and split:")
    print(all_df.groupby(["source", "split"]).size().unstack(fill_value=0).to_string())
    print(f"AI commit summary rows: {len(commits)}")
    print(f"Cross-split patch_id overlap: {len(overlap)}")
    return 0 if len(overlap) == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
bashRun the split builder and check its exit status
python scripts/build_splits.py
OutputExpected split verification table with zero cross-split overlap
Row counts by source and split:
split            test  train  val
source
ctssb1m         <n1>   <n2>  <n3>
python_problems <n4>   <n5>  <n6>
AI commit summary rows: <n7>
Cross-split patch_id overlap: 0
Stage 03 Checkpoint

Verify scripts/build_splits.py prints counts for ctssb1m (2,000 total rows across 1,000 pairs) and python_problems (1,000 rows), writes data/splits/manifest.json, and exits with status 0.

Stage 04 · build3 hours

Build the offline Semgrep Community Edition scanner

Wrap Semgrep Community Edition so it scans candidate Python patches against your local semgrep-rules checkout with metrics disabled and returns structured JSON findings.

Static analysis catches deterministic Python defects in milliseconds before a language model spends compute on the patch. Passing --config vendor/semgrep-rules/python/lang alongside --metrics=off and --disable-version-check keeps every scan strictly offline with zero network calls.

Semgrep's --json output includes a top-level results list where each item stores check_id, path, start.line, end.line, extra.message, and extra.severity. Materializing each candidate patch into a temporary .py file lets the same wrapper scan both CTSSB-1M snippets and Python problem solutions cleanly.

pythonsrc/review_bench/semgrep_runner.pyOffline Semgrep Community Edition wrapper returning normalized JSON findings
from __future__ import annotations

import json
import os
import subprocess
import tempfile
from dataclasses import asdict, dataclass
from pathlib import Path

DEFAULT_RULES_DIR = Path("vendor/semgrep-rules/python/lang")


@dataclass(frozen=True)
class SemgrepFinding:
    check_id: str
    start_line: int
    end_line: int
    severity: str
    message: str


def get_rules_git_sha(rules_repo: Path = Path("vendor/semgrep-rules")) -> str:
    proc = subprocess.run(
        ["git", "-C", str(rules_repo), "rev-parse", "--short", "HEAD"],
        capture_output=True,
        text=True,
        check=False,
    )
    return proc.stdout.strip() or "unknown"


def scan_python_code(
    code: str,
    filename: str = "candidate.py",
    rules_path: Path = DEFAULT_RULES_DIR,
    timeout_seconds: int = 60,
) -> list[SemgrepFinding]:
    if not rules_path.exists():
        raise FileNotFoundError(f"Local Semgrep rules directory not found: {rules_path}")
    safe_name = Path(filename).name if filename.endswith(".py") else "candidate.py"
    env = os.environ.copy()
    env["PYTHONUTF8"] = "1"
    with tempfile.TemporaryDirectory(prefix="semgrep_patch_") as tmpdir:
        target = Path(tmpdir) / safe_name
        target.write_text(code, encoding="utf-8")
        cmd = [
            "semgrep",
            "scan",
            "--config",
            str(rules_path),
            "--metrics=off",
            "--disable-version-check",
            "--json",
            str(target),
        ]
        proc = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            encoding="utf-8",
            env=env,
            timeout=timeout_seconds,
            check=False,
        )
        if proc.returncode not in (0, 1):
            raise RuntimeError(f"Semgrep scan failed ({proc.returncode}): {proc.stderr[:400]}")
        payload = json.loads(proc.stdout or "{}")
    findings: list[SemgrepFinding] = []
    for item in payload.get("results", []):
        extra = item.get("extra", {})
        findings.append(
            SemgrepFinding(
                check_id=str(item.get("check_id", "unknown")),
                start_line=int(item.get("start", {}).get("line", 0)),
                end_line=int(item.get("end", {}).get("line", 0)),
                severity=str(extra.get("severity", "INFO")),
                message=str(extra.get("message", "")).strip(),
            )
        )
    return findings


def findings_to_json(findings: list[SemgrepFinding]) -> str:
    return json.dumps([asdict(f) for f in findings])

Run a baseline scan across 50 sampled CTSSB-1M validation patches and save the structured JSON output to disk. Running this command with Wi-Fi disabled verifies your scanner makes zero hosted-service calls.

bashVerify offline Semgrep scanning on a 50-patch CTSSB-1M sample
python -c "import json, pandas as pd; from pathlib import Path; from review_bench.semgrep_runner import scan_python_code, get_rules_git_sha; df = pd.read_parquet('data/splits/val.parquet'); sub = df[df['source']=='ctssb1m'].head(50); out = [{'patch_id': r.patch_id, 'ground_truth': r.ground_truth, 'findings': [f.__dict__ for f in scan_python_code(r.candidate_code, r.file_path)]} for r in sub.itertuples()]; Path('data/splits/semgrep_ctssb_sample.json').write_text(json.dumps(out, indent=2), encoding='utf-8'); hits = sum(1 for x in out if x['findings']); print('rules_sha:', get_rules_git_sha(), 'scanned:', len(out), 'with_findings:', hits)"
OutputBaseline offline scan summary written to data/splits/semgrep_ctssb_sample.json
rules_sha: <git_short_sha> scanned: 50 with_findings: <finding_count>
Stage 04 Checkpoint

Inspect data/splits/semgrep_ctssb_sample.json and confirm each record contains a patch_id and a findings array of objects with check_id, start_line, end_line, severity, and message.

Stage 05 · build4 hours

Build the typed Pydantic AI dual-judge core

Define the Pydantic AI PatchVerdict schema, connect both Ollama models with NativeOutput and bounded retries, and route every judge disagreement or schema failure to abstain.

Free-form LLM code reviews are hard to score and easy to misparse. Enforcing a strict Pydantic model via NativeOutput(PatchVerdict) tells Ollama to constrain token generation to your JSON schema while retries=2 handles occasional malformed responses.

Both judges evaluate each candidate patch independently without seeing each other's answer. Only unanimous approve or unanimous reject calls resolve automatically; any disagreement, explicit abstain, or exhausted retry routes the patch to human review.

pythonsrc/review_bench/models.pyPydantic AI verdict schema, Ollama judge factory, and unanimous routing logic
from __future__ import annotations

import difflib
import time
from dataclasses import dataclass
from typing import Literal
from pydantic import BaseModel, Field
from pydantic_ai import Agent
from pydantic_ai.exceptions import UnexpectedModelBehavior
from pydantic_ai.models.ollama import OllamaModel
from pydantic_ai.output import NativeOutput
from pydantic_ai.providers.ollama import OllamaProvider

from review_bench.semgrep_runner import SemgrepFinding

Decision = Literal["approve", "reject", "abstain"]


class PatchVerdict(BaseModel):
    verdict: Decision = Field(
        description="approve if the Python patch is bug-free, reject if it contains a defect, or abstain if uncertain."
    )
    cited_lines: list[int] = Field(
        default_factory=list,
        description="1-based line numbers in the candidate snippet supporting the verdict.",
    )
    defect_note: str = Field(
        min_length=5,
        max_length=400,
        description="Plain-text explanation of the defect or why the patch looks correct.",
    )


@dataclass(frozen=True)
class JudgeOutcome:
    model_tag: str
    verdict: Decision
    cited_lines: list[int]
    defect_note: str
    schema_valid: bool
    retries_used: int
    latency_ms: float


@dataclass(frozen=True)
class PanelOutcome:
    final_verdict: Decision
    judge_a: JudgeOutcome
    judge_b: JudgeOutcome
    disagreed: bool


SYSTEM_PROMPT = (
    "You review Python patches for functional bugs, security issues, and failing logic. "
    "Return JSON matching PatchVerdict. "
    "Use approve only when the candidate code is correct, reject when you identify a concrete defect, "
    "and abstain when the diff lacks enough evidence."
)


def build_ollama_agent(
    model_tag: str,
    base_url: str = "http://localhost:11434/v1",
    retries: int = 2,
) -> Agent[None, PatchVerdict]:
    model = OllamaModel(
        model_name=model_tag,
        provider=OllamaProvider(base_url=base_url),
    )
    return Agent(
        model,
        output_type=NativeOutput(PatchVerdict),
        system_prompt=SYSTEM_PROMPT,
        retries=retries,
        instrument=True,
    )


def format_diff_with_context(
    before_code: str, candidate_code: str, file_path: str, context_lines: int
) -> str:
    diff = difflib.unified_diff(
        before_code.splitlines(keepends=True),
        candidate_code.splitlines(keepends=True),
        fromfile=f"a/{file_path}",
        tofile=f"b/{file_path}",
        n=context_lines,
    )
    return "".join(diff)


def build_review_prompt(
    file_path: str,
    diff_text: str,
    findings: list[SemgrepFinding],
    include_semgrep: bool,
) -> str:
    parts = [f"File: {file_path}", "Unified diff:", diff_text[:3500]]
    if include_semgrep:
        if findings:
            lines = [
                f"- [{f.severity}] line {f.start_line}-{f.end_line} {f.check_id}: {f.message}"
                for f in findings[:10]
            ]
            parts.append("Semgrep static findings:\n" + "\n".join(lines))
        else:
            parts.append("Semgrep static findings: none")
    return "\n\n".join(parts)


def run_single_judge(
    agent: Agent[None, PatchVerdict], model_tag: str, prompt: str
) -> JudgeOutcome:
    start = time.perf_counter()
    try:
        result = agent.run_sync(prompt)
        elapsed_ms = (time.perf_counter() - start) * 1000.0
        verdict_obj = result.output
        retries_used = max(0, (result.usage().requests or 1) - 1)
        return JudgeOutcome(
            model_tag=model_tag,
            verdict=verdict_obj.verdict,
            cited_lines=[int(n) for n in verdict_obj.cited_lines],
            defect_note=verdict_obj.defect_note.strip(),
            schema_valid=True,
            retries_used=int(retries_used),
            latency_ms=round(elapsed_ms, 2),
        )
    except UnexpectedModelBehavior as exc:
        elapsed_ms = (time.perf_counter() - start) * 1000.0
        return JudgeOutcome(
            model_tag=model_tag,
            verdict="abstain",
            cited_lines=[],
            defect_note=f"Schema validation failed after retries: {str(exc)[:180]}",
            schema_valid=False,
            retries_used=2,
            latency_ms=round(elapsed_ms, 2),
        )


def combine_panel(judge_a: JudgeOutcome, judge_b: JudgeOutcome) -> PanelOutcome:
    if not judge_a.schema_valid or not judge_b.schema_valid:
        return PanelOutcome("abstain", judge_a, judge_b, disagreed=True)
    if judge_a.verdict == judge_b.verdict and judge_a.verdict in ("approve", "reject"):
        return PanelOutcome(judge_a.verdict, judge_a, judge_b, disagreed=False)
    return PanelOutcome("abstain", judge_a, judge_b, disagreed=True)
bashSmoke-test both local Ollama judges on one buggy snippet
python -c "from review_bench.models import build_ollama_agent, run_single_judge, combine_panel, build_review_prompt; a = build_ollama_agent('qwen2.5-coder:7b'); b = build_ollama_agent('deepseek-coder:6.7b'); prompt = build_review_prompt('demo.py', '--- a/demo.py\n+++ b/demo.py\n@@ -1 +1 @@\n-return x / y if y != 0 else 0\n+return x / y\n', [], False); oa = run_single_judge(a, 'qwen2.5-coder:7b', prompt); ob = run_single_judge(b, 'deepseek-coder:6.7b', prompt); p = combine_panel(oa, ob); print(p.final_verdict, oa.schema_valid, ob.schema_valid, oa.latency_ms, ob.latency_ms)"
OutputExpected smoke-test output showing valid schemas and measured millisecond timings
<final_verdict> True True <judge_a_ms> <judge_b_ms>
Stage 05 Checkpoint

Confirm both local Ollama models return schema_valid=True on the smoke test and combine_panel emits abstain whenever the two judges disagree.

Stage 06 · build2 hours

Persist verdicts and human overrides in a SQLite ledger

Create a SQLite database keyed by (patch_id, run_id) storing Semgrep findings, both model verdicts, final status, human override decisions, and error tags.

Separating the review ledger from MLflow's own SQLite backend avoids write-lock contention when you run evaluations while triaging patches in marimo. Keying the reviews table on (patch_id, run_id) lets you compare multiple workflows side by side while keeping each human correction attached to a specific run.

pythonsrc/review_bench/ledger.pySQLite review ledger with upsert, abstention query, and human override methods
from __future__ import annotations

import json
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS reviews (
    patch_id TEXT NOT NULL,
    run_id TEXT NOT NULL,
    workflow_name TEXT NOT NULL,
    source TEXT NOT NULL,
    split TEXT NOT NULL,
    tier TEXT NOT NULL,
    patch_lines INTEGER NOT NULL,
    file_path TEXT NOT NULL,
    unified_diff TEXT NOT NULL,
    ground_truth TEXT NOT NULL,
    semgrep_json TEXT NOT NULL,
    judge_a_model TEXT NOT NULL,
    judge_a_verdict TEXT NOT NULL,
    judge_a_lines TEXT NOT NULL,
    judge_a_note TEXT NOT NULL,
    judge_a_valid INTEGER NOT NULL,
    judge_a_retries INTEGER NOT NULL,
    judge_a_ms REAL NOT NULL,
    judge_b_model TEXT NOT NULL,
    judge_b_verdict TEXT NOT NULL,
    judge_b_lines TEXT NOT NULL,
    judge_b_note TEXT NOT NULL,
    judge_b_valid INTEGER NOT NULL,
    judge_b_retries INTEGER NOT NULL,
    judge_b_ms REAL NOT NULL,
    final_verdict TEXT NOT NULL,
    human_verdict TEXT,
    human_error_tag TEXT,
    human_note TEXT,
    reviewed_at TEXT,
    created_at TEXT NOT NULL,
    PRIMARY KEY (patch_id, run_id)
);
CREATE INDEX IF NOT EXISTS idx_reviews_abstain ON reviews (run_id, final_verdict, human_verdict);
"""


class ReviewLedger:
    def __init__(self, db_path: Path | str = Path("review_ledger.db")) -> None:
        self.db_path = Path(db_path)
        with self._connect() as conn:
            conn.executescript(SCHEMA_SQL)

    def _connect(self) -> sqlite3.Connection:
        conn = sqlite3.connect(self.db_path, timeout=30.0)
        conn.row_factory = sqlite3.Row
        return conn

    def record_review(self, row: dict[str, Any]) -> None:
        now = datetime.now(timezone.utc).isoformat()
        payload = dict(row)
        payload["created_at"] = now
        cols = [
            "patch_id", "run_id", "workflow_name", "source", "split", "tier",
            "patch_lines", "file_path", "unified_diff", "ground_truth", "semgrep_json",
            "judge_a_model", "judge_a_verdict", "judge_a_lines", "judge_a_note",
            "judge_a_valid", "judge_a_retries", "judge_a_ms",
            "judge_b_model", "judge_b_verdict", "judge_b_lines", "judge_b_note",
            "judge_b_valid", "judge_b_retries", "judge_b_ms",
            "final_verdict", "created_at",
        ]
        placeholders = ", ".join("?" for _ in cols)
        sql = f"INSERT OR REPLACE INTO reviews ({', '.join(cols)}) VALUES ({placeholders})"
        values = [
            json.dumps(payload[c]) if isinstance(payload[c], (list, dict)) else payload[c]
            for c in cols
        ]
        with self._connect() as conn:
            conn.execute(sql, values)

    def fetch_abstained(self, run_id: str | None = None, unresolved_only: bool = True) -> list[dict[str, Any]]:
        clauses = ["final_verdict = 'abstain'"]
        params: list[Any] = []
        if run_id:
            clauses.append("run_id = ?")
            params.append(run_id)
        if unresolved_only:
            clauses.append("human_verdict IS NULL")
        where_sql = " AND ".join(clauses)
        with self._connect() as conn:
            rows = conn.execute(
                f"SELECT * FROM reviews WHERE {where_sql} ORDER BY created_at ASC", params
            ).fetchall()
        return [dict(r) for r in rows]

    def save_human_override(
        self, patch_id: str, run_id: str, human_verdict: str, error_tag: str, human_note: str = ""
    ) -> None:
        if human_verdict not in ("approve", "reject"):
            raise ValueError("human_verdict must be approve or reject")
        now = datetime.now(timezone.utc).isoformat()
        with self._connect() as conn:
            cur = conn.execute(
                """
                UPDATE reviews
                SET human_verdict = ?, human_error_tag = ?, human_note = ?, reviewed_at = ?
                WHERE patch_id = ? AND run_id = ?
                """,
                (human_verdict, error_tag.strip(), human_note.strip(), now, patch_id, run_id),
            )
            if cur.rowcount == 0:
                raise KeyError(f"No review row found for {(patch_id, run_id)}")

    def list_runs(self) -> list[str]:
        with self._connect() as conn:
            rows = conn.execute(
                "SELECT DISTINCT run_id FROM reviews ORDER BY created_at DESC"
            ).fetchall()
        return [str(r["run_id"]) for r in rows]

Connect Semgrep, both Ollama judges, and ReviewLedger inside src/review_bench/pipeline.py. This shared module also computes unanimous accuracy, precision, recall, abstention rate, schema validity, and latency percentiles so validation and held-out runs use identical metric formulas.

pythonsrc/review_bench/pipeline.pyEnd-to-end patch review pipeline and summary metric computation
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from pydantic_ai import Agent

from review_bench.ledger import ReviewLedger
from review_bench.models import (
    PatchVerdict,
    build_review_prompt,
    combine_panel,
    format_diff_with_context,
    run_single_judge,
)
from review_bench.semgrep_runner import findings_to_json, scan_python_code


@dataclass(frozen=True)
class WorkflowConfig:
    name: str
    context_lines: int
    include_semgrep: bool
    judge_a_tag: str = "qwen2.5-coder:7b"
    judge_b_tag: str = "deepseek-coder:6.7b"


def binary_precision_recall(y_true: list[str], y_pred: list[str]) -> tuple[float, float]:
    tp = sum(1 for t, p in zip(y_true, y_pred) if t == "reject" and p == "reject")
    fp = sum(1 for t, p in zip(y_true, y_pred) if t != "reject" and p == "reject")
    fn = sum(1 for t, p in zip(y_true, y_pred) if t == "reject" and p != "reject")
    precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
    recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
    return round(precision, 4), round(recall, 4)


def compute_metrics(records: list[dict[str, Any]]) -> dict[str, float]:
    total = len(records)
    if total == 0:
        return {}
    y_true = [r["ground_truth"] for r in records]
    prec_a, rec_a = binary_precision_recall(y_true, [r["judge_a_verdict"] for r in records])
    prec_b, rec_b = binary_precision_recall(y_true, [r["judge_b_verdict"] for r in records])

    decided = [r for r in records if r["final_verdict"] in ("approve", "reject")]
    unanimous_accuracy = (
        round(sum(1 for r in decided if r["final_verdict"] == r["ground_truth"]) / len(decided), 4)
        if decided
        else 0.0
    )
    prec_panel, rec_panel_decided = binary_precision_recall(
        [r["ground_truth"] for r in decided],
        [r["final_verdict"] for r in decided],
    )
    _, rec_panel_all = binary_precision_recall(y_true, [r["final_verdict"] for r in records])

    abstention_rate = round((total - len(decided)) / total, 4)
    valid_calls = sum(int(r["judge_a_valid"]) + int(r["judge_b_valid"]) for r in records)
    schema_valid_rate = round(valid_calls / (2 * total), 4)
    total_retries = sum(int(r["judge_a_retries"]) + int(r["judge_b_retries"]) for r in records)
    latencies = [r["judge_a_ms"] for r in records] + [r["judge_b_ms"] for r in records]
    return {
        "total_patches": float(total),
        "judge_a_precision": prec_a,
        "judge_a_recall": rec_a,
        "judge_b_precision": prec_b,
        "judge_b_recall": rec_b,
        "unanimous_accuracy": unanimous_accuracy,
        "unanimous_precision": prec_panel,
        "unanimous_recall_decided": rec_panel_decided,
        "unanimous_recall_overall": rec_panel_all,
        "abstention_rate": abstention_rate,
        "schema_valid_rate": schema_valid_rate,
        "schema_retries_total": float(total_retries),
        "latency_p50_ms": round(float(np.percentile(latencies, 50)), 2),
        "latency_p95_ms": round(float(np.percentile(latencies, 95)), 2),
    }


def evaluate_dataframe(
    df: pd.DataFrame,
    workflow: WorkflowConfig,
    run_id: str,
    agent_a: Agent[None, PatchVerdict],
    agent_b: Agent[None, PatchVerdict],
    ledger: ReviewLedger,
    rules_path: Path | None = None,
    skip_semgrep: bool = False,
) -> tuple[list[dict[str, Any]], dict[str, float]]:
    records: list[dict[str, Any]] = []
    for row in df.itertuples(index=False):
        findings = (
            []
            if skip_semgrep
            else scan_python_code(
                row.candidate_code,
                filename=row.file_path,
                rules_path=rules_path or Path("vendor/semgrep-rules/python/lang"),
            )
        )
        diff_text = format_diff_with_context(
            row.before_code, row.candidate_code, row.file_path, workflow.context_lines
        )
        prompt = build_review_prompt(
            row.file_path, diff_text, findings, include_semgrep=workflow.include_semgrep
        )
        out_a = run_single_judge(agent_a, workflow.judge_a_tag, prompt)
        out_b = run_single_judge(agent_b, workflow.judge_b_tag, prompt)
        panel = combine_panel(out_a, out_b)
        record = {
            "patch_id": row.patch_id, "run_id": run_id, "workflow_name": workflow.name,
            "source": row.source, "split": row.split, "tier": row.tier,
            "patch_lines": int(row.patch_lines), "file_path": row.file_path,
            "unified_diff": diff_text, "ground_truth": row.ground_truth,
            "semgrep_json": findings_to_json(findings),
            "judge_a_model": out_a.model_tag, "judge_a_verdict": out_a.verdict,
            "judge_a_lines": out_a.cited_lines, "judge_a_note": out_a.defect_note,
            "judge_a_valid": int(out_a.schema_valid), "judge_a_retries": out_a.retries_used,
            "judge_a_ms": out_a.latency_ms,
            "judge_b_model": out_b.model_tag, "judge_b_verdict": out_b.verdict,
            "judge_b_lines": out_b.cited_lines, "judge_b_note": out_b.defect_note,
            "judge_b_valid": int(out_b.schema_valid), "judge_b_retries": out_b.retries_used,
            "judge_b_ms": out_b.latency_ms,
            "final_verdict": panel.final_verdict,
        }
        ledger.record_review(record)
        records.append(record)
    return records, compute_metrics(records)
Stage 06 Checkpoint

Run python -c "from review_bench.ledger import ReviewLedger; l = ReviewLedger('test_tmp.db'); print(l.list_runs())" and delete test_tmp.db afterward to verify SQLite table creation works cleanly.

Stage 07 · test4 hours

Compare two review workflows and log traces in MLflow

Launch a local MLflow tracking server, enable Pydantic AI autologging, and evaluate two workflows using identical Ollama models across the validation split.

Comparing two prompts or workflow setups only produces clean evidence when both model weights stay fixed. Workflow A sends a narrow 3-line unified diff with zero static findings, while Workflow B sends a wider 12-line unified diff paired with Semgrep Community Edition findings.

Start the local MLflow server in a dedicated terminal backed by its own mlflow.db file and local ./mlartifacts directory. Calling mlflow.pydantic_ai.autolog() records every judge call as an inspectable trace directly beside the run's metrics and parameters.

bashStart the local MLflow tracking server in a separate terminal
mlflow server --backend-store-uri sqlite:///mlflow.db --default-artifact-root ./mlartifacts --host 127.0.0.1 --port 5000
pythonscripts/run_workflows.pyRun both review workflows on the validation split and log everything to MLflow
from __future__ import annotations

import argparse
import json
from pathlib import Path
import mlflow
import pandas as pd

from review_bench.ledger import ReviewLedger
from review_bench.models import build_ollama_agent
from review_bench.pipeline import WorkflowConfig, evaluate_dataframe
from review_bench.semgrep_runner import get_rules_git_sha

WORKFLOWS = [
    WorkflowConfig(name="wf_a_diff3_no_semgrep", context_lines=3, include_semgrep=False),
    WorkflowConfig(name="wf_b_diff12_with_semgrep", context_lines=12, include_semgrep=True),
]


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--tracking-uri", default="http://127.0.0.1:5000")
    parser.add_argument("--experiment", default="patch-review-workbench")
    parser.add_argument("--limit", type=int, default=0, help="Optional row cap for quick smoke checks")
    parser.add_argument("--judge-a", default="qwen2.5-coder:7b")
    parser.add_argument("--judge-b", default="deepseek-coder:6.7b")
    args = parser.parse_args()

    mlflow.set_tracking_uri(args.tracking_uri)
    mlflow.set_experiment(args.experiment)
    mlflow.pydantic_ai.autolog()

    manifest = json.loads(Path("data/splits/manifest.json").read_text(encoding="utf-8"))
    val_df = pd.read_parquet("data/splits/val.parquet")
    if args.limit > 0:
        val_df = val_df.head(args.limit).copy()

    ledger = ReviewLedger("review_ledger.db")
    rules_sha = get_rules_git_sha()
    summary_rows: list[dict] = []

    for base_wf in WORKFLOWS:
        wf = WorkflowConfig(
            name=base_wf.name,
            context_lines=base_wf.context_lines,
            include_semgrep=base_wf.include_semgrep,
            judge_a_tag=args.judge_a,
            judge_b_tag=args.judge_b,
        )
        agent_a = build_ollama_agent(wf.judge_a_tag, retries=2)
        agent_b = build_ollama_agent(wf.judge_b_tag, retries=2)
        with mlflow.start_run(run_name=wf.name) as active_run:
            run_id = active_run.info.run_id
            mlflow.log_params({
                "workflow_name": wf.name,
                "context_lines": wf.context_lines,
                "include_semgrep": wf.include_semgrep,
                "judge_a_model": wf.judge_a_tag,
                "judge_b_model": wf.judge_b_tag,
                "semgrep_rules_sha": rules_sha,
                "val_split_sha256": manifest["files"]["val.parquet"],
                "split_seed": manifest["seed"],
            })
            records, metrics = evaluate_dataframe(
                df=val_df, workflow=wf, run_id=run_id,
                agent_a=agent_a, agent_b=agent_b, ledger=ledger,
            )
            mlflow.log_metrics(metrics)
            out_csv = Path(f"data/splits/{wf.name}_val_results.csv")
            pd.DataFrame(records).to_csv(out_csv, index=False)
            mlflow.log_artifact(str(out_csv))
            summary_rows.append({"workflow": wf.name, "run_id": run_id, **metrics})

    comparison = pd.DataFrame(summary_rows)
    comparison.to_csv("data/splits/mlflow_workflow_comparison.csv", index=False)
    cols = [
        "workflow", "judge_a_precision", "judge_b_precision",
        "unanimous_accuracy", "unanimous_precision", "abstention_rate",
        "schema_valid_rate", "latency_p50_ms", "latency_p95_ms",
    ]
    print(comparison[cols].to_string(index=False))


if __name__ == "__main__":
    main()
bashRun a 20-patch check first, then run both workflows across the full validation split
python scripts/run_workflows.py --limit 20
python scripts/run_workflows.py
OutputSide-by-side workflow summary printed at completion and logged to MLflow
                 workflow  judge_a_precision  judge_b_precision  unanimous_accuracy  unanimous_precision  abstention_rate  schema_valid_rate  latency_p50_ms  latency_p95_ms
    wf_a_diff3_no_semgrep            <prec>             <prec>               <acc>               <prec>          <share>            <rate>            <ms>            <ms>
 wf_b_diff12_with_semgrep            <prec>             <prec>               <acc>               <prec>          <share>            <rate>            <ms>            <ms>
Stage 07 Checkpoint

Open http://127.0.0.1:5000 in your browser, select both validation runs in patch-review-workbench, and confirm parameters, metrics, latency percentiles, and per-patch Traces appear side by side.

Stage 08 · build4 hours

Build the reactive marimo human triage notebook

Create a versioned marimo app that loads abstained patches from SQLite, shows the diff and judge rationales, saves reviewer overrides immediately, and tabulates AI commit shares beside abstention rates.

When two judges disagree, an engineer needs the diff, static findings, and both short rationales on one screen. A marimo notebook saves as a plain Python file, tracks cleanly in Git, and re-runs dependent cells whenever a form submits.

Using mo.md(...).batch(...).form(show_clear_button=True) groups the verdict dropdown, error tag selector, and note field into one explicit submit action. Submitting writes straight back to review_ledger.db and immediately removes the resolved patch from the pending queue.

pythonapp/triage_app.pyReactive marimo human triage workbench and authorship comparison panel
import marimo

__generated_with = "0.14.0"
app = marimo.App(width="medium")


@app.cell
def _():
    import json
    import sqlite3
    from pathlib import Path
    import marimo as mo
    import pandas as pd
    from review_bench.ledger import ReviewLedger

    ledger = ReviewLedger("review_ledger.db")
    runs = ledger.list_runs()
    run_picker = mo.ui.dropdown(options=runs or ["none"], value=runs[0] if runs else "none", label="MLflow Run ID")
    mo.md("# Two-Model Patch Review Triage Queue")
    return Path, json, ledger, mo, pd, run_picker, sqlite3


@app.cell
def _(mo, run_picker):
    refresh_state, set_refresh = mo.state(0)
    run_picker
    return refresh_state, set_refresh


@app.cell
def _(ledger, mo, pd, refresh_state, run_picker):
    _ = refresh_state()
    rid = None if run_picker.value == "none" else run_picker.value
    pending = ledger.fetch_abstained(run_id=rid, unresolved_only=True)
    qdf = pd.DataFrame([
        {"patch_id": r["patch_id"], "source": r["source"], "tier": r["tier"], "lines": r["patch_lines"],
         "judge_a": r["judge_a_verdict"], "judge_b": r["judge_b_verdict"]}
        for r in pending
    ])
    queue_table = mo.ui.table(qdf, selection="single", label="Abstained patches")
    mo.vstack([mo.md(f"**Pending abstained patches:** {len(pending)}"), queue_table if pending else mo.md("Queue is clear.")])
    return pending, queue_table


@app.cell
def _(json, mo, pending, queue_table):
    row = None
    if pending:
        sel = queue_table.value
        cid = sel.iloc[0]["patch_id"] if sel is not None and len(sel) else pending[0]["patch_id"]
        row = next((r for r in pending if r["patch_id"] == cid), pending[0])
    if row is None:
        form, view = None, mo.md("Select a run with abstained items to begin triage.")
    else:
        findings = json.loads(row["semgrep_json"])
        f_md = "\n".join(f"- **{f['severity']}** L{f['start_line']}: `{f['check_id']}` - {f['message']}" for f in findings) or "No Semgrep findings."
        tags = ["logic_bug", "boundary_error", "security_issue", "false_alarm", "context_missing", "other"]
        form = (
            mo.md("### Record Human Resolution\nVerdict: {verdict}\n\nError Tag: {tag}\n\nNote: {note}")
            .batch(
                verdict=mo.ui.dropdown(options=["approve", "reject"], value="reject"),
                tag=mo.ui.dropdown(options=tags, value="logic_bug"),
                note=mo.ui.text(placeholder="Short explanation for SQLite ledger"),
            )
            .form(show_clear_button=True, submit_button_label="Save Verdict to SQLite")
        )
        view = mo.vstack([
            mo.md(f"## Patch `{row['patch_id']}` ({row['source']} / {row['tier']})"),
            mo.md(f"```diff\n{row['unified_diff']}\n```"),
            mo.md(f"### Semgrep Findings\n{f_md}"),
            mo.hstack([
                mo.md(f"**Judge A ({row['judge_a_model']}):** `{row['judge_a_verdict']}`\n\nLines: `{row['judge_a_lines']}`\n\n{row['judge_a_note']}"),
                mo.md(f"**Judge B ({row['judge_b_model']}):** `{row['judge_b_verdict']}`\n\nLines: `{row['judge_b_lines']}`\n\n{row['judge_b_note']}"),
            ]),
            form,
        ])
    view
    return form, row


@app.cell
def _(form, ledger, mo, row, set_refresh):
    msg = ""
    if form is not None and form.value is not None and row is not None:
        ledger.save_human_override(row["patch_id"], row["run_id"], form.value["verdict"], form.value["tag"], form.value["note"])
        set_refresh(lambda n: n + 1)
        msg = f"Saved `{form.value['verdict']}` for `{row['patch_id']}` in SQLite."
    mo.md(msg)
    return


@app.cell
def _(Path, mo, pd, run_picker, sqlite3):
    cpath = Path("data/splits/ai_commits_summary.parquet")
    with sqlite3.connect("review_ledger.db") as conn:
        rdf = (
            pd.read_sql_query("SELECT patch_lines, final_verdict FROM reviews WHERE run_id = ?", conn, params=(run_picker.value,))
            if run_picker.value != "none"
            else pd.DataFrame(columns=["patch_lines", "final_verdict"])
        )
    panels = [mo.md("## Authorship Cohort Share vs. Abstention Rate by Patch Size")]
    if len(rdf):
        rdf["size_bucket"] = pd.cut(rdf["patch_lines"], [-1, 10, 50, 200, 10_000_000], labels=["1-10", "11-50", "51-200", "201+"]).astype(str)
        abst = rdf.groupby("size_bucket", as_index=False).agg(
            total_patches=("final_verdict", "size"),
            abstention_rate=("final_verdict", lambda s: round((s == "abstain").mean(), 4)),
        )
        if cpath.exists():
            cdf = pd.read_parquet(cpath)
            tots = cdf.groupby("size_bucket", as_index=False)["commit_count"].sum().rename(columns={"commit_count": "bucket_commits"})
            auth = cdf.groupby(["size_bucket", "authorship_label"], as_index=False)["commit_count"].sum().merge(tots, on="size_bucket")
            auth["authorship_share"] = (auth["commit_count"] / auth["bucket_commits"]).round(4)
            panels.append(mo.ui.table(auth.merge(abst, on="size_bucket", how="left"), label="Authorship Share vs Abstention"))
        else:
            panels.append(mo.ui.table(abst, label="Abstention Rate by Patch Size"))
    else:
        panels.append(mo.md("Run a workflow first to populate abstention metrics."))
    mo.vstack(panels)
    return


if __name__ == "__main__":
    app.run()
bashLaunch the reactive marimo triage app in app mode or interactive editor mode
marimo run app/triage_app.py
# Or edit cells live:
marimo edit app/triage_app.py
Stage 08 Checkpoint

Resolve one abstained patch through the marimo form, then query review_ledger.db with sqlite3 or Python to confirm human_verdict, human_error_tag, and reviewed_at updated immediately.

Stage 09 · test3 hours

Run the frozen held-out test audit and log failure cases

Freeze the winning workflow from validation, evaluate once on untouched held-out test splits, export confusion tables, and list five concrete false-negative defect classes.

Pick the winning workflow from your validation MLflow comparison before touching data/splits/test.parquet. Running the held-out test split once without further prompt tuning gives an honest reading of solo-model versus two-model agreement precision.

Aim for an 8-point precision gain from unanimous two-model agreement where single-model accuracy leaves headroom, while keeping abstention between 15 and 45 percent. If a single model already clears 92 percent precision on a tier, record that high-baseline ceiling honestly beside the abstention share instead of tuning on test.

pythonscripts/eval_held_out.pyRun one frozen held-out test pass and export confusion tables plus false negatives
from __future__ import annotations

import argparse
import json
from pathlib import Path
import mlflow
import pandas as pd

from review_bench.ledger import ReviewLedger
from review_bench.models import build_ollama_agent
from review_bench.pipeline import WorkflowConfig, compute_metrics, evaluate_dataframe
from review_bench.semgrep_runner import get_rules_git_sha


def confusion_table(df: pd.DataFrame, pred_col: str) -> pd.DataFrame:
    return pd.crosstab(
        df["ground_truth"], df[pred_col], rownames=["ground_truth"], colnames=[pred_col], margins=True
    )


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--workflow", choices=["wf_a", "wf_b"], required=True)
    parser.add_argument("--tracking-uri", default="http://127.0.0.1:5000")
    parser.add_argument("--judge-a", default="qwen2.5-coder:7b")
    parser.add_argument("--judge-b", default="deepseek-coder:6.7b")
    args = parser.parse_args()

    wf = (
        WorkflowConfig("wf_a_diff3_no_semgrep", 3, False, args.judge_a, args.judge_b)
        if args.workflow == "wf_a"
        else WorkflowConfig("wf_b_diff12_with_semgrep", 12, True, args.judge_a, args.judge_b)
    )
    mlflow.set_tracking_uri(args.tracking_uri)
    mlflow.set_experiment("patch-review-workbench-held-out")
    mlflow.pydantic_ai.autolog()

    manifest = json.loads(Path("data/splits/manifest.json").read_text(encoding="utf-8"))
    test_df = pd.read_parquet("data/splits/test.parquet")
    ledger = ReviewLedger("review_ledger.db")
    agent_a = build_ollama_agent(wf.judge_a_tag, retries=2)
    agent_b = build_ollama_agent(wf.judge_b_tag, retries=2)

    with mlflow.start_run(run_name=f"held_out_{wf.name}") as run:
        mlflow.log_params({
            "frozen_workflow": wf.name,
            "context_lines": wf.context_lines,
            "include_semgrep": wf.include_semgrep,
            "judge_a_model": wf.judge_a_tag,
            "judge_b_model": wf.judge_b_tag,
            "semgrep_rules_sha": get_rules_git_sha(),
            "test_split_sha256": manifest["files"]["test.parquet"],
        })
        records, metrics = evaluate_dataframe(
            df=test_df, workflow=wf, run_id=run.info.run_id,
            agent_a=agent_a, agent_b=agent_b, ledger=ledger,
        )
        mlflow.log_metrics(metrics)
        res_df = pd.DataFrame(records)
        out_dir = Path("reports")
        out_dir.mkdir(exist_ok=True)
        res_df.to_csv(out_dir / "held_out_predictions.csv", index=False)

        best_single = max(metrics["judge_a_precision"], metrics["judge_b_precision"])
        precision_gain = round(metrics["unanimous_precision"] - best_single, 4)
        note = "precision_gain" if precision_gain >= 0.08 else "high_baseline_ceiling_or_subtarget_gain"

        tier_rows = [
            {"source": src, "tier": tier, **compute_metrics(grp.to_dict(orient="records"))}
            for (src, tier), grp in res_df.groupby(["source", "tier"])
        ]
        pd.DataFrame(tier_rows).to_csv(out_dir / "tier_summary.csv", index=False)

        source_rows = [
            {"source": src, **compute_metrics(grp.to_dict(orient="records"))}
            for src, grp in res_df.groupby("source")
        ]
        source_df = pd.DataFrame(source_rows)
        source_df.to_csv(out_dir / "source_summary.csv", index=False)

        conf_panel = confusion_table(res_df, "final_verdict")
        conf_panel.to_csv(out_dir / "confusion_panel.csv")
        confusion_table(res_df, "judge_a_verdict").to_csv(out_dir / "confusion_judge_a.csv")
        confusion_table(res_df, "judge_b_verdict").to_csv(out_dir / "confusion_judge_b.csv")

        false_neg = res_df[(res_df["ground_truth"] == "reject") & (res_df["final_verdict"] == "approve")]
        false_neg.to_csv(out_dir / "false_negatives.csv", index=False)

        mlflow.log_artifacts(str(out_dir))
        print("=== Held-Out Summary ===")
        print(json.dumps({**metrics, "precision_gain_vs_best_single": precision_gain, "status": note}, indent=2))
        print("\nBy dataset source:")
        print(source_df[["source", "judge_a_precision", "judge_b_precision", "unanimous_precision", "unanimous_recall_overall", "abstention_rate"]].to_string(index=False))
        print("\nPanel confusion table:")
        print(conf_panel.to_string())
        print(f"\nUnanimous false negatives exported: {len(false_neg)}")


if __name__ == "__main__":
    main()
bashRun the frozen held-out evaluation once using your validation winner (wf_a or wf_b)
python scripts/eval_held_out.py --workflow wf_b
OutputExpected held-out audit summary and exported report files
=== Held-Out Summary ===
{
  "total_patches": <test_count>,
  "judge_a_precision": <prec_a>,
  "judge_b_precision": <prec_b>,
  "unanimous_precision": <prec_panel>,
  "abstention_rate": <abst_share>,
  "schema_valid_rate": <valid_rate>,
  "precision_gain_vs_best_single": <delta>,
  "status": "<precision_gain_or_ceiling>"
}
Unanimous false negatives exported: <fn_count>
Stage 09 Checkpoint

Open reports/false_negatives.csv and inspect five distinct bugs that both Ollama judges unanimously approved. Classify each defect (such as off-by-one indexing, silent exception swallowing, or wrong operator precedence) for your README.

Stage 10 · test3 hours

Add unit tests, a 50-patch CI fixture, and GitHub Actions

Write deterministic pytest unit tests with Pydantic AI FunctionModel, check 98 percent JSON schema compliance across a 50-patch fixture, and add GitHub Actions.

Hosted CI runners do not have GPUs or 10 GB of cached Ollama model weights. Pydantic AI supports FunctionModel alongside models.ALLOW_MODEL_REQUESTS = False so your test suite exercises real Pydantic schema validation, retry behavior, abstention routing, and SQLite updates deterministically in seconds.

pythonscripts/generate_ci_fixture.pyGenerate a deterministic 50-patch JSON fixture from validation rows for CI
from __future__ import annotations

import json
from pathlib import Path
import pandas as pd


def main() -> None:
    val_path = Path("data/splits/val.parquet")
    out_path = Path("tests/fixtures/ci_50_patches.json")
    out_path.parent.mkdir(parents=True, exist_ok=True)
    if val_path.exists():
        df = pd.read_parquet(val_path).head(50)
        rows = df[[
            "patch_id", "source", "split", "tier", "patch_lines",
            "file_path", "before_code", "candidate_code", "ground_truth",
        ]].to_dict(orient="records")
    else:
        rows = [
            {
                "patch_id": f"synthetic_{i:02d}",
                "source": "synthetic",
                "split": "val",
                "tier": "Easy",
                "patch_lines": 4,
                "file_path": f"patch_{i:02d}.py",
                "before_code": "def div(a, b):\n    return a / b if b else 0\n",
                "candidate_code": "def div(a, b):\n    return a / b\n" if i % 2 == 0 else "def div(a, b):\n    return a / b if b != 0 else 0\n",
                "ground_truth": "reject" if i % 2 == 0 else "approve",
            }
            for i in range(50)
        ]
    out_path.write_text(json.dumps(rows, indent=2), encoding="utf-8")
    print(f"Wrote {len(rows)} patches to {out_path}")


if __name__ == "__main__":
    main()
pythontests/test_workbench.pyUnit tests covering diff normalization, schema retries, abstention routing, ledger updates, and the 50-patch CI fixture
from __future__ import annotations

import json
from pathlib import Path
import pandas as pd
from pydantic_ai import Agent, models
from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart
from pydantic_ai.models.function import AgentInfo, FunctionModel
from pydantic_ai.output import NativeOutput

from review_bench.ledger import ReviewLedger
from review_bench.models import (
    PatchVerdict,
    combine_panel,
    format_diff_with_context,
    run_single_judge,
)
from review_bench.pipeline import WorkflowConfig, evaluate_dataframe

models.ALLOW_MODEL_REQUESTS = False


def test_diff_normalization_context_width() -> None:
    before = "\n".join(f"x{i} = {i}" for i in range(15)) + "\n"
    after = before.replace("x7 = 7", "x7 = 70")
    diff_narrow = format_diff_with_context(before, after, "sample.py", context_lines=1)
    diff_wide = format_diff_with_context(before, after, "sample.py", context_lines=5)
    assert "-x7 = 7" in diff_narrow and "+x7 = 70" in diff_narrow
    assert len(diff_wide.splitlines()) > len(diff_narrow.splitlines())


def test_pydantic_ai_schema_retry_recovers_on_second_attempt() -> None:
    attempts = {"count": 0}

    def flaky_model(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
        attempts["count"] += 1
        if attempts["count"] == 1:
            return ModelResponse(parts=[TextPart("not valid json")])
        payload = json.dumps({
            "verdict": "reject",
            "cited_lines": [2],
            "defect_note": "Division by zero when b is 0.",
        })
        return ModelResponse(parts=[TextPart(payload)])

    agent = Agent(FunctionModel(flaky_model), output_type=NativeOutput(PatchVerdict), retries=2)
    outcome = run_single_judge(agent, "mock-flaky", "review this diff")
    assert outcome.schema_valid is True
    assert outcome.verdict == "reject"
    assert attempts["count"] == 2


def test_abstention_routing_and_sqlite_override(tmp_path: Path) -> None:
    approve_json = json.dumps({"verdict": "approve", "cited_lines": [1], "defect_note": "Looks clean."})
    reject_json = json.dumps({"verdict": "reject", "cited_lines": [2], "defect_note": "Missing zero check."})

    agent_a = Agent(
        FunctionModel(lambda m, i: ModelResponse(parts=[TextPart(approve_json)])),
        output_type=NativeOutput(PatchVerdict),
    )
    agent_b = Agent(
        FunctionModel(lambda m, i: ModelResponse(parts=[TextPart(reject_json)])),
        output_type=NativeOutput(PatchVerdict),
    )
    oa = run_single_judge(agent_a, "mock-a", "diff")
    ob = run_single_judge(agent_b, "mock-b", "diff")
    panel = combine_panel(oa, ob)
    assert panel.final_verdict == "abstain"
    assert panel.disagreed is True

    ledger = ReviewLedger(tmp_path / "ledger.db")
    df = pd.DataFrame([{
        "patch_id": "p_001", "source": "unit", "split": "val", "tier": "Easy",
        "patch_lines": 2, "file_path": "a.py",
        "before_code": "x = 1\n", "candidate_code": "x = 2\n", "ground_truth": "reject",
    }])
    wf = WorkflowConfig("unit_wf", 3, False, "mock-a", "mock-b")
    evaluate_dataframe(df, wf, "run_1", agent_a, agent_b, ledger, skip_semgrep=True)

    pending = ledger.fetch_abstained(run_id="run_1", unresolved_only=True)
    assert len(pending) == 1
    ledger.save_human_override("p_001", "run_1", "reject", "logic_bug", "Confirmed bug")
    assert ledger.fetch_abstained(run_id="run_1", unresolved_only=True) == []


def test_ci_50_patch_fixture_enforces_98_percent_schema_validity(tmp_path: Path) -> None:
    fixture_path = Path("tests/fixtures/ci_50_patches.json")
    rows = json.loads(fixture_path.read_text(encoding="utf-8"))
    assert len(rows) == 50
    df = pd.DataFrame(rows)

    def deterministic_judge(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
        prompt_text = str(messages[-1])
        verdict = "reject" if "-return" in prompt_text or "a / b\n" in prompt_text else "approve"
        payload = json.dumps({
            "verdict": verdict,
            "cited_lines": [1],
            "defect_note": f"Deterministic fixture verdict: {verdict}.",
        })
        return ModelResponse(parts=[TextPart(payload)])

    agent_a = Agent(FunctionModel(deterministic_judge), output_type=NativeOutput(PatchVerdict), retries=2)
    agent_b = Agent(FunctionModel(deterministic_judge), output_type=NativeOutput(PatchVerdict), retries=2)
    ledger = ReviewLedger(tmp_path / "ci.db")
    wf = WorkflowConfig("ci_fixture", 3, False, "mock-a", "mock-b")
    _, metrics = evaluate_dataframe(df, wf, "ci_run", agent_a, agent_b, ledger, skip_semgrep=True)
    assert metrics["schema_valid_rate"] >= 0.98
yaml.github/workflows/ci.ymlGitHub Actions workflow running unit tests and the 50-patch CI fixture on every push
name: Patch Review Workbench CI

on:
  push:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -e .
      - name: Run unit tests and 50-patch fixture
        run: pytest -v
bashGenerate the 50-patch fixture and run pytest locally
python scripts/generate_ci_fixture.py
pytest -v
OutputExpected pytest run showing all four test suites passing
tests/test_workbench.py::test_diff_normalization_context_width PASSED
tests/test_workbench.py::test_pydantic_ai_schema_retry_recovers_on_second_attempt PASSED
tests/test_workbench.py::test_abstention_routing_and_sqlite_override PASSED
tests/test_workbench.py::test_ci_50_patch_fixture_enforces_98_percent_schema_validity PASSED
4 passed in <seconds>s
Stage 10 Checkpoint

Confirm pytest -v passes all four tests locally with zero external network calls, and verify .github/workflows/ci.yml is committed to the repository.

Stage 11 · ship3 hours

Publish the technical README and exported artifacts

Export MLflow comparison tables and sample traces, attribute all three Kaggle datasets, report tier-by-tier held-out scores, and summarize five recurring bug categories both judges missed.

A code repository without reproducible evaluation tables and failure analysis looks like a demo rather than a completed engineering audit. Export your MLflow validation comparison, held-out confusion tables, and five sample traces into reports/ so a reader can inspect them directly on GitHub.

Required sections for README.md and matching artifact files
README SectionSource ArtifactWhat to Include
Setup and Commandspyproject.toml, scripts/Exact Python version, Semgrep rules commit SHA, Ollama model tags, and commands to reproduce splits, MLflow, marimo, and pytest.
Dataset Attributionsdata/splits/manifest.jsonMIT license for CTSSB-1M, CC0 for 136K Python Problems, and CC BY 4.0 credit to Abiram Bharathi S.A. for the 1.3M AI Commits dataset.
MLflow Workflow Comparisondata/splits/mlflow_workflow_comparison.csvValidation accuracy, precision, abstention share, median and p95 latency in milliseconds, and schema retry counts for both workflows.
Held-Out Test Auditreports/source_summary.csv, reports/tier_summary.csv, reports/confusion_panel.csvSingle-judge vs unanimous two-model precision, recall, abstention rate by tier, and either precision gain or high-baseline ceiling.
Five Documented False Negativesreports/false_negatives.csvFive distinct bug classes both models unanimously approved, each with patch ID, root cause, and why Semgrep also missed it.
bashExport five sample MLflow traces as JSON and verify Git status stays clean of raw data
python -c "import json, mlflow; from pathlib import Path; mlflow.set_tracking_uri('http://127.0.0.1:5000'); exp = mlflow.get_experiment_by_name('patch-review-workbench'); traces = mlflow.search_traces(locations=[exp.experiment_id], max_results=5) if exp else []; Path('reports/sample_traces.json').write_text(traces.to_json(orient='records', indent=2) if hasattr(traces, 'to_json') else json.dumps([]), encoding='utf-8'); print('Exported sample traces to reports/sample_traces.json')"
git status

Review every item in git status before pushing. Keep raw Kaggle CSVs, Parquet splits, mlflow.db, review_ledger.db, vendor/semgrep-rules, and API tokens untracked. Commit README.md, app/triage_app.py, reports/*.csv, reports/sample_traces.json, tests/, and .github/workflows/ci.yml.

Stage 11 Checkpoint

Verify the core build checks: the split script exits 0 with zero overlap, offline Semgrep writes JSON, and schema validity reaches 98 percent. Then confirm the held-out tables, live marimo SQLite updates, side-by-side MLflow runs, CI workflow, and README failure analysis are all complete.

Troubleshooting

Semgrep fails on Windows with a UnicodeEncodeError or charmap error while scanning Python files.

Set $env:PYTHONUTF8 = '1' in PowerShell and persist it with [System.Environment]::SetEnvironmentVariable('PYTHONUTF8', '1', 'User'), then reopen your terminal. The semgrep_runner.py wrapper also passes PYTHONUTF8=1 into the subprocess environment.

Pydantic AI raises a connection error against http://localhost:11434/v1 or reports model not found.

Start Ollama locally with ollama serve if the desktop service is not running. Then run ollama list to confirm qwen2.5-coder:7b and deepseek-coder:6.7b match the exact --judge-a and --judge-b tags.

Local inference takes more than 30 seconds per patch or swaps heavily on an 8 GB RAM machine.

Switch to the smaller sibling models qwen2.5-coder:3b and deepseek-coder:1.3b via ollama pull, pass both tags through --judge-a and --judge-b, and run scripts/run_workflows.py --limit 20 first to measure per-patch latency.

Schema validity falls below 98 percent with repeated UnexpectedModelBehavior exceptions.

Check that your local Ollama version is 0.5.0 or newer so NativeOutput uses grammar-constrained JSON schema decoding. Keep prompts under 3,500 characters of diff text and verify retries=2 is set on each Agent.

SQLite raises database is locked while MLflow and marimo run at the same time.

Keep MLflow on its own sqlite:///mlflow.db backend and the workbench ledger on review_ledger.db. Never point both services at the same SQLite file.

Kaggle CLI returns 401 Unauthorized or build_splits.py raises KeyError on a dataset column.

Re-authenticate using kaggle auth login or a fresh KAGGLE_API_TOKEN from your Kaggle account API settings page. If a column name mismatches, re-run python scripts/inspect_datasets.py and copy the exact header string into config/dataset_schema.json.

Done when

  • The split script prints row counts by source and split and exits with status zero when no patch identifier appears in multiple splits.
  • Local Semgrep Community Edition scans the CTSSB-1M sample offline and writes structured JSON findings without calling any hosted service.
  • Both Ollama judges return valid Pydantic AI verdict objects on at least 98 percent of test patches after bounded retries.
  • On the held-out test split, the summary table compares single-judge and unanimous two-model precision alongside abstention share and records either a precision gain or a high-baseline ceiling.
  • Every judge disagreement enters the SQLite abstention queue, and resolving an item in marimo updates the persisted ledger immediately.
  • The local MLflow UI displays side-by-side runs for at least two review workflows using identical Ollama models with full traces and latency percentiles.
  • Unit tests and the 50-patch CI fixture pass cleanly, and the README reports held-out confusion tables plus five documented false negatives.

Deliverables

  • A Git repository containing the dataset sampling scripts, Semgrep wrapper, dual-judge Pydantic AI runner and SQLite ledger.
  • A reactive marimo triage notebook stored as a versioned Python file that reads and updates the SQLite review queue.
  • Exported MLflow comparison tables and open trace samples for two review workflows evaluated on identical local models.
  • A technical README covering setup steps, dataset attributions, tier-by-tier test scores and five analyzed failure cases.

How to measure it

Report precision and recall on the held-out CTSSB-1M and Python problem test splits for each individual model and for the unanimous two-model panel. Record unanimous-call precision beside the abstention rate, aiming for an 8-point precision gain where single-model accuracy leaves headroom while keeping abstention between 15 and 45 percent. Compare both review workflows in MLflow by pass accuracy alongside median latency in milliseconds and schema retry counts.

Going further

  • Author custom local YAML Semgrep rules targeting the five false-negative bug classes from your held-out audit, then measure how many catches move from LLM review to static analysis.
  • Export confirmed reject verdicts from review_ledger.db into SARIF 2.1.0 format so findings render inline in GitHub code scanning alerts.
  • Add a Python ast pre-filter before judge inference that skips comment-only or whitespace-only diffs and logs saved judge milliseconds in MLflow.
  • Add a calibration chart to app/triage_app.py grouping two-model agreement and false-negative rates by Python AST construct such as loops, comprehensions, and exception blocks.

Bounty stretch goals

  • Add a third local Ollama judge as a tie-breaker mode in MLflow and measure whether majority voting beats abstention on precision.
  • Connect Open Code Review or Arm Metis to the same local Ollama endpoint and compare its line-level defect recall with your custom runner.
  • Estimate a tiered routing bill from recorded token counts by pricing unanimous versus abstained cohorts against published provider rates.
  • Train a small classifier on authorship records from the open-source commits corpus to prioritize high-risk diffs before judge inference.

References

Reporting behind this quest

An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.