Skip to content
Open
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
90 changes: 90 additions & 0 deletions scripts/run_differential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

"""Run the v0-vs-v1 differential and print a report.

python scripts/run_differential.py [--spec DIR] [--generated N] [--seed S] [--jsonl OUT]

Cases come from an openjd-specifications checkout (samples and conformance
tests) and, with ``--generated``, from the template generator. Each
disagreement is printed with the first point where the two projections differ,
and grouped by its known-difference class (``known_differences.yaml``) or as
NEW.
"""

from __future__ import annotations

import argparse
import collections
import json
import os
import random
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from test.openjd.differential import _corpus, _generate, _harness, _known # noqa: E402


def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--spec", type=Path, default=None)
ap.add_argument("--generated", type=int, default=0, help="number of generated templates")
ap.add_argument("--seed", type=int, default=None)
ap.add_argument("--jsonl", type=Path, default=None, help="write one line per disagreement")
ap.add_argument("--show", type=int, default=3, help="examples to print per class")
args = ap.parse_args()

if args.spec:
os.environ["OPENJD_SPECIFICATIONS_DIR"] = str(args.spec)
spec = _corpus.specifications_dir()
cases = list(_corpus.spec_cases(spec)) if spec else []
seed = args.seed if args.seed is not None else random.randrange(1, 2**31)
if args.generated:
cases += list(_generate.cases(args.generated, seed))

known = _known.load()
start = time.monotonic()
by_class: dict[str, list] = collections.defaultdict(list)
n_err_pairs = n_err_text_equal = 0
for case in cases:
c = _harness.compare(case)
if c.error_text_equal is not None:
n_err_pairs += 1
n_err_text_equal += int(c.error_text_equal)
if c.agree:
continue
by_class[_known.classify(c, known) or "NEW"].append(c)
seconds = time.monotonic() - start

disagree = sum(len(v) for v in by_class.values())
print(f"spec: {spec}")
print(f"cases: {len(cases)} ({args.generated} generated, seed {seed}) in {seconds:.1f} s")
print(f"agree: {len(cases) - disagree} disagree: {disagree}")
if n_err_pairs:
print(f"both rejected: {n_err_pairs}, same error text: {n_err_text_equal}")
print()
for cls in sorted(by_class, key=lambda k: (k != "NEW", -len(by_class[k]), k)):
rows = by_class[cls]
title = known[cls]["title"] if cls in known else "not in known_differences.yaml"
print(f"[{cls}] {len(rows)} case(s): {title}")
for c in rows[: args.show]:
print(f" {c.case.name}")
print(f" {json.dumps(c.summary(), default=str)[:300]}")
if args.jsonl:
with args.jsonl.open("w", encoding="utf-8") as f:
for cls, rows in sorted(by_class.items()):
for c in rows:
f.write(
json.dumps({"class": cls, "case": c.case.name, **c.summary()}, default=str)
)
f.write("\n")
return 1 if "NEW" in by_class else 0


if __name__ == "__main__":
sys.exit(main())
51 changes: 51 additions & 0 deletions test/openjd/differential/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# v0 / v1 differential

This package ships two implementations of the same model: `openjd.model`
(v0, pure Python) and `openjd.model._v1` (Rust-backed). This directory runs
the same inputs through both and compares the results.

Each input goes through these steps:
`decode → preprocess_job_parameters → create_job → StepParameterSpaceIterator`.
Each result is reduced to a plain projection:

- the stage the input stops at (accept/reject agreement);
- the resolved job parameters (type and written value);
- for each step: the resolved `onRun` command, args and timeout; the
embedded files; the step and job environments; and the full task list.

Error text is recorded but not compared.

## Inputs

| Source | Cases |
|---|---|
| `openjd-specifications/samples/v2023-09` | the published samples |
| `openjd-specifications/conformance-tests/*/*/{job_templates,env_templates}` | valid and `.invalid` templates |
| `openjd-specifications/conformance-tests/*/*/jobs/*.test.yaml` | templates with their own parameter values and environments |
| `_generate.py` | seeded, nearly valid templates: number spellings, non-ASCII lengths, descending ranges, edge PATHs, combinations, NONCONTIGUOUS chunks |

The specifications checkout comes from `OPENJD_SPECIFICATIONS_DIR` or from a
sibling `../openjd-specifications`.

## Known differences

`known_differences.yaml` lists each known class. It names the side that the
specification or the conformance corpus says is wrong (or both), and the
matchers for the class.

- A difference that no class matches is NEW, and the tests fail.
- A class that no case shows any more is stale, and the tests fail.
- `test_a_planted_change_in_v1_is_caught` drops one task from each v1 step
and checks that the differential reports it.

## Running

```bash
# The tests. The Hypothesis seed search is opt-in with -m fuzz.
hatch run test-subset test/openjd/differential
pytest test/openjd/differential -m fuzz --no-cov

# A report, grouped by class. Exit status 1 if there is a NEW difference.
python scripts/run_differential.py --generated 5000 --seed 1
python scripts/run_differential.py --generated 1 --seed <case seed> # replay one case
```
1 change: 1 addition & 0 deletions test/openjd/differential/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
102 changes: 102 additions & 0 deletions test/openjd/differential/_corpus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

"""Load differential cases from an openjd-specifications checkout.

Sources:

* ``samples/v2023-09/{job_templates,env_templates}`` -- the published samples;
* ``conformance-tests/<rev>/<ext>/{job_templates,env_templates}`` -- valid and
``.invalid`` templates;
* ``conformance-tests/<rev>/<ext>/jobs/*.test.yaml`` -- a template with its own
job parameter values and environment templates.

The checkout is found through ``OPENJD_SPECIFICATIONS_DIR``, or a sibling
``openjd-specifications`` directory next to this repository.
"""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Iterator, Optional

import yaml

from ._harness import Case

REPO_ROOT = Path(__file__).resolve().parents[3]
_PLATFORM = "windows" if os.name == "nt" else "posix"


def specifications_dir() -> Optional[Path]:
env = os.environ.get("OPENJD_SPECIFICATIONS_DIR")
candidates = [Path(env)] if env else []
candidates.append(REPO_ROOT.parent / "openjd-specifications")
for c in candidates:
if (c / "conformance-tests").is_dir():
return c.resolve()
return None


def _load(path: Path):
text = path.read_text(encoding="utf-8")
if path.suffix == ".json":
return json.loads(text)
return yaml.safe_load(text)


def _templates(root: Path, prefix: str, kind: str) -> Iterator[Case]:
for path in sorted(root.glob("*")):
if path.suffix not in (".yaml", ".yml", ".json") or not path.is_file():
continue
try:
doc = _load(path)
except Exception: # noqa: BLE001 -- not valid YAML: not a model test
continue
expect = (
"reject" if ".invalid." in path.name else "accept" if "conformance" in prefix else None
)
yield Case(
name=f"{prefix}/{path.name}",
template=doc,
template_dir=path.parent,
kind=kind,
expect=expect,
)


def _job_tests(root: Path, prefix: str) -> Iterator[Case]:
for path in sorted(root.glob("*.test.yaml")):
try:
doc = _load(path)
except Exception: # noqa: BLE001
continue
if not isinstance(doc, dict) or "template" not in doc:
continue
run_on = doc.get("runOn")
if isinstance(run_on, list) and _PLATFORM not in run_on:
continue # the test is for another OS; PATH handling depends on it
params = doc.get("parameters")
yield Case(
name=f"{prefix}/{path.name}",
template=doc["template"],
environments=list(doc.get("environments") or []),
parameters=dict(params) if isinstance(params, dict) else None,
template_dir=path.parent,
expect="reject-any" if ".invalid." in path.name else "accept",
)


def spec_cases(spec: Path) -> Iterator[Case]:
samples = spec / "samples" / "v2023-09"
yield from _templates(samples / "job_templates", "samples/job_templates", "job")
yield from _templates(samples / "env_templates", "samples/env_templates", "environment")
for ext in sorted((spec / "conformance-tests").glob("*/*")):
if not ext.is_dir():
continue
prefix = f"conformance/{ext.parent.name}/{ext.name}"
yield from _templates(ext / "job_templates", f"{prefix}/job_templates", "job")
yield from _templates(ext / "env_templates", f"{prefix}/env_templates", "environment")
yield from _job_tests(ext / "jobs", f"{prefix}/jobs")
Loading
Loading