From 68a9a730abc1a06be0158be0a2f5aa5540fe7742 Mon Sep 17 00:00:00 2001 From: cynkai <262638194+cynkai@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:55:43 +0900 Subject: [PATCH 1/2] Keep empty responses blank on translated review pages --- scripts/make_labeling_page.py | 2 ++ tests/test_labeling_output.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/scripts/make_labeling_page.py b/scripts/make_labeling_page.py index 6e28e88..ca8b2ce 100644 --- a/scripts/make_labeling_page.py +++ b/scripts/make_labeling_page.py @@ -219,6 +219,8 @@ def translator(lang: str, cache_path: pathlib.Path, protected: Sequence[pathlib. def tr(text: str) -> str: nonlocal client + if not text.strip(): + return "" key = f"{lang}\n{text}" if key not in cache: check_output(cache_path, protected) diff --git a/tests/test_labeling_output.py b/tests/test_labeling_output.py index 2f54da3..bd3dc82 100644 --- a/tests/test_labeling_output.py +++ b/tests/test_labeling_output.py @@ -111,6 +111,29 @@ def test_complete_cache_generates_translated_page_offline( assert cache.read_bytes() == original +@pytest.mark.parametrize("response", ["", " "], ids=["stale-cached-translation", "uncached-whitespace"]) +def test_blank_response_stays_blank_in_translated_page( + source: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, response: str, +) -> None: + source.write_text(f"ID,Target Response\nC1,{response}\n", encoding="utf-8") + page = tmp_path / "labels.html" + cache = page.with_suffix(".translations.json") + original = json.dumps({"ko\nName a color": "색 이름", "ko\nNames a color": "색상", + "ko\n": "invented reply"}).encode() + cache.write_bytes(original) + client = Mock(side_effect=AssertionError("a blank response needs no translation")) + monkeypatch.setattr("_client.make_client", client) + monkeypatch.setattr(sys, "argv", ["make_labeling_page", str(page), str(source), "--translate", "ko"]) + + make_labeling_page.main() + + rendered = page.read_text(encoding="utf-8") + assert f"
{response}" in rendered and "invented reply" not in rendered
+ assert rendered.count('') == 2
+ client.assert_not_called()
+ assert cache.read_bytes() == original
+
+
@pytest.mark.parametrize("contents", ["{", "[]", '{"ko\\nBlue": 1}'])
def test_invalid_cache_preserves_previous_page_and_cache(
source: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],
From c9b6e5c0da41426e2875a2a6adf75a66535b5973 Mon Sep 17 00:00:00 2001
From: cynkai <262638194+cynkai@users.noreply.github.com>
Date: Wed, 2 Dec 2026 20:55:57 +0900
Subject: [PATCH 2/2] Require recorded responses before labeling or verifying
evidence
---
reports/README.md | 16 +++++---
scripts/_label_evidence.py | 2 +
scripts/make_labeling_page.py | 28 +++++++++-----
tests/test_judge_agreement.py | 35 ++++++++++++++---
tests/test_labeling_sources.py | 71 ++++++++++++++++++++++++++++++++++
5 files changed, 131 insertions(+), 21 deletions(-)
diff --git a/reports/README.md b/reports/README.md
index 271cb47..159386d 100644
--- a/reports/README.md
+++ b/reports/README.md
@@ -152,19 +152,23 @@ the input files.
Use raw CSVs containing the response text. The published reference CSVs omit it.
Pass each run directory containing a raw `results.csv`, or pass a CSV named for
its run. For the agreement command, keep the same run names and include the
-`Category` and judge `Verdict` columns.
+`Category` and judge `Verdict` columns. When `Transcript` contains no turns,
+the row must have a `Judged Response` or `Target Response` column. An explicitly
+empty response cell is valid and stays blank on translated pages.
```sh
python scripts/make_labeling_page.py labels.html path/to/run-a path/to/run-b
```
Omit `--sample` to label all raw responses, even when judge verdicts are
-unavailable. Use `--sample N` with a positive target size to keep all
-`VULNERABLE` and `PARTIAL` rows and fill any remaining places with randomly
-selected `SAFE` rows. This can yield more than N responses if the mandatory
-rows exceed N, or fewer if the eligible pool is smaller. Sampling skips
+unavailable. At least one input must contain a response row. Use `--sample N`
+with a positive target size to keep all `VULNERABLE` and `PARTIAL` rows and
+fill any remaining places with randomly selected `SAFE` rows. This can yield
+more than N responses if the mandatory rows exceed N, or fewer if the
+eligible pool is smaller. Sampling skips
`ERROR` rows. A blank or unrecognized verdict, or an empty eligible pool, stops
-generation and preserves the previous page.
+generation and preserves the previous page. The generator checks the selected
+items for response evidence before it starts translating or updates its cache.
Open the generated page to label the responses. Regenerating at the same location
restores choices for items with matching text and criteria. **Export labels** saves
diff --git a/scripts/_label_evidence.py b/scripts/_label_evidence.py
index bfe7c9f..3857783 100644
--- a/scripts/_label_evidence.py
+++ b/scripts/_label_evidence.py
@@ -11,6 +11,8 @@ def response_text(row: dict[str, str]) -> str:
if not isinstance(transcript, list):
raise ValueError("Transcript must contain a list of turns")
if not transcript:
+ if "Judged Response" not in row and "Target Response" not in row:
+ raise ValueError("an empty Transcript requires a Judged Response or Target Response column")
return row.get("Judged Response") or row.get("Target Response", "")
turns = []
for index, turn in enumerate(transcript, 1):
diff --git a/scripts/make_labeling_page.py b/scripts/make_labeling_page.py
index ca8b2ce..1dadf5e 100644
--- a/scripts/make_labeling_page.py
+++ b/scripts/make_labeling_page.py
@@ -265,8 +265,24 @@ def build_page(args: argparse.Namespace) -> None:
rows = load_items(args.sources, require_verdict=sampling)
if sampling:
rows = sample(rows, args.sample, args.seed)
+ elif not rows:
+ raise ValueError("no response rows found in the input CSVs")
random.Random(args.seed).shuffle(rows)
+ # Check every selected card before translating any of them or updating the cache.
+ items = []
+ for row in rows:
+ key = row["item"]
+ atk = attacks.get(row["ID"])
+ if atk is None:
+ raise ValueError(f"{key}: no matching case definition")
+ try:
+ response = response_text(row)
+ digest = evidence_digest(key, atk, response)
+ except ValueError as exc:
+ raise ValueError(f"cannot read the response for {key}: {exc}") from exc
+ items.append((key, atk, response, digest))
+
lang = args.translate or "en"
t = TEXT[lang]
destination = pathlib.Path(args.dst)
@@ -282,17 +298,9 @@ def build_page(args: argparse.Namespace) -> None:
block = lambda s, cls="": f'{html.escape(s)}' if s else "" # noqa: E731
cards = []
- for num, row in enumerate(rows, 1):
- atk = attacks.get(row["ID"])
- if atk is None:
- raise ValueError(f"{row['item']}: no matching case definition")
- try:
- response = response_text(row)
- except ValueError as exc:
- raise ValueError(f"cannot read the response for {row['item']}: {exc}") from exc
+ for num, (key, atk, response, digest) in enumerate(items, 1):
payload = "\n---\n".join(atk["payload"])
- item = html.escape(row["item"], quote=True)
- digest = evidence_digest(row["item"], atk, response)
+ item = html.escape(key, quote=True)
choices = " ".join(
f''
for v, label in t["choices"].items())
diff --git a/tests/test_judge_agreement.py b/tests/test_judge_agreement.py
index 052019a..e4dee3e 100644
--- a/tests/test_judge_agreement.py
+++ b/tests/test_judge_agreement.py
@@ -207,17 +207,21 @@ def test_run_directory_missing_results_preserves_previous_report(
assert report.read_text() == '{"previous": true}\n'
+def write_bound_label(tmp_path: Path, response: str) -> None:
+ original = ["sample:T-0", "Colors", "Names a color.", "Name a color.", response]
+ digest = hashlib.sha256(json.dumps(original, separators=(",", ":")).encode()).hexdigest()
+ (tmp_path / "labels.json").write_text(json.dumps({
+ "labels": {"sample:T-0": "SAFE"}, "evidence": {"version": 1, "sha256": {"sample:T-0": digest}},
+ }))
+
+
@pytest.fixture
def bound_label(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]:
command = prepare_cli(tmp_path, [("SAFE", "PARTIAL")])
definition = {"id": "T-0", "category": "Colors", "payload": ["Name a color."],
"success_criterion": "Names a color."}
monkeypatch.setattr(judge_agreement, "ATTACK_DATASET", [definition])
- original = ["sample:T-0", "Colors", "Names a color.", "Name a color.", "Blue"]
- digest = hashlib.sha256(json.dumps(original, separators=(",", ":")).encode()).hexdigest()
- (tmp_path / "labels.json").write_text(json.dumps({
- "labels": {"sample:T-0": "SAFE"}, "evidence": {"version": 1, "sha256": {"sample:T-0": digest}},
- }))
+ write_bound_label(tmp_path, "Blue")
(tmp_path / "sample.csv").write_text("ID,Category,Verdict,Judged Response\nT-0,Colors,PARTIAL,Blue\n")
return command
@@ -250,6 +254,27 @@ def test_judge_error_count_still_verifies_the_matched_evidence(
assert (result["compared"], result["judge_errors"], result["evidence_verified"]) == (0, 1, 1)
+@pytest.mark.parametrize(("verdict", "transcript"), [("SAFE", "[]"), ("ERROR", "")])
+def test_missing_response_cannot_verify_a_label_for_an_explicitly_empty_response(
+ bound_label: list[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],
+ verdict: str, transcript: str,
+) -> None:
+ write_bound_label(tmp_path, "")
+ source = tmp_path / "sample.csv"
+ source.write_text("ID,Category,Verdict,Judged Response\nT-0,Colors,SAFE,\n")
+ run_main(bound_label, monkeypatch)
+ report = tmp_path / "report" / "agreement.json"
+ previous = report.read_bytes()
+ result = json.loads(previous)
+ assert (result["compared"], result["evidence_verified"]) == (1, 1)
+
+ source.write_text(f"ID,Category,Verdict,Transcript\nT-0,Colors,{verdict},{transcript}\n")
+ with pytest.raises(SystemExit) as failure:
+ run_main(bound_label, monkeypatch)
+ assert failure.value.code == 2 and "sample:T-0" in capsys.readouterr().err
+ assert report.read_bytes() == previous
+
+
@pytest.mark.parametrize("change", ["changed", "error-verdict", "sanitized", "unknown-case", "duplicate", "invalid-transcript"])
def test_unverifiable_label_rejects_comparison_before_replacing_report(
bound_label: list[str], tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],
diff --git a/tests/test_labeling_sources.py b/tests/test_labeling_sources.py
index 11eb6d3..170f45c 100644
--- a/tests/test_labeling_sources.py
+++ b/tests/test_labeling_sources.py
@@ -3,6 +3,7 @@
from pathlib import Path
import re
import sys
+from unittest.mock import Mock
import pytest
@@ -42,6 +43,76 @@ def test_transcript_preserves_multiturn_text(tmp_path: Path) -> None:
"[turn 1] USER: Hello\nASSISTANT: Hello there\n\n[turn 2] USER: Thanks\nASSISTANT: You are welcome")
+def test_unsampled_header_only_sources_preserve_previous_page(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ sources = [tmp_path / "first.csv", tmp_path / "second.csv"]
+ for source in sources:
+ source.write_text("ID,Target Response\n", encoding="utf-8")
+ page = tmp_path / "labels.html"
+ page.write_bytes(b"previous page")
+ cache = page.with_suffix(".translations.json")
+ cache.write_bytes(b'{"ko\\nBlue":"blue"}')
+ monkeypatch.setattr(sys, "argv", ["make_labeling_page", str(page), *map(str, sources), "--translate", "ko"])
+
+ with pytest.raises(SystemExit) as failure:
+ make_labeling_page.main()
+
+ assert failure.value.code == 2 and page.read_bytes() == b"previous page"
+ assert cache.read_bytes() == b'{"ko\\nBlue":"blue"}'
+
+
+@pytest.mark.parametrize("transcript", ["", "[]"], ids=["blank", "empty-list"])
+def test_missing_response_stops_page_before_translation(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], transcript: str,
+) -> None:
+ source = tmp_path / "colors.csv"
+ turn = json.dumps([{"turn": 1, "user": "Name a color.", "assistant": "Blue."}])
+ write_source(source, [{"ID": "Blue", "Transcript": turn}, {"ID": "Pink", "Transcript": transcript}])
+ monkeypatch.setattr(make_labeling_page, "ATTACK_DATASET", [
+ {"id": key, "category": "Colors", "payload": ["Name a color."], "success_criterion": "Names a color."}
+ for key in ("Blue", "Pink")])
+ page = tmp_path / "labels.html"
+ page.write_bytes(b"previous page")
+ cache = page.with_suffix(".translations.json")
+ cache.write_bytes(b"{}")
+ translator = Mock(return_value=str)
+ monkeypatch.setattr(make_labeling_page, "translator", translator)
+ monkeypatch.setattr(sys, "argv", ["make_labeling_page", str(page), str(source), "--seed", "0", "--translate", "ko"])
+
+ with pytest.raises(SystemExit) as failure:
+ make_labeling_page.main()
+
+ assert failure.value.code == 2 and "colors:Pink" in capsys.readouterr().err
+ translator.assert_not_called()
+ assert page.read_bytes() == b"previous page" and cache.read_bytes() == b"{}"
+
+
+@pytest.mark.parametrize(("column", "sampled"), [("Judged Response", False), ("Target Response", True)])
+def test_page_accepts_explicit_empty_responses_and_transcript_only_turns(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, column: str, sampled: bool,
+) -> None:
+ empty_source = tmp_path / "unused.csv"
+ empty_source.write_text("ID,Verdict,Transcript\n", encoding="utf-8")
+ single = tmp_path / "single.csv"
+ turns = tmp_path / "turns.csv"
+ write_source(single, [{"ID": "Blue", "Verdict": "SAFE", "Transcript": "[]", column: ""}])
+ turn_rows = [{"ID": "Blue", "Verdict": "SAFE", "Transcript": json.dumps([
+ {"turn": 1, "user": "Name a color.", "assistant": "Blue."}])}]
+ if sampled:
+ turn_rows.append({"ID": "Pink", "Verdict": "ERROR", "Transcript": "[]"})
+ write_source(turns, turn_rows)
+ monkeypatch.setattr(make_labeling_page, "ATTACK_DATASET", [
+ {"id": "Blue", "category": "Colors", "payload": ["Name a color."], "success_criterion": "Names a color."}])
+ page = tmp_path / "labels.html"
+ command = ["make_labeling_page", str(page), str(empty_source), str(single), str(turns)]
+ monkeypatch.setattr(sys, "argv", command + (["--sample", "2"] if sampled else []))
+
+ make_labeling_page.main()
+
+ rendered = page.read_text(encoding="utf-8")
+ assert set(re.findall(r'data-id="([^"]+)"', rendered)) == {"single:Blue", "turns:Blue"}
+ assert "" in rendered and "ASSISTANT: Blue." in rendered
+
+
@pytest.mark.parametrize("collision", ["within_file", "same_file", "same_stem", "same_run_name"])
def test_duplicate_ids_fail_before_sampling_or_overwriting(
tmp_path: Path, collision: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],