From 2d3ff1b1492376fd65834b1324bf8a87ab400d79 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:35:18 -0700 Subject: [PATCH 1/6] review: keep multiline TOML examples out of finding bindings A line resembling a hold header or binding field can be part of a multiline answer. Counting it as syntax made the tag rewrite fall back to ordinal keys. Releasing one hold could then move another onto the wrong finding. Check TOML boundaries before editing candidate lines. Regression tests cover hold identity across deletion and preservation of a binding field example. Written by an AI agent on jpsamaroo's review feedback. --- AGENTS.md | 7 +++++++ review/reviewlib/answers.py | 20 ++++++++++++++++---- review/tests/test_review.py | 37 ++++++++++++++++++++++++++++++++++++- 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 03120cce2..9123d1b9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1108,3 +1108,10 @@ this section verbatim). Each entry is one bullet starting with `- `. (`mpi_slot_alloc`) rather than copying it afterwards; the copy leaves a GC-managed buffer of the same size behind, which for 16 8 MB slots per region was 989 MiB of GC allocation and 35 collections over 8 regions. + +102. **Check TOML edit locations with the parser before inserting bindings.** + A maintainer's multiline answer can contain a literal `[[hold]]` or + `binding = ...`. Counting it as syntax can make the tag rewrite fail its + round-trip check and fall back to ordinal keys, so deleting one real hold + moves another onto the wrong finding. Parse the prefix at each candidate + location to distinguish complete TOML from an open multiline value. diff --git a/review/reviewlib/answers.py b/review/reviewlib/answers.py index eda172e3e..af7eb7055 100644 --- a/review/reviewlib/answers.py +++ b/review/reviewlib/answers.py @@ -398,11 +398,21 @@ def new_tag(used=()) -> str: _BINDING_LINE = re.compile(r"^[ \t]*binding[ \t]*=") +def _at_toml_boundary(lines: list[str], index: int) -> bool: + # A real header or assignment follows a complete prefix. The same text inside a multiline + # string or array follows an unterminated value. Let tomllib distinguish those cases. + try: + tomllib.loads("".join(lines[:index])) + except tomllib.TOMLDecodeError: + return False + return True + + def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: """Write `binding = ""` into the entries `planned` names ((kind, index) -> tag), editing answers.toml as text so the maintainer's comments and layout survive. The result is parsed again and - must be the same entries with only those tags set; if it is not (an entry written as an inline table, - a header inside a multi-line string), nothing is written and False is returned.""" + must be the same entries with only those tags set; if it is not (e.g. an entry is written as an + inline table), nothing is written and False is returned.""" path = os.path.join(out_dir, ANSWERS_FILE) with open(path, encoding="utf-8") as fh: text = fh.read() @@ -415,7 +425,7 @@ def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: out.append(line) k += 1 m = _ENTRY_HEADER.match(line.rstrip("\r\n")) - if not m: + if not m or not _at_toml_boundary(lines, k - 1): continue kind = m.group(1) seen[kind] += 1 @@ -427,7 +437,9 @@ def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: tag_line = f"binding = {json.dumps(tag)}\n" # An entry that already has a `binding` line (one copied from another entry) has it replaced. j = k - while j < len(lines) and not _ANY_HEADER.match(lines[j]) and not _BINDING_LINE.match(lines[j]): + while j < len(lines): + if (_ANY_HEADER.match(lines[j]) or _BINDING_LINE.match(lines[j])) and _at_toml_boundary(lines, j): + break j += 1 if j < len(lines) and _BINDING_LINE.match(lines[j]): out += lines[k:j] + [tag_line] diff --git a/review/tests/test_review.py b/review/tests/test_review.py index 15bcd0072..4af1dbde8 100644 --- a/review/tests/test_review.py +++ b/review/tests/test_review.py @@ -12,7 +12,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) -from reviewlib import calibrate, collect, config, julia_static as js, render, tasks, validate # noqa: E402 +from reviewlib import answers, calibrate, collect, config, julia_static as js, render, tasks, validate # noqa: E402 from reviewlib.gitutil import WORKTREE, changes # noqa: E402 @@ -1517,6 +1517,41 @@ def test_releasing_or_adding_an_entry_never_moves_another(self): self.assertEqual(code, 0, text) self.assertNotIn("STALE", text) + def test_multiline_answer_cannot_retarget_a_hold(self): + path = os.path.join(self.out, answers.ANSWERS_FILE) + feedback = '[[answer]]\ntext = """An example header:\n[[hold]]\n"""\n' + previous_hold = '\n[[hold]] # original\nfinding = 1\nuntil = "Alice confirms it"\n' + current_hold = '\n[[hold]] # remaining\nfinding = 1\nuntil = "Bob confirms it"\n' + previous = {"id": "F1", "title": "Original finding", "severity": "should-fix"} + current = {"id": "F2", "title": "New finding", "severity": "blocker"} + write(self.out, answers.ANSWERS_FILE, feedback + previous_hold) + before = {"findings": [previous]} + self.assertEqual(answers.bind(self.out, before)["hold"][0]["finding"], previous) + + with open(path, "a") as fh: + fh.write(current_hold) + after = {"findings": [current, previous]} + holds = answers.bind(self.out, after)["hold"] + self.assertEqual([hold["finding"] for hold in holds], [previous, current]) + + with open(path) as fh: + body = fh.read() + start = body.index("\n[[hold]] # original") + end = body.index("\n[[hold]] # remaining") + with open(path, "w") as fh: + fh.write(body[:start] + body[end:]) + holds = answers.bind(self.out, after)["hold"] + self.assertEqual([hold["finding"] for hold in holds], [current]) + self.assertEqual(body[:start], feedback) + + def test_binding_example_after_a_hold_header_is_preserved(self): + text = '[[hold]]\nfinding = 1\nuntil = """An example field:\nbinding = "placeholder"\n"""\n' + write(self.out, answers.ANSWERS_FILE, text) + finding = {"id": "F1", "title": "Original finding", "severity": "should-fix"} + holds = answers.bind(self.out, {"findings": [finding]})["hold"] + self.assertIsNotNone(holds[0]["entry"]["binding"]) + self.assertEqual(answers.load_holds(self.out)[0]["until"], 'An example field:\nbinding = "placeholder"') + def test_rebind_confirms_only_its_own_kind(self): self.assertEqual(self.run_cli("submit")[0], 0) # Brief numbers: 1 removed method, 2 docstring, 3 extra.jl, 4 spawn's local path. From f28a34fb373210bce1902f680ea1beb943dcff67 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:36:50 -0700 Subject: [PATCH 2/6] review: require usable CI evidence for a Tested pass Pending, skipped and failing checks could satisfy the Tested evidence gate because a normalized check section was treated as a result. Require at least one passing check and reject results known to target another commit. Coverage remains valid evidence. Written by an AI agent on jpsamaroo's review feedback. --- review/README.md | 2 +- review/reviewlib/render.py | 10 +++++----- review/reviewlib/validate.py | 15 +++++++++++++-- review/rubric/tested.md | 5 +++-- review/tests/test_review.py | 23 +++++++++++++++++++++++ 5 files changed, 45 insertions(+), 10 deletions(-) diff --git a/review/README.md b/review/README.md index 725e91440..c2c566b21 100644 --- a/review/README.md +++ b/review/README.md @@ -50,7 +50,7 @@ Genericity · Extensible · Applicable · Scalable · Documented · Tested Verdicts are `pass`, `concern`, `fail`, `unverified` (could not be established; says what is missing) and `na`. Some categories cannot `pass` on reading alone: Performance and Allocations need an attached -benchmark comparison, Tested needs CI results or coverage, Compatible and Documented need the static API +benchmark comparison, Tested needs passing CI results or coverage, Compatible and Documented need the static API and docstring scan (always available). That gating is the `pass_requires_evidence` field. ## What is computed, and what is judged diff --git a/review/reviewlib/render.py b/review/reviewlib/render.py index be4a9ccfe..b7856f71d 100644 --- a/review/reviewlib/render.py +++ b/review/reviewlib/render.py @@ -342,7 +342,7 @@ def _decide_header(final: dict) -> str: def _unmeasured(final: dict, ev: dict) -> tuple[list[str], list[str]]: - """Categories that are `unverified` only because their required measurement was not collected, + """Categories that are `unverified` only because usable evidence is missing, and raised nothing: one line for all of them says as much as one line each.""" from .validate import usable_evidence ids, needs = [], [] @@ -489,8 +489,8 @@ def _brief_text(final: dict, ev: dict, nits: bool = False, verbose: bool = False for cat, entry in rows: out.append(f" {LABEL[entry['verdict']]:<10} {cat['title']:<13} {_basis(entry):<4} {entry['summary']}") if collapsed: - out.append(f" {'UNMEASURED':<10} {', '.join(titles[c] for c in collapsed)}: nothing raised; " - f"a verdict needs {', '.join(needs)}, which was not collected") + out.append(f" {'UNMEASURED':<10} {', '.join(titles[c] for c in collapsed)}. " + f"A verdict needs usable evidence under {', '.join(needs)}") if _changes_line(final): out.append(f" since your answers: {_changes_line(final)}") if major[DECIDE_MAX:]: @@ -611,8 +611,8 @@ def _brief_md(final: dict, ev: dict) -> str: v = f"**{v}**" if entry["verdict"] in ("fail", "concern", "unverified") else v out.append(f"| {v} | {cat['title']} | {basis_names[_basis(entry)]} | {esc(entry['summary'])} |") if collapsed: - out.append(f"| unmeasured | {', '.join(titles[c] for c in collapsed)} | – | Nothing raised; a verdict needs " - f"{', '.join('`' + n + '`' for n in needs)}, which was not collected |") + out.append(f"| unmeasured | {', '.join(titles[c] for c in collapsed)} | – | Nothing raised. A verdict needs " + f"usable evidence under {', '.join('`' + n + '`' for n in needs)} |") if _changes_line(final): out += ["", f"**Since your answers:** {_changes_line(final)}"] if major[DECIDE_MAX:]: diff --git a/review/reviewlib/validate.py b/review/reviewlib/validate.py index 193065324..16967878f 100644 --- a/review/reviewlib/validate.py +++ b/review/reviewlib/validate.py @@ -82,9 +82,15 @@ def _present(ev: dict, prefix: str) -> bool: def usable_evidence(ev: dict, prefix: str) -> list[str]: """The pointers under `prefix` that can satisfy a `pass_requires_evidence` requirement. A computed - section counts when it is present. Under /external/, which the reviewer attached, only measurements + section counts when it is present, and CI must have a passing check for the reviewed revision. + Under /external/, which the reviewer attached, only measurements the tool recognizes count (collect.measurements): an empty benchmark suite or a JSON of any other shape does not, however it is cited.""" + if prefix == "/checks": + checks = ev.get("checks") or {} + if checks.get("commit_is_reviewed_head") is False or not checks.get("tally", {}).get("pass"): + return [] + return [prefix] if not prefix.startswith("/external/"): return [prefix] if _present(ev, prefix) else [] try: @@ -471,12 +477,17 @@ def validate(report, ev: dict, repo: str, check_stale: bool = True, pr_head: str cited = [p for b, c in verified if b == "measured" for p in c.get("evidence", []) if any(p == u or p.startswith(u + "/") or (p.startswith("/external/") and u.startswith(p + "/")) for u in usable)] - unusable = [p for p in prefixes if _present(ev, p) and not usable_evidence(ev, p)] + unusable = [p for p in prefixes if p.startswith("/external/") and _present(ev, p) + and not usable_evidence(ev, p)] if not usable and unusable: res.err("E031", where, f"`pass` here requires a measurement under {' or '.join(prefixes)}; " f"{' and '.join(unusable)} was attached but is not one the tool recognizes " "(a benchmark/ci.jl summary that compared at least one job, or " "{\"base\": [...], \"head\": [...]} samples), so the verdict is `unverified`") + elif not usable and "/checks" in prefixes and _present(ev, "/checks"): + res.err("E031", where, "`pass` here requires a passing CI result on the reviewed revision or " + "coverage. The collected checks do not establish a pass, so the verdict " + "is `unverified`") elif not usable: res.err("E031", where, f"`pass` here requires evidence under {' or '.join(prefixes)}, and none was " "collected; the verdict is `unverified` until it is") diff --git a/review/rubric/tested.md b/review/rubric/tested.md index 9e4417d64..7fe35e904 100644 --- a/review/rubric/tested.md +++ b/review/rubric/tested.md @@ -45,8 +45,9 @@ configurations? - **fail**: new behavior with no assertion; a bug fix with no regression test; a new test file that is never run; tests weakened, skipped or deleted to get green; an applicable configuration failing. - **na**: no behavior changed (comments, docs). -- **unverified**: neither CI results nor coverage were collected, so you can show tests exist but not - that they ran or passed. Say exactly which command or CI job would settle it. +- **unverified**: when there is no established test failure or gap and the available evidence does + not establish that the applicable tests passed. Pending or skipped jobs and results for another + revision cannot support a pass. Say which command or CI job would settle it. ## Dagger-specific diff --git a/review/tests/test_review.py b/review/tests/test_review.py index 4af1dbde8..ee574e407 100644 --- a/review/tests/test_review.py +++ b/review/tests/test_review.py @@ -684,6 +684,29 @@ def test_pass_needs_measured_claim_under_required_prefix(self): "cites": [{"file": "src/Mini.jl", "lines": [21, 21], "quote": "tilecount(x) = length(x)"}]}]} self.assertIn("E031", self.codes(r)) + def test_tested_pass_requires_passing_checks_or_coverage(self): + report = self.good_report() + tested = report["categories"]["tested"] + tested.update(verdict="pass", summary="CI ran successfully.", claims=[ + {"text": "The applicable tests pass.", "basis": "measured", "evidence": ["/checks"]}, + ]) + tested["flags"][0].update(disposition="benign", note="assume the flag was reviewed for this fixture") + report["findings"] = [f for f in report["findings"] if f["id"] != "F5"] + head = self.ev["repo"]["head"] + for status, commit, passes in (("IN_PROGRESS", head, False), ("SKIPPED", head, False), + ("FAILURE", head, False), ("SUCCESS", self.base, False), + ("SUCCESS", head, True)): + with self.subTest(status=status, commit=commit): + checks = collect._checks_section({"commit": commit, "checks": [{"name": "suite", "status": status}]}, head) + ev = {**self.ev, "checks": checks} + errors = validate.validate(report, ev, self.repo).errors + self.assertEqual([e.code for e in errors], [] if passes else ["E031"]) + + tested["claims"][0]["evidence"] = ["/coverage"] + pending = collect._checks_section([{"name": "suite", "status": "IN_PROGRESS"}]) + ev = {**self.ev, "checks": pending, "coverage": {"changed_line_coverage": 1.0}} + self.assertEqual(validate.validate(report, ev, self.repo).errors, []) + def test_concern_must_mark_its_problem(self): r = self.good_report() del r["categories"]["necessity"]["claims"][0]["problem"] From 4dcfaec745a95ee3af1f15b9be8d8492d01a20e3 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:37:01 -0700 Subject: [PATCH 3/6] review: isolate package-image caches across benchmark revisions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Alternating base and head in one scratch depot can replace a revision’s package image and make the next run pay for compilation. Document separate depots and reuse through each revision’s warmup and samples. Written by an AI agent on jpsamaroo's review feedback. --- review/REVIEW.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/review/REVIEW.md b/review/REVIEW.md index 5b6d6cb77..4413945b6 100644 --- a/review/REVIEW.md +++ b/review/REVIEW.md @@ -83,9 +83,11 @@ To run Julia against the PR (a probe, a timing, one test file): the worktree has make a scratch environment instead of instantiating in the worktree, e.g. `julia --project=/env -e 'using Pkg; Pkg.develop([PackageSpec(path=""), PackageSpec(path="/lib/TimespanLogging")])'`. Every worktree is the same package to Julia, so -concurrent reviews contend for one set of precompile caches; for timings, put a scratch depot first in -`JULIA_DEPOT_PATH` (`JULIA_DEPOT_PATH=/depot:` with the trailing colon) so the measurement is not -disturbed and does not evict the maintainer's caches. Keep everything in your scratch directory, never in +concurrent reviews contend for one set of precompile caches. For timings, put a scratch depot first in +`JULIA_DEPOT_PATH` (`JULIA_DEPOT_PATH=/depot:` with the trailing colon) to isolate the benchmark's +cache writes. When comparing base and head, give each revision its own scratch depot and reuse it for +that revision's warmup and samples. Switching revisions in a shared depot can overwrite the same +package image and charge a sample for recompilation. Keep everything in your scratch directory, never in the worktree. Running `test/runtests.jl` as a script activates `test/` and rewrites its `Project.toml` (and creates a `Manifest.toml`) even under `--project=`; use `julia --project=/env -e 'include("test/runtests.jl")' -- --test ` instead, and check From 373f9b87b2f5c8bdff9523863185651e5ed7e85c Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:37:57 -0700 Subject: [PATCH 4/6] review: keep overflow explanations available in the brief The brief printed the first three explanations and silently dropped the rest. Fold additional explanations in Markdown and make them available through the existing verbose text view. Written by an AI agent on jpsamaroo's review feedback. --- review/REVIEW.md | 3 ++- review/review.py | 2 +- review/reviewlib/render.py | 16 ++++++++++------ review/tests/test_review.py | 16 ++++++++++++++++ 4 files changed, 29 insertions(+), 8 deletions(-) diff --git a/review/REVIEW.md b/review/REVIEW.md index 4413945b6..77387b7d5 100644 --- a/review/REVIEW.md +++ b/review/REVIEW.md @@ -170,7 +170,8 @@ precisely and make each one stand alone. A fragment may also `explain` up to two things the maintainer is likely to wonder ("Why is this needed?", "Why doesn't the existing X already handle this?"), each backed by that fragment's supported claims. The Necessity reviewer always answers "Why is this needed?". These go in the brief under "You might ask", so -the maintainer does not have to ask the author a question the review already answered. +the maintainer does not have to ask the author a question the review already answered. The brief shows +up to three explanations at first. Find the rest in the Markdown disclosure or run `R render --verbose`. ## 4. Consolidate findings diff --git a/review/review.py b/review/review.py index cfa391fa8..cc9bb85db 100755 --- a/review/review.py +++ b/review/review.py @@ -818,7 +818,7 @@ def main(argv=None) -> int: p.add_argument("--evidence") p.add_argument("--format", choices=("text", "md"), default="text") p.add_argument("--nits", action="store_true", help="also list findings that are only nits (text format)") - p.add_argument("--verbose", action="store_true", help="show what each reviewer said under every finding (text format)") + p.add_argument("--verbose", action="store_true", help="show each reviewer's claims and all explanations (text format)") p.set_defaults(fn=cmd_render) p = sub.add_parser("schema", help="regenerate report.schema.json from categories.toml") diff --git a/review/reviewlib/render.py b/review/reviewlib/render.py index b7856f71d..9be8cc565 100644 --- a/review/reviewlib/render.py +++ b/review/reviewlib/render.py @@ -479,11 +479,13 @@ def _brief_text(final: dict, ev: dict, nits: bool = False, verbose: bool = False tail = (f"finding {hangs}" if hangs else "") + (" · " if hangs and q["why"] else "") + (q["why"] or "") if tail: out.append(f" {'':<16} ({tail})") - asked = final.get("explained", [])[:EXPLAIN_SHOWN] + asked = final.get("explained", []) if asked: out += ["", "YOU MIGHT ASK"] - for e in asked: + for e in asked if verbose else asked[:EXPLAIN_SHOWN]: out += [f" Q: {e['question']}", f" A: {e['answer']} ({titles[e['category']]})"] + if not verbose and len(asked) > EXPLAIN_SHOWN: + out.append(f" {len(asked) - EXPLAIN_SHOWN} more (`review.py render --verbose`)") rows, collapsed, needs = _verdict_rows(final, ev) out += ["", f"VERDICTS {_tally(final)} (basis: M measured, T traced in code, i inferred only)"] for cat, entry in rows: @@ -597,11 +599,13 @@ def _brief_md(final: dict, ev: dict) -> str: tail = (f"finding {hangs}" if hangs else "") + (" · " if hangs and q["why"] else "") + (q["why"] or "") out.append(f"- `{q['ref']}` {q['text']}" + (f" \n *{tail}*" if tail else "")) out.append("") - asked = final.get("explained", [])[:EXPLAIN_SHOWN] + asked = [f"- **{e['question']}** \n {e['answer']} *({titles[e['category']]})*" + for e in final.get("explained", [])] if asked: - out += ["### You might ask", ""] - for e in asked: - out += [f"- **{e['question']}** ", f" {e['answer']} *({titles[e['category']]})*"] + out += ["### You might ask", "", *asked[:EXPLAIN_SHOWN]] + if len(asked) > EXPLAIN_SHOWN: + out += ["", f"
More explanations ({len(asked) - EXPLAIN_SHOWN})", "", + *asked[EXPLAIN_SHOWN:], "", "
"] out.append("") rows, collapsed, needs = _verdict_rows(final, ev) out += ["### Verdicts", "", "| Verdict | Category | Basis | Summary |", "|:--|:--|:--|:--|"] diff --git a/review/tests/test_review.py b/review/tests/test_review.py index ee574e407..bb07f18a6 100644 --- a/review/tests/test_review.py +++ b/review/tests/test_review.py @@ -1012,6 +1012,22 @@ def test_explain_is_backed_by_supported_claims(self): r["categories"]["scalable"]["explain"] = [{"question": "Q?", "answer": "A.", "claims": [0]}] self.assertIn("E071", self.codes(r)) + def test_extra_explanations_are_available_in_both_brief_formats(self): + final = self.final() + final["explained"] = [ + {"category": "necessity", "question": f"Question {i}?", "answer": f"Answer {i}."} + for i in range(1, 5) + ] + text = render.brief(final, self.ev) + self.assertIn("Question 3?", text) + self.assertNotIn("Question 4?", text) + self.assertIn("1 more (`review.py render --verbose`)", text) + verbose = render.brief(final, self.ev, verbose=True) + self.assertIn("Question 4?", verbose) + markdown = render.brief(final, self.ev, fmt="md") + self.assertLess(markdown.index("Question 3?"), markdown.index("More explanations (1)")) + self.assertLess(markdown.index("More explanations (1)"), markdown.index("Question 4?")) + def test_nits_are_hidden_unless_asked(self): r = self.good_report() r["categories"]["extensible"] = { From da33a3b4b4ab441c88a5d61d09a6a435fb3c7cbb Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:52:36 -0700 Subject: [PATCH 5/6] review: validate a linear tag edit before parsing TOML prefixes Review finding 1 on PR #842 (should-fix): First-time binding reparses each growing TOML prefix Requested: Try the candidate-line edit with round-trip validation before reparsing TOML prefixes. Use prefix checks on retry if needed. Require the full parsed document to match the intended tag-only edit before replacing answers.toml. A misleading line inside a multiline value still triggers the boundary-aware retry. The ordinary binding regression test fails on the former head and passes with the patch. Both existing multiline regression tests pass. Median time to bind 250 new holds across seven runs falls from 3.98 s to 47 ms. Written by an AI agent on jpsamaroo's review feedback. --- review/reviewlib/answers.py | 58 +++++++++++++++++++++++-------------- review/tests/test_review.py | 9 ++++++ 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/review/reviewlib/answers.py b/review/reviewlib/answers.py index af7eb7055..dee3d91de 100644 --- a/review/reviewlib/answers.py +++ b/review/reviewlib/answers.py @@ -408,15 +408,7 @@ def _at_toml_boundary(lines: list[str], index: int) -> bool: return True -def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: - """Write `binding = ""` into the entries `planned` names ((kind, index) -> tag), editing - answers.toml as text so the maintainer's comments and layout survive. The result is parsed again and - must be the same entries with only those tags set; if it is not (e.g. an entry is written as an - inline table), nothing is written and False is returned.""" - path = os.path.join(out_dir, ANSWERS_FILE) - with open(path, encoding="utf-8") as fh: - text = fh.read() - lines = text.splitlines(keepends=True) +def _insert_tags(lines: list[str], planned: dict[tuple[str, int], str], *, check_boundaries: bool) -> str: seen = {k: -1 for k in BINDING_KINDS} out: list[str] = [] k = 0 @@ -425,7 +417,7 @@ def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: out.append(line) k += 1 m = _ENTRY_HEADER.match(line.rstrip("\r\n")) - if not m or not _at_toml_boundary(lines, k - 1): + if not m or (check_boundaries and not _at_toml_boundary(lines, k - 1)): continue kind = m.group(1) seen[kind] += 1 @@ -438,7 +430,9 @@ def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: # An entry that already has a `binding` line (one copied from another entry) has it replaced. j = k while j < len(lines): - if (_ANY_HEADER.match(lines[j]) or _BINDING_LINE.match(lines[j])) and _at_toml_boundary(lines, j): + if (_ANY_HEADER.match(lines[j]) or _BINDING_LINE.match(lines[j])) and ( + not check_boundaries or _at_toml_boundary(lines, j) + ): break j += 1 if j < len(lines) and _BINDING_LINE.match(lines[j]): @@ -446,22 +440,42 @@ def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: k = j + 1 else: out.append(tag_line) - new = "".join(out) + return "".join(out) + + +def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool: + """Write `binding = ""` into the entries `planned` names ((kind, index) -> tag), editing + answers.toml as text so the maintainer's comments and layout survive. The result is parsed again and + must be the same entries with only those tags set; if it is not (e.g. an entry is written as an + inline table), nothing is written and False is returned.""" + path = os.path.join(out_dir, ANSWERS_FILE) + with open(path, encoding="utf-8") as fh: + text = fh.read() try: - before, after = tomllib.loads(text), tomllib.loads(new) + expected = tomllib.loads(text) except tomllib.TOMLDecodeError: return False for (kind, i), tag in planned.items(): - if i >= len(before.get(kind) or []): + if i >= len(expected.get(kind) or []): return False - before[kind][i] = {**before[kind][i], "binding": tag} - if before != after: - return False - tmp = path + ".tmp" - with open(tmp, "w", encoding="utf-8") as fh: - fh.write(new) - os.replace(tmp, path) - return True + expected[kind][i]["binding"] = tag + + # Most files can be edited in one scan. If an example inside a multiline + # value was mistaken for syntax, the round-trip check rejects the edit. + lines = text.splitlines(keepends=True) + for check_boundaries in (False, True): + new = _insert_tags(lines, planned, check_boundaries=check_boundaries) + try: + actual = tomllib.loads(new) + except tomllib.TOMLDecodeError: + continue + if actual == expected: + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8") as fh: + fh.write(new) + os.replace(tmp, path) + return True + return False def lookup(final: dict, ref) -> dict | None: diff --git a/review/tests/test_review.py b/review/tests/test_review.py index bb07f18a6..47f2a5d3e 100644 --- a/review/tests/test_review.py +++ b/review/tests/test_review.py @@ -1556,6 +1556,15 @@ def test_releasing_or_adding_an_entry_never_moves_another(self): self.assertEqual(code, 0, text) self.assertNotIn("STALE", text) + def test_ordinary_bindings_need_no_toml_prefix_parses(self): + text = '[[hold]] # keep this comment\nfinding = 1\nuntil = "Alice"\n' + write(self.out, answers.ANSWERS_FILE, text) + finding = {"id": "F1", "title": "Original finding", "severity": "should-fix"} + with mock.patch.object(answers, "_at_toml_boundary", side_effect=AssertionError("parsed a prefix")): + holds = answers.bind(self.out, {"findings": [finding]})["hold"] + self.assertEqual(holds[0]["finding"], finding) + self.assertIsNotNone(holds[0]["entry"]["binding"]) + def test_multiline_answer_cannot_retarget_a_hold(self): path = os.path.join(self.out, answers.ANSWERS_FILE) feedback = '[[answer]]\ntext = """An example header:\n[[hold]]\n"""\n' From 7098815a7ec02b96dac9d5a3f6cc46fd1d4a1439 Mon Sep 17 00:00:00 2001 From: Julian P Samaroo Date: Sat, 28 Nov 2026 22:53:45 -0700 Subject: [PATCH 6/6] review: preserve bindings for quoted TOML array headers Review finding 2 on PR #842 (nit): Quoted hold headers can still move a hold onto the wrong finding Requested: Recognize standard quoted hold and change headers with the TOML parser and verify that removing an entry preserves the other finding bindings. Identify a quoted standalone header with tomllib. Keep the existing candidate rewrite checks, so a quoted header example in a multiline value cannot disturb the finding tags. The new hold and change cases both fail on the former head and pass with the patch. The complete 111-test review suite passes on Python 3.11.15 and 3.14.6. Written by an AI agent on jpsamaroo's review feedback. --- review/reviewlib/answers.py | 20 +++++++++++++++++--- review/tests/test_review.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/review/reviewlib/answers.py b/review/reviewlib/answers.py index dee3d91de..3aab9b4bd 100644 --- a/review/reviewlib/answers.py +++ b/review/reviewlib/answers.py @@ -398,6 +398,21 @@ def new_tag(used=()) -> str: _BINDING_LINE = re.compile(r"^[ \t]*binding[ \t]*=") +def _entry_kind(line: str) -> str | None: + match = _ENTRY_HEADER.match(line.rstrip("\r\n")) + if match: + return match.group(1) + if not line.lstrip(" \t").startswith("[["): + return None + # TOML permits quoted keys in array-of-table headers. Accept only an + # empty top-level hold or change, excluding nested tables. + try: + header = tomllib.loads(line) + except tomllib.TOMLDecodeError: + return None + return next((kind for kind in BINDING_KINDS if header == {kind: [{}]}), None) + + def _at_toml_boundary(lines: list[str], index: int) -> bool: # A real header or assignment follows a complete prefix. The same text inside a multiline # string or array follows an unterminated value. Let tomllib distinguish those cases. @@ -416,10 +431,9 @@ def _insert_tags(lines: list[str], planned: dict[tuple[str, int], str], *, check line = lines[k] out.append(line) k += 1 - m = _ENTRY_HEADER.match(line.rstrip("\r\n")) - if not m or (check_boundaries and not _at_toml_boundary(lines, k - 1)): + kind = _entry_kind(line) + if kind is None or (check_boundaries and not _at_toml_boundary(lines, k - 1)): continue - kind = m.group(1) seen[kind] += 1 tag = planned.get((kind, seen[kind])) if tag is None: diff --git a/review/tests/test_review.py b/review/tests/test_review.py index 47f2a5d3e..720b02f47 100644 --- a/review/tests/test_review.py +++ b/review/tests/test_review.py @@ -8,6 +8,7 @@ import tempfile import textwrap import unittest +from pathlib import Path from unittest import mock sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) @@ -1600,6 +1601,35 @@ def test_binding_example_after_a_hold_header_is_preserved(self): self.assertIsNotNone(holds[0]["entry"]["binding"]) self.assertEqual(answers.load_holds(self.out)[0]["until"], 'An example field:\nbinding = "placeholder"') + def test_deleting_a_quoted_entry_preserves_the_other_binding(self): + first = {"id": "F1", "title": "Original finding", "severity": "should-fix"} + second = {"id": "F2", "title": "New finding", "severity": "blocker"} + for kind, quoted, field in (("hold", '"hold"', "until"), ("change", "'change'", "solution")): + with self.subTest(kind=kind), tempfile.TemporaryDirectory() as out: + path = Path(out) / answers.ANSWERS_FILE + header = f"[[ {quoted} ]]" + feedback = f'[[answer]]\ntext = """An example header:\n{header}\n"""\n' + path.write_text(feedback + f'\n{header} # original\nfinding = 1\n{field} = "Alice"\n', + encoding="utf-8") + entries = answers.bind(out, {"findings": [first]})[kind] + self.assertEqual(entries[0]["finding"], first) + self.assertIsNotNone(entries[0]["entry"]["binding"]) + + later_header = f"\n{header} # remaining" + with path.open("a", encoding="utf-8") as fh: + fh.write(later_header + f'\nfinding = 1\n{field} = "Bob"\n') + final = {"findings": [second, first]} + entries = answers.bind(out, final)[kind] + self.assertEqual([row["finding"] for row in entries], [first, second]) + later_tag = entries[1]["entry"]["binding"] + self.assertIsNotNone(later_tag) + body = path.read_text(encoding="utf-8") + self.assertTrue(body.startswith(feedback)) + path.write_text(feedback + body[body.index(later_header):], encoding="utf-8") + remaining, = answers.bind(out, final)[kind] + self.assertEqual(remaining["finding"], second) + self.assertEqual(remaining["entry"]["binding"], later_tag) + def test_rebind_confirms_only_its_own_kind(self): self.assertEqual(self.run_cli("submit")[0], 0) # Brief numbers: 1 removed method, 2 docstring, 3 extra.jl, 4 spawn's local path.