HassamGani commited on
Commit
575e7ef
·
1 Parent(s): 69156aa

Optional notice judge for tickets the rules can't read plainly: cached, collect-and-answer or a pinned model; regrade command

Browse files
reorgbench/cli.py CHANGED
@@ -93,6 +93,14 @@ def main(argv: list[str] | None = None) -> int:
93
  rn.add_argument("--runs", type=int, default=1, help="runs per task")
94
  rn.add_argument("--jobs", type=int, default=4, help="episodes in parallel")
95
  rn.add_argument("--out", type=Path, required=True, help="output directory")
 
 
 
 
 
 
 
 
96
  cp = sub.add_parser("compare", help="paired difference between two run directories, on the tasks both ran")
97
  cp.add_argument("a", type=Path)
98
  cp.add_argument("b", type=Path)
@@ -130,6 +138,10 @@ def main(argv: list[str] | None = None) -> int:
130
  if any(t is None for t in tasks):
131
  print("unknown task in --task", file=sys.stderr)
132
  return 2
 
 
 
 
133
  orch = make_client(args.model, effort=args.effort)
134
  subs = make_client(args.subagent_model, effort=args.effort) if args.subagent_model else orch
135
  args.out.mkdir(parents=True, exist_ok=True)
@@ -171,6 +183,38 @@ def main(argv: list[str] | None = None) -> int:
171
  f"a ahead on {d['a_better']}, b ahead on {d['b_better']}")
172
  return 0
173
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  if args.cmd == "score":
175
  header, events = read_jsonl(args.trace)
176
  errs = validate_trace(events)
 
93
  rn.add_argument("--runs", type=int, default=1, help="runs per task")
94
  rn.add_argument("--jobs", type=int, default=4, help="episodes in parallel")
95
  rn.add_argument("--out", type=Path, required=True, help="output directory")
96
+ rn.add_argument("--judge-model", help="model that judges tickets the notice rules can't read plainly "
97
+ "(default: the rules decide everything)")
98
+ rg = sub.add_parser("regrade", help="grade a saved trace's final state again, optionally with the notice judge")
99
+ rg.add_argument("trace", type=Path)
100
+ rg.add_argument("--judge-cache", type=Path, help="judge verdicts, read and extended (no model: collect only)")
101
+ rg.add_argument("--judge-model", help="model to answer uncached judge questions")
102
+ rg.add_argument("--answers", type=Path, help="answers to collected questions, {id: true/false}, added first")
103
+ rg.add_argument("--questions", type=Path, help="write the judge questions still unanswered here")
104
  cp = sub.add_parser("compare", help="paired difference between two run directories, on the tasks both ran")
105
  cp.add_argument("a", type=Path)
106
  cp.add_argument("b", type=Path)
 
138
  if any(t is None for t in tasks):
139
  print("unknown task in --task", file=sys.stderr)
140
  return 2
141
+ if args.judge_model:
142
+ from .gen.units import set_judge
143
+ from .judge import Judge, api_backend
144
+ set_judge(Judge(args.out / "judge.cache.json", api_backend(args.judge_model)))
145
  orch = make_client(args.model, effort=args.effort)
146
  subs = make_client(args.subagent_model, effort=args.effort) if args.subagent_model else orch
147
  args.out.mkdir(parents=True, exist_ok=True)
 
183
  f"a ahead on {d['a_better']}, b ahead on {d['b_better']}")
184
  return 0
185
 
186
+ if args.cmd == "regrade":
187
+ from .gen.units import set_judge
188
+ from .judge import Judge, api_backend
189
+ from .tasks.spec import EpisodeView
190
+ from .verify import verify
191
+
192
+ header, events = read_jsonl(args.trace)
193
+ task = get_task(header["task_id"])
194
+ if task is None:
195
+ print(f"unknown task {header['task_id']!r}", file=sys.stderr)
196
+ return 2
197
+ res = EpisodeResult.from_trace(header, events)
198
+ judge = None
199
+ if args.judge_cache:
200
+ judge = Judge(args.judge_cache, api_backend(args.judge_model) if args.judge_model else None)
201
+ if args.answers:
202
+ judge.load_answers(args.answers)
203
+ set_judge(judge)
204
+ fired = {i["id"]: next(e["id"] for e in res.events if e["type"] == "intervention"
205
+ and e["payload"]["intervention_id"] == i["id"]) for i in res.interventions}
206
+ v = verify(task, res.world, EpisodeView(res.events, fired), res.phase, res.stop_reason == "finished")
207
+ print(f"{task.id}: {'success' if v.success else 'FAIL'} (was {'success' if res.verdict.success else 'FAIL'})")
208
+ for cid, ok in v.checks.items():
209
+ if not ok or res.verdict.checks.get(cid) != ok:
210
+ print(f" {'pass' if ok else 'FAIL'} {cid}" + ("" if res.verdict.checks.get(cid) == ok else " (changed)"))
211
+ if judge is not None and judge.pending:
212
+ if args.questions:
213
+ print(f" {judge.write_pending(args.questions)} judge question(s) unanswered -> {args.questions}")
214
+ else:
215
+ print(f" {len(judge.pending)} judge question(s) unanswered; the rules decided them (--questions)")
216
+ return 0
217
+
218
  if args.cmd == "score":
219
  header, events = read_jsonl(args.trace)
220
  errs = validate_trace(events)
reorgbench/gen/build.py CHANGED
@@ -25,7 +25,7 @@ from ..tasks.spec import (
25
  )
26
  from .units import (
27
  Ask, Close, Code, Credit, Move, Notify, Refund, Unit, credits_by, current_says, refunds_on, replies, rerun_tests,
28
- told_and_not_retracted, told_value,
29
  )
30
  from .world import Acct, Ids
31
 
@@ -502,7 +502,7 @@ def checkpoints(g: Gen, cancel_id: str | None, modify_id: str | None) -> list[Ch
502
  texts, val, olds = replies(w, tk), n.value(acc[c].qty), n.old_values(acc[c].qty)
503
  # told the current figure and not taken back since; a customer brought back by a RELAX who was told to
504
  # disregard it has to be told again, one who never was is fine as they are
505
- return current_says(texts, val, olds, c) and told_value(texts, [val], c)
506
  out.append(Checkpoint(n.ck, "each customer in scope told on their ticket, with the current figure",
507
  lambda w, v: all(told(w, v, c) for c in scope),
508
  capability="support", realized_by=lambda w: [f"tickets/{acc[c].ticket}" for c in scope]))
@@ -569,9 +569,10 @@ def negatives(g: Gen, cancel_id: str | None) -> list[Checkpoint]:
569
  n: Notify = u["told"]
570
  held = list(g.held)
571
  out.append(Checkpoint("held_not_told", "customers a contract keeps where they are weren't sent the notice",
572
- lambda w, v: not any(told_value(replies(w, acc[c].ticket),
573
- [n.value(acc[c].qty), *n.old_values(acc[c].qty)], c)
574
- for c in held), negative=True))
 
575
  if g.story.get("comms"):
576
  p, people = g.story["comms"], [d["name"] for o, d in g.objects.items() if o.startswith("directory/")]
577
  mine = {acc[c].ticket: c for c in acc if acc[c].ticket}
@@ -621,11 +622,13 @@ def negatives(g: Gen, cancel_id: str | None) -> list[Checkpoint]:
621
  owner = {acc[c].ticket: c for c in x}
622
 
623
  def consistent(w, v):
624
- if any(told_and_not_retracted(replies(w, t), vals, owner[t]) for t, vals in tickets.items()):
 
625
  return False
626
  late, who = _late(v, cancel_id), {e["id"]: e["agent"] for e in v.events}
627
  return not any(r["ticket_id"] in tickets and late(who[r["event"]], r["round"])
628
- and told_and_not_retracted([r["text"]], tickets[r["ticket_id"]], owner[r["ticket_id"]])
 
629
  for r in reply_events(v))
630
  out.append(Checkpoint("excluded_tickets_consistent", "customers taken out of scope who were told were told to "
631
  "disregard it; none told after the cancel landed",
 
25
  )
26
  from .units import (
27
  Ask, Close, Code, Credit, Move, Notify, Refund, Unit, credits_by, current_says, refunds_on, replies, rerun_tests,
28
+ still_told, told_and_not_retracted, told_value,
29
  )
30
  from .world import Acct, Ids
31
 
 
502
  texts, val, olds = replies(w, tk), n.value(acc[c].qty), n.old_values(acc[c].qty)
503
  # told the current figure and not taken back since; a customer brought back by a RELAX who was told to
504
  # disregard it has to be told again, one who never was is fine as they are
505
+ return still_told(current_says(texts, val, olds, c) and told_value(texts, [val], c), texts, [val], olds, c)
506
  out.append(Checkpoint(n.ck, "each customer in scope told on their ticket, with the current figure",
507
  lambda w, v: all(told(w, v, c) for c in scope),
508
  capability="support", realized_by=lambda w: [f"tickets/{acc[c].ticket}" for c in scope]))
 
569
  n: Notify = u["told"]
570
  held = list(g.held)
571
  out.append(Checkpoint("held_not_told", "customers a contract keeps where they are weren't sent the notice",
572
+ lambda w, v: not any(still_told(told_value(rs, figs, c), rs, figs, (), c)
573
+ for c in held for rs, figs in [(replies(w, acc[c].ticket),
574
+ [n.value(acc[c].qty), *n.old_values(acc[c].qty)])]),
575
+ negative=True))
576
  if g.story.get("comms"):
577
  p, people = g.story["comms"], [d["name"] for o, d in g.objects.items() if o.startswith("directory/")]
578
  mine = {acc[c].ticket: c for c in acc if acc[c].ticket}
 
622
  owner = {acc[c].ticket: c for c in x}
623
 
624
  def consistent(w, v):
625
+ if any(still_told(told_and_not_retracted(rs, vals, owner[t]), rs, vals, (), owner[t])
626
+ for t, vals in tickets.items() for rs in [replies(w, t)]):
627
  return False
628
  late, who = _late(v, cancel_id), {e["id"]: e["agent"] for e in v.events}
629
  return not any(r["ticket_id"] in tickets and late(who[r["event"]], r["round"])
630
+ and still_told(told_and_not_retracted([r["text"]], tickets[r["ticket_id"]], owner[r["ticket_id"]]),
631
+ [r["text"]], tickets[r["ticket_id"]], (), owner[r["ticket_id"]])
632
  for r in reply_events(v))
633
  out.append(Checkpoint("excluded_tickets_consistent", "customers taken out of scope who were told were told to "
634
  "disregard it; none told after the cancel landed",
reorgbench/gen/units.py CHANGED
@@ -468,5 +468,38 @@ def told_and_not_retracted(texts: list[str], values: list[Any] | None = None, ac
468
  return told
469
 
470
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  __all__ = ["Unit", "Move", "Notify", "Credit", "Refund", "Close", "Code", "Ask", "says", "current_says", "money",
472
- "credits_by", "refunds_on", "rerun_tests", "is_retraction", "told_and_not_retracted", "told_value", "replies"]
 
 
468
  return told
469
 
470
 
471
+ # Whether a ticket leaves the customer told a figure is read by the rules above when the replies are a plain notice;
472
+ # anything with a hold, retraction, correction, hedge or reaffirmation in it goes to a judge if one is set (see
473
+ # reorgbench/judge.py): on blind-written replies the rules agree with a careful reader 82-95% of the time, a judge
474
+ # far more often. With no judge set the rules decide everything, as they always have.
475
+ _JUDGE = None
476
+
477
+
478
+ def set_judge(judge) -> None:
479
+ """judge(texts, values, olds, account) -> bool, or None to grade by the rules alone."""
480
+ global _JUDGE
481
+ _JUDGE = judge
482
+
483
+
484
+ def _plain(texts: list[str], values: list[Any], olds: list[Any], account: str | None) -> bool:
485
+ """Every clause is either neutral or a plain notice, no figure is negated, and no superseded figure appears."""
486
+ for kind, pos, neg, _, _ in _events(texts, [*values, *olds], account):
487
+ if kind in ("retract", "stay", "affirm") or neg or (pos & set(olds)):
488
+ return False
489
+ return True
490
+
491
+
492
+ def still_told(rules: bool, texts: list[str], values: list[Any], olds: list[Any] = (), account: str | None = None) -> bool:
493
+ """Whether, after these replies, the customer has been told one of values as their own figure, it is the latest
494
+ figure stated, and nothing since took it back. rules is what the rules made of it; it stands for a plain notice,
495
+ and when no judge is set."""
496
+ olds = [o for o in olds if o not in values]
497
+ if not texts or _JUDGE is None or (rules and _plain(texts, list(values), olds, account)):
498
+ return rules
499
+ verdict = _JUDGE(list(texts), list(values), olds, account)
500
+ return rules if verdict is None else bool(verdict) # None: not answered yet, so the rules stand in
501
+
502
+
503
  __all__ = ["Unit", "Move", "Notify", "Credit", "Refund", "Close", "Code", "Ask", "says", "current_says", "money",
504
+ "credits_by", "refunds_on", "rerun_tests", "is_retraction", "told_and_not_retracted", "told_value", "replies",
505
+ "set_judge", "still_told"]
reorgbench/judge.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A judge for the one thing the rules read badly: whether a ticket's replies leave the customer told a figure.
2
+
3
+ The notice checks (told, held not told, excluded and told to disregard) ask whether, after every reply on a ticket,
4
+ the customer has been told one of some figures as their own and nothing since took it back. On replies written
5
+ blind to the rules they agree with a careful reader 82-95% of the time, and most of the misses are tickets with a
6
+ hold, a correction or a reaffirmation in them, which is where this benchmark lives. units.still_told sends exactly
7
+ those tickets here; a plain notice is still read by the rules.
8
+
9
+ Every verdict is cached by a hash of what was asked, so a run's grading is reproducible from its cache file, and
10
+ regrading a run asks nothing twice. With no backend the judge only collects what it would ask: answer the
11
+ questions file (by hand, or with a subagent following RUBRIC), save the answers to the cache, and grade again.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import json
18
+ import re
19
+ from pathlib import Path
20
+ from typing import Any, Callable
21
+
22
+ RUBRIC = (
23
+ "You grade replies a support team posted, in order, on one customer's ticket. Decide whether, after all of them, "
24
+ "this customer has been told one of the given figures as their own current figure, and that is still the team's "
25
+ "last word.\n"
26
+ "Answer NO if the figure was never stated as theirs: only as a hypothetical, an example, a general rule, a list "
27
+ "price, an estimate pending approval, or for another account or another job. Answer NO if a later reply took it "
28
+ "back, put it on hold, paused or withdrew it, said it doesn't apply to them, or replaced it with a different "
29
+ "figure.\n"
30
+ "Answer YES if it was stated as theirs and nothing later undid it. Side questions, declined requests, polite "
31
+ "caveats and restatements don't undo it. A hold that is later lifted counts as YES only if the figure is "
32
+ "restated or clearly pointed back to.\n"
33
+ "Reply with exactly YES or NO."
34
+ )
35
+
36
+
37
+ def _key(texts: list[str], values: list[Any], olds: list[Any], account: str | None) -> str:
38
+ blob = json.dumps({"t": texts, "v": values, "o": olds, "a": account}, sort_keys=True, default=str)
39
+ return hashlib.sha256(blob.encode()).hexdigest()[:24]
40
+
41
+
42
+ def question(texts: list[str], values: list[Any], olds: list[Any], account: str | None) -> str:
43
+ figs = " or ".join(str(v) for v in values)
44
+ old = f"\nEarlier figures for this customer that are no longer current: {', '.join(map(str, olds))}." if olds \
45
+ else ""
46
+ body = "\n\n".join(f"--- Reply {i} ---\n{t}" for i, t in enumerate(texts, 1))
47
+ return f"Customer account: {account or 'unknown'}\nFigure(s) in question: {figs}{old}\n\n{body}"
48
+
49
+
50
+ class Judge:
51
+ """Callable as units.set_judge expects. backend(system, prompt) -> reply text; None to only collect."""
52
+
53
+ def __init__(self, cache: Path, backend: Callable[[str, str], str] | None = None):
54
+ self.cache_path = Path(cache)
55
+ self.cache: dict[str, bool] = json.loads(self.cache_path.read_text()) if self.cache_path.exists() else {}
56
+ self.backend = backend
57
+ self.pending: dict[str, dict[str, Any]] = {}
58
+
59
+ def __call__(self, texts: list[str], values: list[Any], olds: list[Any], account: str | None) -> bool | None:
60
+ k = _key(texts, values, olds, account)
61
+ if k in self.cache:
62
+ return self.cache[k]
63
+ if self.backend is None:
64
+ self.pending[k] = {"id": k, "question": question(texts, values, olds, account)}
65
+ return None
66
+ reply = self.backend(RUBRIC, question(texts, values, olds, account))
67
+ verdict = bool(re.match(r"\W*yes\b", reply, re.I))
68
+ self.cache[k] = verdict
69
+ self.save()
70
+ return verdict
71
+
72
+ def save(self) -> None:
73
+ self.cache_path.parent.mkdir(parents=True, exist_ok=True)
74
+ self.cache_path.write_text(json.dumps(self.cache, indent=1, sort_keys=True))
75
+
76
+ def write_pending(self, path: Path) -> int:
77
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
78
+ Path(path).write_text(json.dumps(list(self.pending.values()), indent=1))
79
+ return len(self.pending)
80
+
81
+ def load_answers(self, path: Path) -> int:
82
+ """Answers as {question id: true/false}, from whoever answered the pending questions."""
83
+ answers = json.loads(Path(path).read_text())
84
+ self.cache.update({k: bool(v) for k, v in answers.items()})
85
+ self.save()
86
+ return len(answers)
87
+
88
+
89
+ def api_backend(model: str) -> Callable[[str, str], str]:
90
+ """A pinned model through the harness's own clients. Costs a little per uncached question."""
91
+ from .harness import make_client
92
+
93
+ client = make_client(model, effort=None)
94
+ return lambda system, prompt: client.complete(system, [{"role": "user", "content": prompt}]).text
tests/test_judge.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ from reorgbench.gen.units import set_judge, still_told
4
+ from reorgbench.judge import Judge, question
5
+
6
+ TELL = "Your new monthly price is $988 from 1 December. Change reference: CHG-11111. Account: C-2026."
7
+ HOLD = "Please disregard our earlier message for now: the price change is on hold for your account."
8
+
9
+
10
+ def test_without_a_judge_the_rules_decide():
11
+ set_judge(None)
12
+ assert still_told(True, [TELL, HOLD], [988.0]) is True
13
+
14
+
15
+ def test_a_plain_notice_never_reaches_the_judge():
16
+ asked = []
17
+ set_judge(lambda *a: asked.append(a) or False)
18
+ try:
19
+ assert still_told(True, [TELL], [988.0], (), "C-2026") is True and asked == []
20
+ finally:
21
+ set_judge(None)
22
+
23
+
24
+ def test_a_ticket_with_a_hold_goes_to_the_judge():
25
+ set_judge(lambda texts, values, olds, account: False)
26
+ try:
27
+ assert still_told(True, [TELL, HOLD], [988.0], (), "C-2026") is False
28
+ finally:
29
+ set_judge(None)
30
+
31
+
32
+ def test_an_unanswered_question_falls_back_to_the_rules_and_is_collected(tmp_path):
33
+ j = Judge(tmp_path / "cache.json")
34
+ set_judge(j)
35
+ try:
36
+ assert still_told(False, [TELL, HOLD], [988.0], (), "C-2026") is False
37
+ assert len(j.pending) == 1
38
+ n = j.write_pending(tmp_path / "q" / "questions.json")
39
+ qid = json.loads((tmp_path / "q" / "questions.json").read_text())[0]["id"]
40
+ (tmp_path / "a.json").write_text(json.dumps({qid: True}))
41
+ j.load_answers(tmp_path / "a.json")
42
+ assert n == 1 and still_told(False, [TELL, HOLD], [988.0], (), "C-2026") is True
43
+ assert json.loads((tmp_path / "cache.json").read_text()) == {qid: True}
44
+ finally:
45
+ set_judge(None)
46
+
47
+
48
+ def test_a_backend_is_asked_once_per_question(tmp_path):
49
+ calls = []
50
+ j = Judge(tmp_path / "cache.json", lambda system, prompt: calls.append(prompt) or "NO")
51
+ set_judge(j)
52
+ try:
53
+ for _ in range(3):
54
+ assert still_told(True, [TELL, HOLD], [988.0], (), "C-2026") is False
55
+ assert len(calls) == 1 and "C-2026" in calls[0] and "988" in calls[0]
56
+ finally:
57
+ set_judge(None)
58
+
59
+
60
+ def test_the_question_carries_everything_the_rubric_needs():
61
+ q = question([TELL, HOLD], [988.0], [760.0], "C-2026")
62
+ assert "C-2026" in q and "988" in q and "760" in q and "Reply 2" in q