Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -1109,7 +1109,14 @@ this section verbatim). Each entry is one bullet starting with `- `.
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. **In eager mode, the scheduler's root thunk counts as running for the
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.

103. **In eager mode, the scheduler's root thunk counts as running for the
scheduler's whole life.** `start_state` credits it to `running_count`, and
it gives the credit back only after `state.halt` is notified. So
`running_count == 0` never happens before a halt, and any wait for "all
Expand All @@ -1123,7 +1130,7 @@ this section verbatim). Each entry is one bullet starting with `- `.
Compare the root by identity and not-finished state, not by id alone:
Thunk pooling (lesson 8) hands a recycled thunk a fresh id.

103. **Per-processor bookkeeping registered together must be dropped
104. **Per-processor bookkeeping registered together must be dropped
together.** The processor runner records a task's `cancel_tokens` entry
in the same lock as its `task_specs` entry, but `DoTaskSpec` dropped the
token only for cancelled tasks. Every normally finished task's token
Expand All @@ -1137,15 +1144,15 @@ this section verbatim). Each entry is one bullet starting with `- `.
*absence* of one entry next to the *presence* of another, check that
every exit path removes them as a pair.

104. **A queued cancellation result does not yet mark the thunk finished.**
105. **A queued cancellation result does not yet mark the thunk finished.**
A second cancel can acquire the scheduler lock before its result loop.
It must recognize a cancellation already queued for this thunk, or the
fallback posts another result and reports a cancellation it did not make.
Hold the scheduler lock across both requests in a regression test so the
result loop cannot make the race disappear. Reset the pending marker
when recycling a thunk or invalidating a completed result for replay.

105. **Never leave a timer running that Dagger cannot stop on its own.**
106. **Never leave a timer running that Dagger cannot stop on its own.**
A background task that loops on `sleep` (or any repeating `Timer`) keeps
libuv's event loop alive. Julia writes a package image only once that loop
is idle (`jl_task_wait_empty`), printing a notice after 10 ms and every
Expand Down
2 changes: 1 addition & 1 deletion review/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions review/REVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<scratch>/env -e 'using Pkg; Pkg.develop([PackageSpec(path="<worktree>"),
PackageSpec(path="<worktree>/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=<scratch>/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=<scratch>/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=<scratch>`; use
`julia --project=<scratch>/env -e 'include("test/runtests.jl")' -- --test <name>` instead, and check
Expand Down Expand Up @@ -168,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

Expand Down
2 changes: 1 addition & 1 deletion review/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
88 changes: 64 additions & 24 deletions review/reviewlib/answers.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,26 +398,42 @@ def new_tag(used=()) -> str:
_BINDING_LINE = re.compile(r"^[ \t]*binding[ \t]*=")


def _write_tags(out_dir: str, planned: dict[tuple[str, int], str]) -> bool:
"""Write `binding = "<tag>"` 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."""
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 _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.
try:
tomllib.loads("".join(lines[:index]))
except tomllib.TOMLDecodeError:
return False
return 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
while k < len(lines):
line = lines[k]
out.append(line)
k += 1
m = _ENTRY_HEADER.match(line.rstrip("\r\n"))
if not m:
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:
Expand All @@ -427,29 +443,53 @@ 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 (
not check_boundaries or _at_toml_boundary(lines, j)
):
break
j += 1
if j < len(lines) and _BINDING_LINE.match(lines[j]):
out += lines[k:j] + [tag_line]
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 = "<tag>"` 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:
Expand Down
26 changes: 15 additions & 11 deletions review/reviewlib/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [], []
Expand Down Expand Up @@ -479,18 +479,20 @@ 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:
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:]:
Expand Down Expand Up @@ -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"<details><summary>More explanations ({len(asked) - EXPLAIN_SHOWN})</summary>", "",
*asked[EXPLAIN_SHOWN:], "", "</details>"]
out.append("")
rows, collapsed, needs = _verdict_rows(final, ev)
out += ["### Verdicts", "", "| Verdict | Category | Basis | Summary |", "|:--|:--|:--|:--|"]
Expand All @@ -611,8 +615,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:]:
Expand Down
15 changes: 13 additions & 2 deletions review/reviewlib/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand Down
5 changes: 3 additions & 2 deletions review/rubric/tested.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading