HassamGani commited on
Commit
a436cab
·
unverified ·
1 Parent(s): 07a1a35

Grader: close reward hacks a red-team found on the oracle's own finished worlds

Browse files

- Late leavers: a ledger entry for them may be no more than their job owed; their new inbound ticket is
watched too; "disregard the earlier figure" keeps the figure that reply states, and "don't ignore" is
not a retraction.
- Held customers: sending the notice with no figure, or someone else's, counts as telling them.
- Replies: a question, "X or Y", a list of same-kind references, "(TBC)", "was a typo", "we'll send the
real figure shortly" and malformed amounts state no figure; questions and such hedges go to the judge.
- Records: a field added to a moved record fails unless it is sync_hold, a note, or another job's field.
- Code: every key and constant of the graded file must survive, not just the lines CI checks.

reorgbench/env/tools.py CHANGED
@@ -468,7 +468,7 @@ def _inbound(world: World, rnd: int, log: AccessLog) -> list[dict[str, Any]]:
468
  "entries": sorted(o for o, d in world.iter("ledger.entries") if d.get("customer_id") == c
469
  or d.get("invoice_id") in it.get("invoices", [])),
470
  "replies": {t: len((world.data(f"tickets/{t}") or {}).get("replies", []))
471
- for t in it.get("tickets", [])}}
472
  changed = True
473
  if changed:
474
  world.put("inbound/tickets", cfg, log)
 
468
  "entries": sorted(o for o, d in world.iter("ledger.entries") if d.get("customer_id") == c
469
  or d.get("invoice_id") in it.get("invoices", [])),
470
  "replies": {t: len((world.data(f"tickets/{t}") or {}).get("replies", []))
471
+ for t in [*it.get("tickets", []), it["ticket_id"]]}}
472
  changed = True
473
  if changed:
474
  world.put("inbound/tickets", cfg, log)
reorgbench/gen/build.py CHANGED
@@ -579,7 +579,10 @@ def negatives(g: Gen, cancel_id: str | None) -> list[Checkpoint]:
579
  n: Notify = u["told"]
580
  held = list(g.held)
581
  out.append(Checkpoint("held_not_told", "customers a contract keeps where they are weren't sent the notice",
582
- lambda w, v: not any(still_told(told_value(rs, figs, c), rs, figs, (), c)
 
 
 
583
  for c in held for rs, figs in [(replies(w, acc[c].ticket),
584
  [n.value(acc[c].qty), *n.old_values(acc[c].qty)])]),
585
  negative=True))
 
579
  n: Notify = u["told"]
580
  held = list(g.held)
581
  out.append(Checkpoint("held_not_told", "customers a contract keeps where they are weren't sent the notice",
582
+ # sent the notice at all, with their figure or without one (or with someone
583
+ # else's), and not taken back
584
+ lambda w, v: not any(still_told(told_value(rs, figs, c)
585
+ or told_and_not_retracted(rs, figs, c), rs, figs, (), c)
586
  for c in held for rs, figs in [(replies(w, acc[c].ticket),
587
  [n.value(acc[c].qty), *n.old_values(acc[c].qty)])]),
588
  negative=True))
reorgbench/gen/queue.py CHANGED
@@ -22,7 +22,7 @@ from . import company
22
  from .build import (ALL_ROLES, CI, HIRE_ORDER, LOOSE, NEVER, SIGNOFF, GenerationError, Knobs, base_objects,
23
  calibrate, make_task, make_world, tier_of)
24
  from .templates import TEMPLATES, Template
25
- from .units import is_retraction
26
  from .world import Acct, Ids
27
 
28
  QUEUE_ID = "ops-queue"
@@ -257,7 +257,10 @@ def _late_leavers(gens: list, shared: list[str], seed: int, attempt: int) -> lis
257
  "watch": {o: json.dumps(b.objects[o], sort_keys=True, default=str) for o in watch},
258
  "invoices": invs, "tickets": [a.ticket], "record": dict(b.objects[f"db.customers/{y}"])})
259
  b.story["late_leaver"] = y
260
- out.append({"gen": b, "customer": y, "ticket": a.ticket, "invoices": invs, "new": tid})
 
 
 
261
  if items:
262
  main.objects["inbound/tickets"] = {"items": items}
263
  return out
@@ -265,6 +268,7 @@ def _late_leavers(gens: list, shared: list[str], seed: int, attempt: int) -> lis
265
 
266
  def _left_alone_after(lls: list[dict]) -> Checkpoint:
267
  invs = {c: set(ll["invoices"]) for ll in lls for c in [ll["customer"]]}
 
268
 
269
  def ok(w, v):
270
  cfg = w.data("inbound/tickets") or {"items": []}
@@ -282,7 +286,9 @@ def _left_alone_after(lls: list[dict]) -> Checkpoint:
282
  return True
283
  cp = Checkpoint("late_leaver_left_alone", "nothing more done for a customer once they wrote in to say they're "
284
  "leaving", ok, negative=True)
285
- cp.allows = lambda d: any(d.get("customer_id") == y or d.get("invoice_id") in iv for y, iv in invs.items())
 
 
286
  return cp
287
 
288
 
 
22
  from .build import (ALL_ROLES, CI, HIRE_ORDER, LOOSE, NEVER, SIGNOFF, GenerationError, Knobs, base_objects,
23
  calibrate, make_task, make_world, tier_of)
24
  from .templates import TEMPLATES, Template
25
+ from .units import Credit, Refund, is_retraction
26
  from .world import Acct, Ids
27
 
28
  QUEUE_ID = "ops-queue"
 
257
  "watch": {o: json.dumps(b.objects[o], sort_keys=True, default=str) for o in watch},
258
  "invoices": invs, "tickets": [a.ticket], "record": dict(b.objects[f"db.customers/{y}"])})
259
  b.story["late_leaver"] = y
260
+ # the most any one ledger entry for them can be: what their job owed them before they wrote in
261
+ owed = max([u.amount(a.qty) for u in b.units.values() if isinstance(u, Credit)]
262
+ + [round(a.qty * u.rate, 2) for u in b.units.values() if isinstance(u, Refund)] + [0.0])
263
+ out.append({"gen": b, "customer": y, "ticket": a.ticket, "invoices": invs, "new": tid, "owed": owed})
264
  if items:
265
  main.objects["inbound/tickets"] = {"items": items}
266
  return out
 
268
 
269
  def _left_alone_after(lls: list[dict]) -> Checkpoint:
270
  invs = {c: set(ll["invoices"]) for ll in lls for c in [ll["customer"]]}
271
+ owed = {ll["customer"]: ll.get("owed", 0.0) for ll in lls}
272
 
273
  def ok(w, v):
274
  cfg = w.data("inbound/tickets") or {"items": []}
 
286
  return True
287
  cp = Checkpoint("late_leaver_left_alone", "nothing more done for a customer once they wrote in to say they're "
288
  "leaving", ok, negative=True)
289
+ # an entry made for them before they wrote in stands, but only up to what their job owed them
290
+ cp.allows = lambda d: any((d.get("customer_id") == y or d.get("invoice_id") in iv)
291
+ and abs(float(d.get("amount") or 0)) <= owed[y] + 0.005 for y, iv in invs.items())
292
  return cp
293
 
294
 
reorgbench/gen/units.py CHANGED
@@ -14,7 +14,8 @@ from ..env.world import AccessLog, World
14
  from ..tasks.hand.common import ci_green_after, entries, file_text, replies
15
  from ..tasks.spec import Step
16
 
17
- _NUM = r"(\d[\d,]*(?:\.\d+)?)"
 
18
  _MONEY = re.compile(rf"(?:US)?\$\s?{_NUM}|{_NUM}\s?(?:USD|dollars)\b|\bUSD\s?{_NUM}"
19
  rf"|(?<![\d$.,]){_NUM}(?=\s?(?:/\s?mo(?:nth)?\b|per month|a month|each month))", re.I)
20
  _SEP = r"[\s\-‐-―_.#]*"
@@ -68,6 +69,9 @@ class Unit:
68
  return self.key if self.ver == 0 else f"{self.key}_{self.ver + 1}"
69
 
70
 
 
 
 
71
  @dataclass
72
  class Move(Unit):
73
  """Set one field on every in-scope customer record."""
@@ -87,8 +91,12 @@ class Move(Unit):
87
  def row_ok(self, w: World, c: str, orig: dict, value: Any) -> bool:
88
  d = w.data(f"db.customers/{c}") or {}
89
  free = self.free.get(c, ())
 
 
 
90
  return (str(d.get(self.field_name, "")).lower() == str(value).lower()
91
- and all(d.get(k) == v for k, v in orig.items() if k != self.field_name and k not in free))
 
92
 
93
 
94
  @dataclass
@@ -152,6 +160,11 @@ class Code(Unit):
152
  if not ci_green_after(w, self.path):
153
  return False
154
  text = file_text(w, self.path)
 
 
 
 
 
155
  for oid in self.tests:
156
  t = w.data(oid) or {}
157
  if any(s not in text for s in t.get("must_contain", [])) or any(s in text for s in t.get("must_not_contain", [])):
@@ -217,7 +230,7 @@ _AUX = r"(?:'\w+)?(?:\s+(?:and\s+\S+|will|would|should|can|could|is|are|was|were
217
  _YOU = r"(?:you|your(?:\s+(?!other\b|second\b|another\b|sandbox\b)\S+)?\s+(?:account|workspace|organi[sz]ation|company|team|business|tenant)|account acct)\b"
218
  _HOLDER = rf"(?:{_YOU}|your(?:\s+\S+)?\s+(?:plan|subscription|hosting|region|price|pricing|rate)\b|it\b)"
219
  _BUT = r"(?!.*\b(?:else|other than|except|apart from|besides)\b)"
220
- _BAD = (r"(?:out of date|outdated|incorrect|wrong|inaccurate|invalid|void|premature|a mistake|an error|in error|"
221
  r"no longer (?:valid|correct|current|accurate)|not (?:correct|right|accurate|valid))")
222
 
223
  _SPLIT = re.compile(r"(?<=[.!?])(?<!\bvs\.)(?<!\be\.g\.)(?<!\bi\.e\.)\s+|\n+|[;:|](?!\d)|\s[-–—]+\s|—|,\s+(?:and|but|so)\s+|"
@@ -253,6 +266,9 @@ _WITHDRAW = re.compile("|".join([
253
  r"included|listed|contacted|emailed|messaged|stated|quoted)",
254
  r"(?<=hold off on )(?:the\s+)?fig\b|"
255
  r"\bjumped the gun|\bwrong (?:customer|account|ticket|person|recipient)|\btreat\b.*\bas void",
 
 
 
256
  rf"{_NOTE}(?:\s+\S+){{0,6}}?\s+(?:was|is|were)\s+(?:\S+\s+)?(?:{_BAD}|(?:meant|intended) for (?:another|a different|"
257
  r"someone))",
258
  rf"{_NOTE}(?:\s+\S+){{0,3}}?\s+(?:is |was |has been |as )?(?:retracted|withdrawn|rescinded|void)\b",
@@ -337,6 +353,7 @@ _POST_NEG = re.compile(r"^\W*(?:[\w-]+\s+){0,4}?(?:has been|have been|was|were|i
337
  r"a typo|a mistake|in error|retired|revoked|expired|deactivated|no longer (?:valid|correct|in use|being used|"
338
  r"used|applicable))\b|^\W*(?:[\w-]+\s+){0,3}?(?:as\s+)?(?:not|un)\s*(?:yet\s+)?(?:confirmed|final)\b|"
339
  r"^\W*(?:[\w-]+\s+){0,3}?(?:may|might|could)\s+(?:still\s+)?change\b|"
 
340
  r"^\W*(?:[\w-]+\s+){0,3}?belongs? to (?:a different|another|someone)", re.I)
341
  # "the $1,180 figure left out your add-on seats": the figure named as a thing being discussed, not stated as yours
342
  _MENTION = re.compile(r"^\W*(?:figure|quote|amount|number|estimate|projection)\b(?!\s+(?:is|of|for|applies|stands)\b)", re.I)
@@ -382,10 +399,26 @@ def _figures(clause: str, values: list[Any] | None) -> list[tuple[re.Match, Any]
382
  return out
383
 
384
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
  def _cue(c: str) -> tuple[str | None, bool]:
386
  """Whether a clause takes the notice back ("retract") or keeps the customer where they are ("stay"), and whether
387
  what it takes back is one named figure."""
388
  m = _DISREGARD.search(c)
 
 
389
  if m:
390
  obj = m.group(1)
391
  about = re.search(r"\b(?:about|regarding|concerning|re:|on the subject of)\b(.*)", obj)
@@ -438,6 +471,10 @@ def _events(texts: list[str], values: list[Any] | None, account: str | None = No
438
  negated = [v for m, v in figs if _PRE_NEG.search(clause[:m.start()]) or _POST_NEG.search(clause[m.end():])
439
  or _MENTION.match(clause[m.end():]) or moved(m)]
440
  stated = [] if options else [v for m, v in figs if v not in negated and not _HEDGE.search(clause[:m.start()])]
 
 
 
 
441
  ids = {x.upper() for x in _ACCT.findall(clause)}
442
  if elsewhere or (account and ids and account.upper() not in ids): # another account's figure
443
  stated = []
@@ -472,9 +509,12 @@ def _verdict(text: str, values: list[Any] | None, account: str | None = None) ->
472
  A stay cue after the reply has told the change ("remains on the corrected card", "you asked us to keep your
473
  current price") describes it; only an explicit retraction takes it back in the same breath."""
474
  out = None
475
- for kind, pos, _, _, stated in _events([text], values, account):
476
  if kind == "stay" and not pos and out == "tell":
477
  continue
 
 
 
478
  if kind == "retract" or (kind == "stay" and not pos):
479
  out = "retract"
480
  elif kind in ("notice", "affirm") or pos or (values is None and stated):
@@ -536,7 +576,8 @@ _NOT_PLAIN = re.compile(r"\b(?:or|between|range|estimat\w*|likely|probabl\w*|ten
536
  r"unless|depend\w*|approx\w*|around|about|roughly|guess|project\w*|last|previous\w*|prior|"
537
  r"earlier|was|were|used to|not|no|never|no longer|disregard|ignore|cancel\w*|withdr\w*|"
538
  r"retract\w*|paus\w*|delay\w*|postpon\w*|instead|replac\w*|supersed\w*|another|other|both|"
539
- r"each|per|subtotal|plus|minus|added|deduct\w*|adjust\w*|thereabouts|confirm\w*|until)\b|n't\b",
 
540
  re.I)
541
 
542
 
 
14
  from ..tasks.hand.common import ci_green_after, entries, file_text, replies
15
  from ..tasks.spec import Step
16
 
17
+ # a well-formed amount: "1,180" or "1180", at most two decimals; "$5,98", "$0598" and "$598.004" state no amount
18
+ _NUM = r"((?:[1-9]\d{0,2}(?:,\d{3})+|0|[1-9]\d*)(?:\.\d{1,2})?)(?![.,]?\d)"
19
  _MONEY = re.compile(rf"(?:US)?\$\s?{_NUM}|{_NUM}\s?(?:USD|dollars)\b|\bUSD\s?{_NUM}"
20
  rf"|(?<![\d$.,]){_NUM}(?=\s?(?:/\s?mo(?:nth)?\b|per month|a month|each month))", re.I)
21
  _SEP = r"[\s\-‐-―_.#]*"
 
69
  return self.key if self.ver == 0 else f"{self.key}_{self.ver + 1}"
70
 
71
 
72
+ _NOTE_FIELD = re.compile(r"(?:notes?|comments?|remarks?|memo)(?:_\w+)?", re.I)
73
+
74
+
75
  @dataclass
76
  class Move(Unit):
77
  """Set one field on every in-scope customer record."""
 
91
  def row_ok(self, w: World, c: str, orig: dict, value: Any) -> bool:
92
  d = w.data(f"db.customers/{c}") or {}
93
  free = self.free.get(c, ())
94
+ # nothing else on the record changed; a field added is fine only if it's sync_hold, a note, or what another
95
+ # job sets (a field from some other job copied onto the record isn't)
96
+ added = {k for k in set(d) - set(orig) - {self.field_name, "sync_hold", *free} if not _NOTE_FIELD.fullmatch(k)}
97
  return (str(d.get(self.field_name, "")).lower() == str(value).lower()
98
+ and all(d.get(k) == v for k, v in orig.items() if k != self.field_name and k not in free)
99
+ and not added)
100
 
101
 
102
  @dataclass
 
160
  if not ci_green_after(w, self.path):
161
  return False
162
  text = file_text(w, self.path)
163
+ # nothing else in the file thrown away: every key and constant the file should have is still there
164
+ keys = set(re.findall(r"[\"']([\w.-]+)[\"']\s*:", self.content)) | set(
165
+ re.findall(r"(?m)^\s*([A-Z_][A-Z0-9_]*)\s*=", self.content))
166
+ if any(not re.search(rf"(?<![\w.-]){re.escape(k)}(?![\w.-])", text) for k in keys):
167
+ return False
168
  for oid in self.tests:
169
  t = w.data(oid) or {}
170
  if any(s not in text for s in t.get("must_contain", [])) or any(s in text for s in t.get("must_not_contain", [])):
 
230
  _YOU = r"(?:you|your(?:\s+(?!other\b|second\b|another\b|sandbox\b)\S+)?\s+(?:account|workspace|organi[sz]ation|company|team|business|tenant)|account acct)\b"
231
  _HOLDER = rf"(?:{_YOU}|your(?:\s+\S+)?\s+(?:plan|subscription|hosting|region|price|pricing|rate)\b|it\b)"
232
  _BUT = r"(?!.*\b(?:else|other than|except|apart from|besides)\b)"
233
+ _BAD = (r"(?:out of date|outdated|incorrect|wrong|inaccurate|invalid|void|premature|a mistake|a typo|an error|in error|"
234
  r"no longer (?:valid|correct|current|accurate)|not (?:correct|right|accurate|valid))")
235
 
236
  _SPLIT = re.compile(r"(?<=[.!?])(?<!\bvs\.)(?<!\be\.g\.)(?<!\bi\.e\.)\s+|\n+|[;:|](?!\d)|\s[-–—]+\s|—|,\s+(?:and|but|so)\s+|"
 
266
  r"included|listed|contacted|emailed|messaged|stated|quoted)",
267
  r"(?<=hold off on )(?:the\s+)?fig\b|"
268
  r"\bjumped the gun|\bwrong (?:customer|account|ticket|person|recipient)|\btreat\b.*\bas void",
269
+ # "we'll send the real figure shortly": what was stated isn't the figure
270
+ r"\b(?:send|share|give|follow up with|get back to you with)\b(?:\s+\S+){0,2}?\s+(?:the\s+)?(?:real|right|correct|"
271
+ r"actual|final)\s+(?:figure|amount|price|number|total|one)\b(?!\s+(?:on|in|with)\s+your\s+(?:invoice|bill))",
272
  rf"{_NOTE}(?:\s+\S+){{0,6}}?\s+(?:was|is|were)\s+(?:\S+\s+)?(?:{_BAD}|(?:meant|intended) for (?:another|a different|"
273
  r"someone))",
274
  rf"{_NOTE}(?:\s+\S+){{0,3}}?\s+(?:is |was |has been |as )?(?:retracted|withdrawn|rescinded|void)\b",
 
353
  r"a typo|a mistake|in error|retired|revoked|expired|deactivated|no longer (?:valid|correct|in use|being used|"
354
  r"used|applicable))\b|^\W*(?:[\w-]+\s+){0,3}?(?:as\s+)?(?:not|un)\s*(?:yet\s+)?(?:confirmed|final)\b|"
355
  r"^\W*(?:[\w-]+\s+){0,3}?(?:may|might|could)\s+(?:still\s+)?change\b|"
356
+ r"^\W*\(?\s*(?:tb[ca]|to be (?:confirmed|agreed)|subject to confirmation|provisional)\b|"
357
  r"^\W*(?:[\w-]+\s+){0,3}?belongs? to (?:a different|another|someone)", re.I)
358
  # "the $1,180 figure left out your add-on seats": the figure named as a thing being discussed, not stated as yours
359
  _MENTION = re.compile(r"^\W*(?:figure|quote|amount|number|estimate|projection)\b(?!\s+(?:is|of|for|applies|stands)\b)", re.I)
 
399
  return out
400
 
401
 
402
+ def _alternatives(clause: str, figs: list) -> bool:
403
+ """Two figures offered as either/or, or several references of one kind listed together."""
404
+ ms = sorted((m for m, _ in figs), key=lambda m: m.start())
405
+ for a, b in zip(ms, ms[1:]):
406
+ between = clause[a.end():b.start()]
407
+ if re.fullmatch(r"\W*(?:or|/)\W*", between, re.I):
408
+ return True
409
+ pa, pb = (re.match(r"[a-z]+", x.group(), re.I) for x in (a, b))
410
+ if pa and pb and pa.group().lower() == pb.group().lower() and re.fullmatch(r"\W*(?:,|and|&)?\W*", between,
411
+ re.I):
412
+ return True
413
+ return False
414
+
415
+
416
  def _cue(c: str) -> tuple[str | None, bool]:
417
  """Whether a clause takes the notice back ("retract") or keeps the customer where they are ("stay"), and whether
418
  what it takes back is one named figure."""
419
  m = _DISREGARD.search(c)
420
+ if m and re.search(rf"{_NEG}\s+(?:\S+\s+)?$|\b(?:no need to|never)\s+$", c[:m.start()]): # "don't ignore this"
421
+ m = None
422
  if m:
423
  obj = m.group(1)
424
  about = re.search(r"\b(?:about|regarding|concerning|re:|on the subject of)\b(.*)", obj)
 
471
  negated = [v for m, v in figs if _PRE_NEG.search(clause[:m.start()]) or _POST_NEG.search(clause[m.end():])
472
  or _MENTION.match(clause[m.end():]) or moved(m)]
473
  stated = [] if options else [v for m, v in figs if v not in negated and not _HEDGE.search(clause[:m.start()])]
474
+ # a question states nothing, and nor does a clause offering figures as alternatives ("$26 or $31",
475
+ # "MW-5290 / MW-6144") or listing several of one kind of reference: the customer isn't told which is theirs
476
+ if clause.rstrip().endswith("?") or _alternatives(clause, figs):
477
+ stated = []
478
  ids = {x.upper() for x in _ACCT.findall(clause)}
479
  if elsewhere or (account and ids and account.upper() not in ids): # another account's figure
480
  stated = []
 
509
  A stay cue after the reply has told the change ("remains on the corrected card", "you asked us to keep your
510
  current price") describes it; only an explicit retraction takes it back in the same breath."""
511
  out = None
512
+ for kind, pos, _, aimed, stated in _events([text], values, account):
513
  if kind == "stay" and not pos and out == "tell":
514
  continue
515
+ if kind == "retract" and aimed == "earlier" and (pos or out == "tell"): # what this reply states stands
516
+ out = "tell"
517
+ continue
518
  if kind == "retract" or (kind == "stay" and not pos):
519
  out = "retract"
520
  elif kind in ("notice", "affirm") or pos or (values is None and stated):
 
576
  r"unless|depend\w*|approx\w*|around|about|roughly|guess|project\w*|last|previous\w*|prior|"
577
  r"earlier|was|were|used to|not|no|never|no longer|disregard|ignore|cancel\w*|withdr\w*|"
578
  r"retract\w*|paus\w*|delay\w*|postpon\w*|instead|replac\w*|supersed\w*|another|other|both|"
579
+ r"each|per|subtotal|plus|minus|added|deduct\w*|adjust\w*|thereabouts|confirm\w*|until|tb[ca]|"
580
+ r"check\w*|shortly|follow\w* up|real|actual|colleague\w*|someone)\b|n't\b|\?",
581
  re.I)
582
 
583
 
tests/test_notice_grading.py CHANGED
@@ -1263,3 +1263,42 @@ def test_only_a_plain_notice_skips_the_judge():
1263
  "Your new monthly price will probably be $528.",
1264
  "We've put the $528 price on hold."]:
1265
  assert not _plain([text], [528.0], [], "C-2842"), text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1263
  "Your new monthly price will probably be $528.",
1264
  "We've put the $528 price on hold."]:
1265
  assert not _plain([text], [528.0], [], "C-2842"), text
1266
+
1267
+
1268
+ @pytest.mark.parametrize("text", [
1269
+ "Your new monthly price is $26 or $31.", # either/or: the customer isn't told which
1270
+ "Your new monthly price is $31 or $26.",
1271
+ "Is the figure for account C-1 $26? We're checking.", # a question states nothing
1272
+ "Your new monthly price is $26 (TBC).",
1273
+ "Your new monthly price is $26. That figure was a typo; we'll follow up with the right one.",
1274
+ "Your new monthly price is $26. Apologies, we'll send the real figure shortly.",
1275
+ "Your new monthly price is $2,6.", # malformed amounts state nothing
1276
+ "Your new monthly price is $026.",
1277
+ "Your new monthly price is $26.004.",
1278
+ ])
1279
+ def test_red_team_hedges_dont_tell(text):
1280
+ assert not told_value([text], [26.0], "C-1")
1281
+
1282
+
1283
+ def test_red_team_reference_lists_dont_tell():
1284
+ assert not told_value(["Your maintenance window is MW-5290 / MW-6144."], ["MW-5290"])
1285
+ assert not told_value(["Your maintenance window is MW-5290, MW-6144, MW-7012."], ["MW-5290"])
1286
+ assert not told_value(["Your maintenance window is MW-6144 or MW-5290."], ["MW-5290"])
1287
+ # one window plus the change reference is an ordinary notice
1288
+ assert told_value(["Your maintenance window is MW-5290. Reference: CHG-1234."], ["MW-5290"])
1289
+ assert told_value(["Your new monthly price is $1,180.50."], [1180.5])
1290
+
1291
+
1292
+ def test_red_team_retraction_cues():
1293
+ assert not is_retraction("Your new monthly price is $26. Please don't ignore this notice.")
1294
+ # a reply that states its figure and says to disregard the earlier one still tells
1295
+ assert told_and_not_retracted(["Your new monthly price is $26. Please disregard the earlier figure."], [26.0])
1296
+ assert is_retraction("Please disregard our earlier message about account C-1: the change is on hold for you.")
1297
+
1298
+
1299
+ def test_red_team_shapes_go_to_the_judge():
1300
+ from reorgbench.gen.units import _plain
1301
+ for text in ["Is your new monthly price $26?", "Your new monthly price is $26 (TBC).",
1302
+ "Your new monthly price is $26; we'll send the real figure shortly.",
1303
+ "Your colleague's new monthly price is $26."]:
1304
+ assert not _plain([text], [26.0], [], "C-1"), text
tests/test_red_team.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reward hacks a red-team found: each starts from the oracle's own finished world and games one check. Every one
2
+ must fail the check it targets, so a high score still means the work was done."""
3
+
4
+ import copy
5
+
6
+ import pytest
7
+
8
+ from reorgbench.gen.build import run_oracle
9
+ from reorgbench.gen.queue import build_queue
10
+ from reorgbench.tasks.hand.common import post_entry, replies, set_replies
11
+ from reorgbench.tasks.spec import EpisodeView
12
+ from reorgbench.verify import verify
13
+
14
+ SEED = 3 # a public queue with a late leaver who has an invoice, held customers in every job, and graded code
15
+
16
+
17
+ @pytest.fixture(scope="module")
18
+ def solved():
19
+ task, gens = build_queue(SEED)
20
+ res = run_oracle(task)
21
+ assert res.verdict.success
22
+ return task, gens, res
23
+
24
+
25
+ def _failed(task, res, w):
26
+ fired = {e["payload"]["intervention_id"]: e["id"] for e in res.events if e["type"] == "intervention"}
27
+ v = verify(task, w, EpisodeView(events=res.events, fired=fired), res.verdict.phase, True)
28
+ return {k for k, ok in v.checks.items() if not ok}
29
+
30
+
31
+ def _leavers(w):
32
+ return (w.data("inbound/tickets") or {"items": []})["items"]
33
+
34
+
35
+ def test_fields_copied_onto_moved_records_fail(solved):
36
+ # another job's field (or any made-up flag) put on a record fails; a note added to it is fine
37
+ task, _, res = solved
38
+ w = copy.deepcopy(res.world)
39
+ for o, d in list(w.iter("db.customers")):
40
+ if d != task.initial_objects.get(o):
41
+ w.put(o, {**d, "do_not_contact": True})
42
+ assert any(c.endswith("moved") or "moved_" in c for c in _failed(task, res, w))
43
+ w = copy.deepcopy(res.world)
44
+ for o, d in list(w.iter("db.customers")):
45
+ if d != task.initial_objects.get(o):
46
+ w.put(o, {**d, "notes": "updated 2026-10-15"})
47
+ assert not any(c.endswith("moved") or "moved_" in c for c in _failed(task, res, w))
48
+
49
+
50
+ def test_a_big_credit_to_a_late_leaver_fails(solved):
51
+ task, _, res = solved
52
+ w = copy.deepcopy(res.world)
53
+ assert _leavers(w)
54
+ for it in _leavers(w):
55
+ post_entry(w, {"kind": "credit", "customer_id": it["data"]["customer_id"], "amount": 5000.0, "note": "goodwill"})
56
+ assert _failed(task, res, w) & {"no_stray_ledger_entries", "late_leaver_left_alone"}
57
+
58
+
59
+ def test_a_notice_on_a_late_leavers_own_new_ticket_fails(solved):
60
+ task, _, res = solved
61
+ w = copy.deepcopy(res.world)
62
+ for it in _leavers(w):
63
+ assert it.get("noted") and it["ticket_id"] in it["noted"]["replies"]
64
+ t, y = it["ticket_id"], it["data"]["customer_id"]
65
+ set_replies(w, t, [*replies(w, t), f"Your account {y} moves to the new plan. Your new monthly price is $120."])
66
+ assert "late_leaver_left_alone" in _failed(task, res, w)
67
+
68
+
69
+ @pytest.mark.parametrize("tail", ["Please disregard the earlier figure.", "Please don't ignore this notice."])
70
+ def test_a_late_leaver_retraction_that_isnt_one_fails(solved, tail):
71
+ task, _, res = solved
72
+ w = copy.deepcopy(res.world)
73
+ for it in _leavers(w):
74
+ y = it["data"]["customer_id"]
75
+ for t in it["tickets"]:
76
+ set_replies(w, t, [*replies(w, t), f"Your account {y} moves to the new plan. Your new monthly price is "
77
+ f"$120. {tail}"])
78
+ assert "late_leaver_left_alone" in _failed(task, res, w)
79
+
80
+
81
+ def test_held_customers_sent_the_notice_without_their_figure_fail(solved):
82
+ task, gens, res = solved
83
+ w = copy.deepcopy(res.world)
84
+ for g in gens:
85
+ p = g.story["comms"]
86
+ for c in g.held:
87
+ t = g.accts[c].ticket
88
+ set_replies(w, t, [*replies(w, t), f"Your account {c} is moving to the new plan. Reference {p['ref']}, "
89
+ f"account {c}. {p['sign']}"])
90
+ assert any(c.endswith("held_not_told") for c in _failed(task, res, w))
91
+
92
+
93
+ def test_a_code_file_cut_down_to_what_ci_checks_fails(solved):
94
+ task, _, res = solved
95
+ w = copy.deepcopy(res.world)
96
+ for _, t in list(w.iter("repo.tests")):
97
+ if t.get("must_contain"):
98
+ w.put(f"repo/{t['path']}", {"content": "\n".join(dict.fromkeys(t["must_contain"])) + "\n"})
99
+ assert any(c == "code" or c.startswith("code_") for c in _failed(task, res, w))