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
34 changes: 34 additions & 0 deletions docs/evaluating.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,40 @@ coverage:
with gcov, so that CI compiles nothing. The files are run one at a time, in order (the counters are shared), and
what the verdict pass ran does not count: the counters are cleared first.

## Not evaluating again what has not changed: `--reuse`

With a fixed seed and the same parsers, evaluating a spec again can only give the same result (but for how fast it went, which is
the machine's). `--reuse` leaves that out:

```bash
fanbase evaluate --all --seed 1 --coverage --json-file evaluation.json --reuse https://github.com/acme/specs/releases/latest/download/quality.json
fanbase quality build evaluation.json -o quality.json # the specs that were not evaluated again keep what was found
```

Each spec in `quality.json` carries a **fingerprint** of everything its evaluation depended on:

- the spec **and everything it extends** (when `png` changes, so does `png-apng`), by the hash of each file;
- each **target** that judges it: every file of the target's folder, and the **version** the parser reports (a parser that is
upgraded, or that is not installed any more, is a change);
- **Fandango's** version and **fanbase's**;
- the settings that change what comes out: the number of inputs, the **seed**, the time Fandango gets, whether coverage is
measured and after how many inputs.

A spec whose fingerprint is the same as in the earlier results is not asked of Fandango or of the parsers: its earlier result is
kept, and the report says so. `decodes` is read from the spec as it is now (it is metadata, not part of the grammar), so a changed
expectation is checked against the kept result without evaluating anything (`--strict` sees it).

Things to know:

- **Use one seed.** The seed is part of the fingerprint. A seed that changes every week, as in the registry's workflows until now,
makes every spec a change every week.
- **A full evaluation is still the way to be sure.** The fingerprint does not know the Python packages a spec imports, nor
anything about the machine that no version string says. Evaluate without `--reuse` at each release.
- **Speed** is the machine's: a reused result keeps the speed it was measured at.
- **The private record** (`--incidents`) holds what was found in the specs that were evaluated; a bug found in a spec that was
not is in the record of the run that found it.
- Results that cannot be read are not an error: everything is evaluated, and it says so.

## Choosing between grammars: `quality.json` and `--compare-with`

Several specs can describe the same format. What is kept of an evaluation for choosing between them is
Expand Down
1 change: 1 addition & 0 deletions src/fanbase/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,7 @@ def build_parser() -> argparse.ArgumentParser:
p.add_argument("--incidents", metavar="DIR", help="write the private record of targets that crash, hang or are killed to DIR (only you can read it)")
p.add_argument("--incident-recipients", metavar="FILE", help="with --incidents: encrypt the record with age to the public key(s) in FILE, and never print anything about it; for CI")
p.add_argument("--compare-with", metavar="FILE|URL", help="say what changed since earlier results (quality.json, or a report of --json-file); nothing to compare with is only said")
p.add_argument("--reuse", metavar="FILE|URL", help="earlier results (quality.json): a spec that nothing it depends on has changed since is not evaluated again, and its earlier result is kept; a different seed or count counts as a change, so use one seed. Leave it out for a full evaluation")
p.add_argument("--fail-on-worse", action="store_true", help="with --compare-with: exit 1 if a spec does worse than before on a parser that is the same")
p.add_argument("--coverage", action="store_true", help="also measure how much of the library each target that can be measured runs on the files, against real files (needs the image of the registry's coverage/)")
p.add_argument("--coverage-only", action="store_true", help="--coverage, and only the targets that can be measured, not the ones the formats name")
Expand Down
45 changes: 44 additions & 1 deletion src/fanbase/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from dataclasses import dataclass, field
from pathlib import Path

from fanbase import __version__, compare as comparing, quality as quality_results
from fanbase import __version__, compare as comparing, fingerprint as fingerprints, quality as quality_results
from fanbase.context import Context
from fanbase.contrib import changed_specs, checkout, find_fandango, produce
from fanbase.coverage import DEFAULT_CURVE, CoverageError, CoverageResult, coverage_targets, measure
Expand Down Expand Up @@ -78,13 +78,18 @@ class SpecReport:
targets: list[TargetReport] = field(default_factory=list)
decodes: str | None = None
unjudged: str = "" # why no target judged it
fingerprint: str = "" # everything this evaluation depends on (see fingerprint.py)
reused: dict | None = None # the earlier row of quality.json, when nothing it depends on has changed (--reuse)
reused_made: str | None = None # when that row was made

@property
def per_second(self) -> float:
return self.produced / self.seconds if self.seconds else 0.0

@property
def best(self) -> float | None:
if self.reused is not None:
return self.reused.get("best_accepted")
ran = [t.result for t in self.targets if t.status == "ok" and t.result and t.result.total]
return max((r.accepted / r.total for r in ran), default=None)

Expand Down Expand Up @@ -153,6 +158,18 @@ def evaluate_spec(reg: Registry, entry: Entry, ctx: Context, args, fandango: str
if not report.targets else "none of the targets judges this format")
return report

report.fingerprint = fingerprints.of(reg, entry, ctx, targets, {
"count": args.count, "seed": args.seed, "budget": args.budget, "coverage": bool(getattr(args, "coverage", False)),
"curve": list(getattr(args, "curve_points", ())), "fandango": _fandango_version(), "fanbase": __version__})
earlier = getattr(args, "reuse_doc", None)
row = earlier["specs"].get(str(entry)) if earlier is not None else None
if earlier is not None and row and row.get("fingerprint") == report.fingerprint and row.get("sha256") == report.sha256 \
and (row.get("targets") or row.get("coverage")):
report.reused, report.reused_made = row, earlier.get("made")
report.produced = row.get("count") or 0
report.seconds = report.produced / row["per_second"] if row.get("per_second") else 0.0
return report

made = produce(reg, entry, ctx, count=args.count, timeout=1800, fandango=fandango,
install_them=not args.no_requirements, say=say, seed=args.seed, budget=args.budget or None)
try:
Expand Down Expand Up @@ -209,6 +226,8 @@ def to_json(reports: list[SpecReport], args) -> dict:
"spec": str(r.entry),
"version": r.version,
"sha256": r.sha256,
"fingerprint": r.fingerprint or None,
**({"reused": {"made": r.reused_made, "row": r.reused}} if r.reused is not None else {}),
"generated": {"requested": r.requested, "produced": r.produced, "seconds": round(r.seconds, 3),
"per_second": round(r.per_second, 2), "note": r.note or None},
"error": r.error,
Expand Down Expand Up @@ -295,6 +314,13 @@ def as_text(reports: list[SpecReport], args) -> str:
if r.error:
out += [f"{head}: no inputs: {clean(r.error)}", ""]
continue
if r.reused is not None:
out.append(f"{head}: not evaluated again, nothing it depends on has changed since {clean(r.reused_made or 'the results')}"
f": {quality_results.summary(r.reused)}")
if expect := _expectation(r):
out.append(f" {expect}")
out.append("")
continue
out.append(f"{head}: {r.produced} inputs from seed {args.seed} in {r.seconds:.1f}s ({quality_results.speed(r.per_second)}/s)")
if r.note:
out.append(f" note: {clean(r.note)}")
Expand Down Expand Up @@ -332,6 +358,12 @@ def as_markdown(reports: list[SpecReport], args) -> str:
if r.error:
out += [f"**No inputs:** {clean(r.error)}", ""]
continue
if r.reused is not None:
out += [f"Not evaluated again: nothing it depends on has changed since {clean(r.reused_made or 'the results')}. "
f"{quality_results.summary(r.reused)}.", ""]
if expect := _expectation(r):
out += [f"{'✅' if r.met else '⚠️'} {expect}", ""]
continue
out.append(f"{r.produced} inputs in {r.seconds:.1f}s ({quality_results.speed(r.per_second)}/s)." + (f" {clean(r.note)}." if r.note else ""))
out.append("")
if r.unjudged:
Expand Down Expand Up @@ -392,6 +424,12 @@ def cmd_evaluate(args, ctx: Context) -> int:
if getattr(args, "coverage_only", False):
args.coverage = True
args.curve_points = _curve(args.curve) if getattr(args, "curve", None) is not None else DEFAULT_CURVE
args.reuse_doc = None
if getattr(args, "reuse", None):
try:
args.reuse_doc = quality_results.load(args.reuse)
except RegistryError as exc: # nothing to reuse yet is not a failure: everything is evaluated
print(f"nothing reused: {clean(exc)}", file=sys.stderr)
log = IncidentLog() if args.incidents else None
reg = checkout(ctx)
fandango = find_fandango()
Expand Down Expand Up @@ -445,6 +483,11 @@ def cmd_evaluate(args, ctx: Context) -> int:
if earlier is not None:
print(comparing.as_text(earlier, differences), end="")

if args.reuse_doc is not None:
reused = sum(1 for r in reports if r.reused is not None)
print(f"reused the results of {reused} of {len(reports)} spec(s) from {clean(args.reuse_doc.get('made') or 'earlier')}; "
f"evaluated {len(reports) - reused}", file=sys.stderr)

failed = [r for r in reports if r.error]
if failed:
print(f"no inputs from {', '.join(str(r.entry) for r in failed)}", file=sys.stderr)
Expand Down
62 changes: 62 additions & 0 deletions src/fanbase/fingerprint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""What an evaluation of a spec depends on, as one hash.

Evaluating a spec means asking Fandango for inputs and asking the parsers of its format about them. If the spec, what it
extends, the parsers, Fandango, fanbase and the settings are the same as when it was last evaluated, the result can only be
the same (but for how fast it went, which is the machine's), and `fanbase evaluate --reuse` need not do it again.

What is in the fingerprint:

- the spec and everything it extends (`png-apng` builds on `png`: when `png` changes, so does the fingerprint of `png-apng`),
each by the hash of its file;
- each target that judges it: every file of its folder (`target.yml`, its harness), and the version it reports (a parser that is
upgraded, or that is not there any more);
- Fandango's version and fanbase's;
- the settings that change what comes out: the number of inputs, the seed, the time Fandango gets, whether coverage is measured
and after how many inputs.

What is not: the Python packages that a spec imports (a package that changes its output changes it without the spec changing),
and anything about the machine that no version string says. That is what a full evaluation without `--reuse` at each release
is for.
"""

from __future__ import annotations

import hashlib
import json
from pathlib import Path

from fanbase.deps import closure
from fanbase.manager import entry_sha
from fanbase.targets import Target, unavailable, version_of

MAX_TARGET_BYTES = 4 * 1024 * 1024 # a target's folder is a few small files; past this, only its size is counted


def directory_digest(directory: Path) -> str:
"""A hash of the files of a folder, by name and content (not of hidden files or caches)."""
digest = hashlib.sha256()
left = MAX_TARGET_BYTES
files = sorted(p for p in directory.rglob("*")
if p.is_file() and not any(part.startswith(".") or part == "__pycache__" for part in p.relative_to(directory).parts))
for path in files:
digest.update(path.relative_to(directory).as_posix().encode() + b"\0")
size = path.stat().st_size
if size <= left:
digest.update(path.read_bytes())
left -= size
else:
digest.update(f"[{size} bytes]".encode())
digest.update(b"\0")
return digest.hexdigest()


def of(reg, entry, ctx, targets: list[Target], settings: dict) -> str:
"""The fingerprint of evaluating `entry` against `targets` with these settings."""
parts = {
"specs": sorted((str(e), entry_sha(r, e)) for r, e in closure(ctx, reg, entry)),
"targets": sorted(
(t.name, directory_digest(t.directory), "unavailable" if unavailable(t) is not None else version_of(t))
for t in targets),
"settings": settings,
}
return hashlib.sha256(json.dumps(parts, sort_keys=True, default=str).encode()).hexdigest()
16 changes: 15 additions & 1 deletion src/fanbase/quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,27 @@ def build(reports: list[dict], previous: dict | None = None) -> dict:
if spec.get("error") or not spec.get("sha256"):
continue
key = spec["spec"]
if isinstance(spec.get("reused"), dict) and isinstance(spec["reused"].get("row"), dict) \
and spec["reused"]["row"].get("sha256") == spec["sha256"]:
# not evaluated again: what was found before stays, but for what the spec says to expect, which may have changed
kept = dict(spec["reused"]["row"])
kept["decodes"] = spec.get("decodes")
best = kept.get("best_accepted")
from fanbase.evaluate import band

kept["expectation_met"] = band(best) == kept["decodes"] if kept["decodes"] and best is not None else None
kept["fingerprint"] = spec.get("fingerprint") or kept.get("fingerprint")
specs[key] = kept
continue
current = specs.get(key)
if current is None or current.get("sha256") != spec["sha256"]:
current = specs[key] = {"version": spec.get("version"), "sha256": spec["sha256"], "targets": {}, "coverage": {}}
targets: dict = current["targets"]
coverages: dict = current["coverage"]
generated = spec.get("generated") or {}
current.update(count=generated.get("produced"), seed=report.get("seed"),
per_second=generated.get("per_second"), decodes=spec.get("decodes"))
per_second=generated.get("per_second"), decodes=spec.get("decodes"),
fingerprint=spec.get("fingerprint"))
for target in spec.get("targets", []):
if target.get("status") != "ok" or not target.get("total"):
continue
Expand Down Expand Up @@ -147,6 +160,7 @@ def parse(data: bytes | str) -> dict:
"decodes": spec.get("decodes") if spec.get("decodes") in ("always", "mostly", "rarely", "never") else None,
"best_accepted": _ratio(spec.get("best_accepted")),
"expectation_met": spec.get("expectation_met") if isinstance(spec.get("expectation_met"), bool) else None,
"fingerprint": spec["fingerprint"] if isinstance(spec.get("fingerprint"), str) and _SHA.fullmatch(spec["fingerprint"]) else None,
"targets": {}, "coverage": {}}
for name, target in (spec.get("targets") or {}).items():
if is_safe_name(name) and isinstance(target, dict):
Expand Down
Loading
Loading