diff --git a/scripts/run_differential.py b/scripts/run_differential.py new file mode 100644 index 00000000..a59a3b8d --- /dev/null +++ b/scripts/run_differential.py @@ -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()) diff --git a/test/openjd/differential/README.md b/test/openjd/differential/README.md new file mode 100644 index 00000000..a9083ba2 --- /dev/null +++ b/test/openjd/differential/README.md @@ -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 # replay one case +``` diff --git a/test/openjd/differential/__init__.py b/test/openjd/differential/__init__.py new file mode 100644 index 00000000..8d929cc8 --- /dev/null +++ b/test/openjd/differential/__init__.py @@ -0,0 +1 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/test/openjd/differential/_corpus.py b/test/openjd/differential/_corpus.py new file mode 100644 index 00000000..34487249 --- /dev/null +++ b/test/openjd/differential/_corpus.py @@ -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///{job_templates,env_templates}`` -- valid and + ``.invalid`` templates; +* ``conformance-tests///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") diff --git a/test/openjd/differential/_generate.py b/test/openjd/differential/_generate.py new file mode 100644 index 00000000..abe46eb8 --- /dev/null +++ b/test/openjd/differential/_generate.py @@ -0,0 +1,218 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Seeded generator of job templates for the differential. + +Templates are built to be *nearly* valid: most parts are drawn from valid +forms and a few from edge forms (number spellings, non-ASCII lengths, +descending ranges, boundary values, wrong types, NONCONTIGUOUS chunks). The +aim is to reach create_job and the parameter space iterator often, where the +two implementations hold most of their logic, while still exercising +validation. + +The generator only uses ``random.Random(seed)``, so a case is replayed from +its seed: ``python scripts/run_differential.py --generated N --seed S``. +""" + +from __future__ import annotations + +import random +from pathlib import Path +from typing import Any, Iterator + +from ._harness import Case + +INT_SPELLINGS: list[Any] = [ + 0, + 1, + -1, + 7, + 100, + 2**31, + 2**53 + 1, + 2**63 - 1, + -(2**63), + 2**63, + "5", + " 7 ", + "1_000", + "42.0", + "0x10", +] +FLOAT_SPELLINGS: list[Any] = [ + 0, + 1, + 2, + -0.0, + 0.5, + 1.5, + 1e3, + 1e20, + 5e300, + 9007199254740993, + "2", + "2.0", + "1e3", + "-0", + "nan", +] +STRINGS = ["", "a", "abc", "héllo", "日本語", "😀", "a b", " pad ", "{{x}}", "x" * 64, "é" * 33] +PATHS = [ + "/abs/a", + "rel/a", + "./a", + "a/../b", + "a//b", + "out/", + ".", + "..", + "s3://bucket/key", + "C:\\x\\y", + "", +] + + +def _int_range(r: random.Random) -> str: + form = r.randrange(6) + a, b = r.randint(-20, 20), r.randint(-20, 20) + lo, hi = min(a, b), max(a, b) + if form == 0: + return f"{lo}-{hi}" + if form == 1: + return f"{hi}-{lo}" # descending + if form == 2: + return f"{lo}-{hi}:{r.choice([1, 2, 3, 5])}" + if form == 3: + return f"{hi}-{lo}:-{r.choice([1, 2, 3])}" # negative step + if form == 4: + vals = sorted(set(r.sample(range(-10, 30), r.randint(1, 6)))) + if r.random() < 0.3: + r.shuffle(vals) + return ",".join(str(v) for v in vals) + return f"{a}" if r.random() < 0.5 else f" {lo} - {hi} " + + +def _task_param(r: random.Random, name: str) -> dict[str, Any]: + kind = r.choice(["INT", "INT", "INT", "FLOAT", "STRING", "PATH"]) + rng: Any + if kind == "INT": + if r.random() < 0.6: + rng = _int_range(r) + else: + rng = [r.choice(INT_SPELLINGS[:9]) for _ in range(r.randint(1, 4))] + elif kind == "FLOAT": + rng = [r.choice(FLOAT_SPELLINGS[:10]) for _ in range(r.randint(1, 4))] + elif kind == "STRING": + rng = r.sample(STRINGS[1:9], r.randint(1, 3)) + else: + rng = r.sample(PATHS[:8], r.randint(1, 3)) + return {"name": name, "type": kind, "range": rng} + + +def _chunk_param(r: random.Random, name: str) -> dict[str, Any]: + """A NONCONTIGUOUS CHUNK[INT] parameter over an increasing range.""" + lo = r.randint(-10, 10) + hi = lo + r.randint(0, 20) + form = r.randrange(3) + rng: Any + if form == 0: + rng = f"{lo}-{hi}" + elif form == 1: + rng = f"{lo}-{hi}:{r.choice([2, 3])}" + else: + rng = sorted(set(r.sample(range(lo, hi + 1), min(hi - lo + 1, r.randint(1, 8))))) + return { + "name": name, + "type": "CHUNK[INT]", + "range": rng, + "chunks": { + "defaultTaskCount": r.choice([1, 2, 3, 4, 7]), + "rangeConstraint": "NONCONTIGUOUS", + }, + } + + +def _job_param(r: random.Random, name: str) -> dict[str, Any]: + kind = r.choice(["INT", "FLOAT", "STRING", "PATH", "STRING", "INT"]) + p: dict[str, Any] = {"name": name, "type": kind} + if kind == "INT": + if r.random() < 0.8: + p["default"] = r.choice(INT_SPELLINGS) + if r.random() < 0.3: + p["minValue"] = r.choice([0, 1, -5, "0"]) + if r.random() < 0.3: + p["maxValue"] = r.choice([10, 2**63 - 1, "100"]) + elif kind == "FLOAT": + if r.random() < 0.8: + p["default"] = r.choice(FLOAT_SPELLINGS) + if r.random() < 0.3: + p["minValue"] = r.choice([0, 0.5, "0"]) + elif kind == "STRING": + if r.random() < 0.8: + p["default"] = r.choice(STRINGS) + if r.random() < 0.4: + p["minLength"] = r.choice([0, 1, 3]) + if r.random() < 0.4: + p["maxLength"] = r.choice([1, 3, 5, 64]) + if r.random() < 0.2: + p["allowedValues"] = r.sample(STRINGS[1:], 3) + else: + if r.random() < 0.8: + p["default"] = r.choice(PATHS) + if r.random() < 0.3: + p["objectType"] = r.choice(["FILE", "DIRECTORY"]) + p["dataFlow"] = r.choice(["IN", "OUT", "INOUT", "NONE"]) + return p + + +def template(r: random.Random) -> dict[str, Any]: + params = [_job_param(r, f"P{i}") for i in range(r.randint(0, 4))] + steps = [] + chunked = False + for s in range(r.randint(1, 3)): + tps = [_task_param(r, f"T{i}") for i in range(r.randint(0, 3))] + step_chunked = r.random() < 0.15 + if step_chunked: + tps.append(_chunk_param(r, f"T{len(tps)}")) + chunked = True + args = [f"{{{{Param.{p['name']}}}}}" for p in params] + args += [f"{{{{Task.Param.{t['name']}}}}}" for t in tps] + step: dict[str, Any] = { + "name": f"S{s}", + "script": {"actions": {"onRun": {"command": "echo", "args": args or ["x"]}}}, + } + if tps: + space: dict[str, Any] = {"taskParameterDefinitions": tps} + if len(tps) > 1 and not step_chunked and r.random() < 0.5: + names = [t["name"] for t in tps] + r.shuffle(names) + if r.random() < 0.5: + space["combination"] = f"({names[0]}, {names[1]})" + "".join( + f" * {n}" for n in names[2:] + ) + else: + space["combination"] = " * ".join(names) + step["parameterSpace"] = space + if s and r.random() < 0.4: + step["dependencies"] = [{"dependsOn": f"S{r.randrange(s)}"}] + steps.append(step) + doc: dict[str, Any] = { + "specificationVersion": "jobtemplate-2023-09", + "name": r.choice(["J", "Job é", "j" * 64]), + "steps": steps, + } + if chunked: + doc["extensions"] = ["TASK_CHUNKING"] + if params: + doc["parameterDefinitions"] = params + return doc + + +def cases(n: int, seed: int) -> Iterator[Case]: + for i in range(n): + case_seed = (seed * 1_000_003 + i) % 2**32 + yield Case( + name=f"generated/{case_seed}", + template=template(random.Random(case_seed)), + template_dir=Path("/tmp/openjd-differential"), + ) diff --git a/test/openjd/differential/_harness.py b/test/openjd/differential/_harness.py new file mode 100644 index 00000000..c0414e57 --- /dev/null +++ b/test/openjd/differential/_harness.py @@ -0,0 +1,519 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Cross-implementation differential harness: v0 (pure Python) vs v1 (Rust). + +Each case is one job template (plus optional environment templates and job +parameter values). The harness runs the case through the same pipeline on both +implementations + + decode -> preprocess_job_parameters -> create_job -> iterate parameter space + +and reduces each result to a plain, JSON-serializable *projection*. Two +implementations agree on a case when their projections are equal. + +What is compared: + +* the stage a case stops at (``decode``, ``preprocess``, ``create_job``, + ``iterate``, or ``ok``) -- that is, accept/reject agreement; +* on success: resolved job parameters (type and value), each step's name, + dependencies, resolved action command/args/timeout, embedded files, step + and job environments, and the task list from the parameter space iterator. + +Error *text* is recorded but not compared: the two implementations word their +errors differently on purpose. ``error_text_equal`` reports it as a metric. +""" + +from __future__ import annotations + +import enum +import json +import math +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Optional + +import openjd.model as v0 +import openjd.model._v1 as v1 + +# The task list of a step is compared in full up to this many tasks; past it, +# the count, the first and the last ``TASK_SAMPLE`` tasks are compared. +TASK_LIMIT = 2000 +TASK_SAMPLE = 50 + +MISSING = "" + +STAGES = ("decode", "preprocess", "create_job", "iterate", "ok") + + +@dataclass +class Case: + """One differential input.""" + + name: str + template: Any + environments: list[Any] = field(default_factory=list) + parameters: Optional[dict[str, Any]] = None + template_dir: Path = Path("/") + kind: str = "job" # "job" or "environment" + # What the corpus file says should happen: "accept", "reject" (a template + # that must fail validation), "reject-any" (a job test that must fail at + # some point, possibly only when run), or None (no expectation). + expect: Optional[str] = None + + +@dataclass +class Outcome: + stage: str + projection: Any = None + error: Optional[str] = None + error_type: Optional[str] = None + + +@dataclass +class Comparison: + case: Case + v0: Outcome + v1: Outcome + + @property + def agree(self) -> bool: + return self.v0.stage == self.v1.stage and self.v0.projection == self.v1.projection + + @property + def error_text_equal(self) -> Optional[bool]: + if self.v0.error is None or self.v1.error is None: + return None + return self.v0.error.strip() == self.v1.error.strip() + + def verdict(self) -> Optional[str]: + """For a stage difference on a case with an expectation: which side + the corpus agrees with ("v0", "v1"), or None when it cannot tell.""" + if self.v0.stage == self.v1.stage or self.case.expect is None: + return None + if ( + self.case.kind == "environment" + or self.case.expect in ("accept", "reject") + and ("/job_templates/" in self.case.name or "/env_templates/" in self.case.name) + ): + # A template test (``openjd check``) is about validation only. + ok0, ok1 = self.v0.stage != "decode", self.v1.stage != "decode" + else: + ok0, ok1 = self.v0.stage == "ok", self.v1.stage == "ok" + if self.case.expect == "accept": + return "v0" if ok0 and not ok1 else "v1" if ok1 and not ok0 else None + if self.case.expect == "reject": + return "v0" if not ok0 and ok1 else "v1" if not ok1 and ok0 else None + # reject-any: the side that already fails is right; the other side + # may still fail at run time, which this harness does not reach. + return "v0?" if not ok0 and ok1 else "v1?" if not ok1 and ok0 else None + + def summary(self) -> dict[str, Any]: + """A short description of where the two sides first differ.""" + if self.v0.stage != self.v1.stage: + both_reject = "ok" not in (self.v0.stage, self.v1.stage) + return { + "kind": "reject-stage" if both_reject else "stage", + "corpus_agrees_with": self.verdict(), + "v0": self.v0.stage, + "v1": self.v1.stage, + "v0_error": _short(self.v0.error), + "v1_error": _short(self.v1.error), + } + path, a, b = first_difference(self.v0.projection, self.v1.projection) + order = _task_order_only(self.v0.projection, self.v1.projection, path) + return {"kind": "task-order" if order else "value", "path": path, "v0": a, "v1": b} + + +def _task_order_only(a: Any, b: Any, path: str) -> bool: + """True when the first difference is inside a step's task list and the + two task lists hold the same tasks in another order.""" + if ".tasks." not in path or not path.startswith("$.steps["): + return False + i = int(path[len("$.steps[") : path.index("]")]) + ta, tb = a["steps"][i]["tasks"], b["steps"][i]["tasks"] + if ta.get("count") != tb.get("count") or "tasks" not in ta or "tasks" not in tb: + return False + key = lambda t: json.dumps(t, sort_keys=True) # noqa: E731 + return sorted(map(key, ta["tasks"])) == sorted(map(key, tb["tasks"])) + + +def _short(text: Optional[str], limit: int = 240) -> Optional[str]: + if text is None: + return None + text = " ".join(text.split()) + return text if len(text) <= limit else text[: limit - 3] + "..." + + +def first_difference(a: Any, b: Any, path: str = "$") -> tuple[str, Any, Any]: + if type(a) is not type(b): + return path, a, b + if isinstance(a, dict): + for key in sorted(set(a) | set(b), key=str): + if a.get(key, MISSING) != b.get(key, MISSING): + return first_difference(a.get(key, MISSING), b.get(key, MISSING), f"{path}.{key}") + elif isinstance(a, list): + if len(a) != len(b): + return f"{path}.length", len(a), len(b) + for i, (x, y) in enumerate(zip(a, b)): + if x != y: + return first_difference(x, y, f"{path}[{i}]") + return path, a, b + + +# --------------------------------------------------------------------------- +# Canonical projection. Both implementations expose the same attribute names +# (v1 offers camelCase aliases), so one projection serves both. +# --------------------------------------------------------------------------- + + +def type_name(t: Any) -> str: + if t is None: + return MISSING + if hasattr(t, "as_str"): + return t.as_str() + if isinstance(t, enum.Enum): + return str(t.value) + return str(t).rsplit(".", 1)[-1] + + +def scalar(x: Any) -> Any: + if x is None or isinstance(x, (bool, int)): + return x + if isinstance(x, float): + return repr(x) if not math.isfinite(x) else x + if isinstance(x, enum.Enum) or hasattr(x, "as_str"): + return type_name(x) + # str, v1 FormatString, v0 FormatString (a str subclass), Decimal, ... + return _GENERATED_REF.sub(r"\1_", str(x)) + + +# A reference to a SimpleAction's generated embedded file, in a format string. +_GENERATED_REF = re.compile(r"(Task\.File\.[A-Za-z0-9_]+?)_(?:[A-Za-z0-9]{6}|script)\b") + + +def get(obj: Any, *names: str) -> Any: + for n in names: + if obj is not None and hasattr(obj, n): + return getattr(obj, n) + return MISSING + + +def _structured(value: Any) -> Any: + """LIST and BOOL values: v1 returns JSON text, v0 Python objects (and v0 + keeps a LIST[LIST[INT]] row as JSON text). Compare the decoded value. + Numbers keep their spelling (``2`` and ``2.0`` differ).""" + if not isinstance(value, (str, list, tuple, bool, int, float, type(None))): + value = str(value) # v1 ExprValue: its str() is JSON + if isinstance(value, bool) or value is None: + return value + if isinstance(value, (int, float)): + return repr(value) + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + return value + if isinstance(value, (list, tuple)): + return [_structured(x) for x in value] + return scalar(value) + + +def pvalue(v: Any) -> Any: + """A typed parameter value -> [TYPE, value].""" + kind = type_name(get(v, "type")) + value = get(v, "value") + if kind.startswith("LIST") or kind == "BOOL": + value = _structured(value) + elif isinstance(value, (list, tuple)): + value = [scalar(x) for x in value] + else: + value = scalar(value) + return [kind, value] + + +# A SimpleAction's embedded file gets an implementation-chosen name: v0 adds a +# random 6-character suffix, v1 the fixed suffix "_script". Both are allowed. +_GENERATED_FILENAME = re.compile(r"_(?:[A-Za-z0-9]{6}|script)((?:\.[A-Za-z0-9]+)?)$") + + +def generated_filename(name: Any) -> Any: + if isinstance(name, str): + return _GENERATED_FILENAME.sub(r"_\1", name) + return name + + +def action(a: Any) -> Any: + if a is None or a is MISSING: + return None + timeout = get(a, "timeout") + return { + "command": scalar(get(a, "command")), + "args": ( + [scalar(x) for x in (get(a, "args") or [])] + if get(a, "args") is not MISSING + else MISSING + ), + # v0 holds an int, v1 the template's string; compare the text. + "timeout": None if timeout in (None, MISSING) else str(scalar(timeout)), + } + + +def embedded_files(files: Any) -> Any: + if not files or files is MISSING: + return [] + out = [] + for f in files: + out.append( + { + "name": generated_filename(scalar(get(f, "name"))), + "type": type_name(get(f, "type")), + "filename": generated_filename(scalar(get(f, "filename"))), + "runnable": scalar(get(f, "runnable")), + "data": scalar(get(f, "data")), + } + ) + return out + + +def environment(env: Any) -> Any: + script = get(env, "script") + actions = get(script, "actions") if script not in (None, MISSING) else None + variables = get(env, "variables") + return { + "name": scalar(get(env, "name")), + "variables": ( + {str(k): scalar(v) for k, v in variables.items()} + if isinstance(variables, dict) + else scalar(variables) if variables not in (None, MISSING) else None + ), + "onEnter": action(get(actions, "onEnter")) if actions not in (None, MISSING) else None, + "onExit": action(get(actions, "onExit")) if actions not in (None, MISSING) else None, + "embeddedFiles": ( + embedded_files(get(script, "embeddedFiles")) if script not in (None, MISSING) else [] + ), + } + + +def environments(envs: Any) -> Any: + if not envs or envs is MISSING: + return [] + return [environment(e) for e in envs] + + +def tasks(it: Any) -> Any: + n = len(it) + if n <= TASK_LIMIT: + items = list(it) + return {"count": n, "tasks": [task(t) for t in items]} + first = [task(it[i]) for i in range(TASK_SAMPLE)] + last = [task(it[i]) for i in range(n - TASK_SAMPLE, n)] + return {"count": n, "first": first, "last": last} + + +def task(t: dict) -> Any: + return {str(k): pvalue(v) for k, v in sorted(t.items())} + + +def dependencies(deps: Any) -> Any: + if not deps or deps is MISSING: + return [] + return sorted(str(get(d, "dependsOn")) for d in deps) + + +def step(s: Any, iterator: Callable[[Any], Any]) -> Any: + script = get(s, "script") + actions = get(script, "actions") + space = get(s, "parameterSpace") + return { + "name": scalar(get(s, "name")), + "dependencies": dependencies(get(s, "dependencies")), + "onRun": action(get(actions, "onRun")), + "embeddedFiles": embedded_files(get(script, "embeddedFiles")), + "stepEnvironments": environments(get(s, "stepEnvironments")), + "tasks": tasks(iterator(space)) if space not in (None, MISSING) else None, + } + + +def job(j: Any, iterator: Callable[[Any], Any]) -> Any: + return { + "name": scalar(get(j, "name")), + "parameters": {str(k): pvalue(v) for k, v in sorted((get(j, "parameters") or {}).items())}, + "jobEnvironments": environments(get(j, "jobEnvironments")), + "steps": [step(s, iterator) for s in get(j, "steps")], + } + + +# --------------------------------------------------------------------------- +# The two pipelines. +# --------------------------------------------------------------------------- + + +def _extensions(doc: Any) -> list[str]: + if isinstance(doc, dict) and isinstance(doc.get("extensions"), list): + return [e for e in doc["extensions"] if isinstance(e, str)] + return [] + + +class Impl: + name = "" + + def decode_job(self, doc: Any, extensions: list[str]) -> Any: + raise NotImplementedError + + def decode_env(self, doc: Any, extensions: list[str]) -> Any: + raise NotImplementedError + + def preprocess(self, t: Any, values: dict, envs: list, template_dir: Path) -> Any: + raise NotImplementedError + + def create_job(self, t: Any, values: Any, envs: list) -> Any: + raise NotImplementedError + + def iterator(self, space: Any) -> Any: + raise NotImplementedError + + def run(self, case: Case) -> Outcome: + stage = "decode" + try: + if case.kind == "environment": + env = self.decode_env(case.template, _extensions(case.template)) + return Outcome("ok", {"environment": environment(get(env, "environment"))}) + t = self.decode_job(case.template, _extensions(case.template)) + envs = [self.decode_env(e, _extensions(e)) for e in case.environments] + stage = "preprocess" + values = self.preprocess( + t, + case.parameters if case.parameters is not None else synth_values(case.template), + envs, + case.template_dir, + ) + stage = "create_job" + j = self.create_job(t, values, envs) + stage = "iterate" + projection = job(j, self.iterator) + return Outcome("ok", projection) + except Exception as e: # noqa: BLE001 -- any exception is an outcome + return Outcome(stage, None, str(e), type(e).__name__) + + +class V0(Impl): + name = "v0" + + def decode_job(self, doc, extensions): + return v0.decode_job_template(template=doc, supported_extensions=extensions) + + def decode_env(self, doc, extensions): + return v0.decode_environment_template(template=doc, supported_extensions=extensions) + + def preprocess(self, t, values, envs, template_dir): + return v0.preprocess_job_parameters( + job_template=t, + job_parameter_values=values, + job_template_dir=template_dir, + current_working_dir=template_dir, + environment_templates=envs or None, + ) + + def create_job(self, t, values, envs): + return v0.create_job( + job_template=t, job_parameter_values=values, environment_templates=envs or None + ) + + def iterator(self, space): + return v0.StepParameterSpaceIterator(space=space) + + +class V1(Impl): + name = "v1" + + def decode_job(self, doc, extensions): + return v1.decode_job_template(doc, supported_extensions=extensions) + + def decode_env(self, doc, extensions): + return v1.decode_environment_template(doc, supported_extensions=extensions) + + def preprocess(self, t, values, envs, template_dir): + return v1.preprocess_job_parameters( + job_template=t, + job_parameter_values=values, + job_template_dir=template_dir, + current_working_dir=template_dir, + environment_templates=envs or None, + ) + + def create_job(self, t, values, envs): + return v1.create_job( + job_template=t, job_parameter_values=values, environment_templates=envs or None + ) + + def iterator(self, space): + return v1.job.StepParameterSpaceIterator(space=space) + + +IMPLS = (V0(), V1()) + + +def compare(case: Case) -> Comparison: + return Comparison(case, IMPLS[0].run(case), IMPLS[1].run(case)) + + +# --------------------------------------------------------------------------- +# Job parameter values for templates that need them. +# --------------------------------------------------------------------------- + + +_LIST_VALUES: dict[str, Any] = { + "LIST[STRING]": ["x"], + "LIST[PATH]": ["/tmp/openjd-differential/value"], + "LIST[INT]": [1], + "LIST[FLOAT]": [1.5], + "LIST[BOOL]": [True], + "LIST[LIST[INT]]": [[1]], +} + + +def synth_values(doc: Any) -> dict[str, Any]: + """Pick a value for each job parameter that has no default. + + The value is derived from the template text only, so both implementations + receive exactly the same input. + """ + out: dict[str, Any] = {} + if not isinstance(doc, dict) or not isinstance(doc.get("parameterDefinitions"), list): + return out + for p in doc["parameterDefinitions"]: + if not isinstance(p, dict) or "default" in p or not isinstance(p.get("name"), str): + continue + allowed = p.get("allowedValues") + if isinstance(allowed, list) and allowed: + out[p["name"]] = allowed[0] + continue + kind = p.get("type") + lo = p.get("minValue") + if kind == "INT": + out[p["name"]] = lo if isinstance(lo, int) else 1 + elif kind == "FLOAT": + out[p["name"]] = lo if isinstance(lo, (int, float)) else 1.5 + elif kind == "STRING": + min_length = p.get("minLength") + n = min_length if isinstance(min_length, int) else 1 + out[p["name"]] = "x" * max(n, 1) + elif kind == "PATH": + out[p["name"]] = "/tmp/openjd-differential/value" + elif kind == "BOOL": + out[p["name"]] = True + elif kind == "RANGE_EXPR": + out[p["name"]] = "1-3" + elif isinstance(kind, str) and kind.startswith("LIST["): + out[p["name"]] = _LIST_VALUES.get(kind, []) + return out + + +def to_json(c: Comparison) -> str: + return json.dumps( + {"case": c.case.name, "agree": c.agree, **({} if c.agree else c.summary())}, + default=str, + sort_keys=True, + ) diff --git a/test/openjd/differential/_known.py b/test/openjd/differential/_known.py new file mode 100644 index 00000000..4b53db4f --- /dev/null +++ b/test/openjd/differential/_known.py @@ -0,0 +1,132 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Known v0/v1 differences (``known_differences.yaml``). + +Each class has a title, the side that is believed wrong (``v0``, ``v1``, +``both``, or ``spec`` when the specification does not decide), and matchers. +A matcher has any of: + +* ``kind``: ``stage`` (one side accepts), ``reject-stage`` (both reject, at + different stages), ``value`` or ``task-order`` (same tasks, other order); +* ``case``: an ``fnmatch`` glob on the case name; +* ``stage``: ``">"`` for a stage (accept/reject) difference; +* ``path``: a regular expression on the first differing projection path; +* ``v0`` / ``v1``: a regular expression on the error text, or on the + differing value when that value is a string (a count or a list never + matches, so a changed task count is never hidden by a spelling class); +* ``values``: ``same`` or ``differ``. Both differing values are integer range + texts (``5``, ``1-3,7`` or ``1-9:2``), and they list the same integers, or + not. Any other value never matches; +* ``template``: a regular expression on the case template, written as JSON; +* ``task_param``: a regular expression on the definition, written as JSON, of + the task parameter whose value differs first. + +All keys given in a matcher must match. A disagreement that no class matches +is NEW and fails the differential test: either fix the implementation that is +wrong, or add a class with a reason. +""" + +from __future__ import annotations + +import fnmatch +import json +import re +from pathlib import Path +from typing import Any, Optional + +import yaml + +from ._harness import Comparison + +KNOWN_FILE = Path(__file__).with_name("known_differences.yaml") + + +def load(path: Path = KNOWN_FILE) -> dict[str, dict[str, Any]]: + doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + return {str(k): v for k, v in (doc.get("classes") or {}).items()} + + +def _text(x: Any) -> str: + return x if isinstance(x, str) else json.dumps(x, default=str, sort_keys=True) + + +_RANGE_ITEM = re.compile(r"^\s*(-?[0-9]+)\s*(?:-\s*(-?[0-9]+)\s*(?::\s*(-?[0-9]+)\s*)?)?$") + + +def _range_values(x: Any) -> Optional[frozenset[int]]: + """The integers an integer range text lists, or None when it is not one.""" + if not isinstance(x, str): + return None + out: set[int] = set() + for item in x.split(","): + g = _RANGE_ITEM.match(item) + if g is None: + return None + a = int(g.group(1)) + b = int(g.group(2)) if g.group(2) is not None else a + step = int(g.group(3)) if g.group(3) is not None else 1 + if step == 0 or (b - a) * step < 0 or abs(b - a) // abs(step) > 100_000: + return None + out.update(range(a, b + (1 if step > 0 else -1), step)) + return frozenset(out) + + +_TASK_VALUE_PATH = re.compile( + r"^\$\.steps\[([0-9]+)\]\.tasks\.[a-z]+\[[0-9]+\]\.([A-Za-z_][A-Za-z0-9_]*)\[" +) + + +def _task_param(c: Comparison, path: str) -> Optional[dict[str, Any]]: + """The template's definition of the task parameter that ``path`` names.""" + g = _TASK_VALUE_PATH.match(path) + steps = c.case.template.get("steps") if isinstance(c.case.template, dict) else None + if g is None or not isinstance(steps, list) or int(g.group(1)) >= len(steps): + return None + step = steps[int(g.group(1))] + space = step.get("parameterSpace") if isinstance(step, dict) else None + defs = space.get("taskParameterDefinitions") if isinstance(space, dict) else None + for d in defs if isinstance(defs, list) else []: + if isinstance(d, dict) and d.get("name") == g.group(2): + return d + return None + + +def _matches(m: dict[str, Any], c: Comparison) -> bool: + s = c.summary() + if "kind" in m and s["kind"] != m["kind"]: + return False + if "case" in m and not fnmatch.fnmatch(c.case.name, m["case"]): + return False + if "stage" in m: + if s["kind"] not in ("stage", "reject-stage") or f"{s['v0']}>{s['v1']}" != m["stage"]: + return False + if "path" in m: + if "path" not in s or not re.search(m["path"], s["path"]): + return False + for side in ("v0", "v1"): + if side in m: + got = s.get(f"{side}_error") if "path" not in s else s.get(side) + if got is None or ("path" in s and not isinstance(got, str)): + return False # value patterns match written values (strings) only + if not re.search(m[side], _text(got)): + return False + if "values" in m: + a, b = _range_values(s.get("v0")), _range_values(s.get("v1")) + if "path" not in s or a is None or b is None or (a == b) != (m["values"] == "same"): + return False + if "task_param" in m: + d = _task_param(c, s.get("path", "")) + if d is None or not re.search(m["task_param"], json.dumps(d, default=str, sort_keys=True)): + return False + if "template" in m: + if not re.search(m["template"], json.dumps(c.case.template, default=str, sort_keys=True)): + return False + return True + + +def classify(c: Comparison, known: dict[str, dict[str, Any]]) -> Optional[str]: + for name, cls in known.items(): + if any(_matches(m, c) for m in cls.get("match") or []): + return name + return None diff --git a/test/openjd/differential/known_differences.yaml b/test/openjd/differential/known_differences.yaml new file mode 100644 index 00000000..8147a354 --- /dev/null +++ b/test/openjd/differential/known_differences.yaml @@ -0,0 +1,181 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Known differences between openjd.model (v0, pure Python) and +# openjd.model._v1 (Rust-backed). See _known.py for the matcher format. +# +# wrong: the side the specification or the conformance corpus says is wrong +# (v0, v1, both), or "spec" when the specification does not decide. +# Delete a class when the two sides agree again: the corpus test fails while +# a class matches no case, so a stale entry cannot hide a new difference. +classes: + v0-list-path-defaults: + title: v0 does not join, normalize or walk-up-check LIST[PATH] defaults and values + wrong: v0 + evidence: Template Schemas 2.2 and 2.12; test_known_gaps.py _V0_PATH_GAP + match: + - case: "*/2.12--list-path-*" + + v0-path-not-normalized: + title: v0 joins a relative PATH value to the directory but keeps "..", "." segments + wrong: v0 + evidence: conformance base/jobs/2.2--path-value-relative-joined-with-cwd expects os.path.join(cwd, "other") + match: + - case: "*/base/jobs/2.2--path-value-*" + + v0-number-white-space: + title: v0 keeps white space around a submitted INT or FLOAT value + wrong: v0 + evidence: conformance base/jobs/2.3--int-parameter-value-white-space expects SUBMITTED=[7] + match: + - case: "*white-space*" + + v0-list-string-items: + title: v0 refuses numeric strings as LIST[INT], LIST[FLOAT] or LIST[LIST[INT]] items and bounds + wrong: v0 + evidence: conformance EXPR 2.13, 2.14, 2.16 *-string-items and expr1.3.12 expect success + match: + - case: "*string-item*" + - case: "*/expr1.3.12--float-range-expression-keeps-spelling.test.yaml" + + v0-expr-range-list-elements: + title: v0 does not flatten list elements or drop null elements of an expression range list + wrong: v0 + evidence: Expression Language 1.3.2; conformance expr1.3.2--*-range-list-element-* + match: + - case: "*/expr1.3.2--*range-list-*" + + v0-raw-value-error: + title: v0 raises a bare ValueError ("invalid literal for int()") while iterating a resolved range + wrong: v0 + evidence: not a model error type; v1 reports the element at create_job + match: + - stage: "iterate>create_job" + - stage: "iterate>ok" + + v1-earlier-expression-errors: + title: v1 rejects at create_job a resolved range or expression that v0 accepts until run time + wrong: v0 + evidence: each case is a conformance .invalid.test; v0 fails only when the task runs + match: + - stage: "ok>create_job" + case: "*.invalid.test.yaml" + + range-order: + title: a descending or negative-step range; v0 keeps written order, v1 increasing order + wrong: v0 + evidence: >- + Template Schemas 3.4.1: "combined to form a list of values in increasing order". + The conformance file base/jobs/3.4.1--descending-range-negative-step lists 10..1, + but the runner checks containment only, so order is not tested. + match: + - kind: task-order + + float-integer-spelling: + title: a FLOAT written as an integer; v0 keeps "2", v1 writes "2.0" + wrong: spec + match: + - v0: "^-?[0-9]+$" + v1: "^-?[0-9]+\\.0$" + + float-exponent-spelling: + title: a FLOAT with an exponent; v0 writes "5E+300", v1 "5e300" + wrong: spec + match: + - v0: "E\\+" + + # The next 2 classes come before range-expr-spelling: its patterns match any + # two range texts, plain integers too, and the first class that matches wins. + noncontiguous-chunk-split: + title: a NONCONTIGUOUS CHUNK[INT]; v0 and v1 give the leftover values to other chunks (10 values at 3 - v0 3,2,3,2, v1 3,3,2,2) + wrong: spec + evidence: Template Schemas 3.4.1.5 sets the chunk size and form but not which chunks take the leftover values + match: + - kind: value + task_param: '"rangeConstraint": "NONCONTIGUOUS"' + values: differ + + int-2^63: + title: an INT value of 2^63; v0 keeps 9223372036854775808, v1 clamps it to 9223372036854775807 + wrong: both + evidence: Expression Language 1.2.1 types int as a 64-bit signed integer (-2^63 to 2^63-1), so both sides should refuse 2^63 + match: + - v0: "^9223372036854775808$" + v1: "^9223372036854775807$" + # with maxValue 2^63-1: v0 refuses the default, v1 clamps it and goes on + - stage: "decode>ok" + template: "(?create_job" + template: "(?$" + + v1-merged-default-constraint: + title: v1 accepts a merged LIST default that breaks the merged maxLength + wrong: v1 + evidence: conformance EXPR/jobs/2.13--list-int-merged-default-violates-constraint.invalid + match: + - case: "*merged-default-violates-constraint*" + + v1-binding-lag-uri-path: + title: the published crate the bindings pin refuses URI PATH values (openjd-rs main accepts them) + wrong: v1 + evidence: conformance EXPR/jobs/expr2.3.* expect success; openjd-rs main CLI passes them + match: + - case: "*/expr2.3.*uri-*" + + v1-binding-lag-command-length: + title: the published crate the bindings pin caps an action command at 1024 characters + wrong: v1 + evidence: conformance EXPR/jobs/5.1--command-4096-characters expects success; openjd-rs main CLI passes it + match: + - case: "*/5.1--command-4096-characters.test.yaml" + + negative-zero: + title: a FLOAT -0; v0 keeps "-0.0", v1 writes "0.0" + wrong: spec + match: + - v0: "^-0(\\.0)?$" + v1: "^0(\\.0)?$" + + v0-python-int-literals: + title: v0 accepts INT spellings "1_000" and "42.0"; v1 refuses them + wrong: v0 + evidence: Template Schemas 2.3 defines an integer string; int("1_000") is a Python literal rule + match: + - stage: "ok>decode" + v1: "Cannot parse '([0-9]+(_[0-9]+)+|-?[0-9]+\\.0+)' as integer" + - stage: "create_job>decode" + v1: "Cannot parse '([0-9]+(_[0-9]+)+|-?[0-9]+\\.0+)' as integer" + - stage: "preprocess>decode" + v1: "Cannot parse '([0-9]+(_[0-9]+)+|-?[0-9]+\\.0+)' as integer" + + v0-path-default-walk-up: + title: v0 accepts a PATH default that walks up out of the template directory ("..") + wrong: v0 + evidence: Template Schemas 2.2 (default paths are joined to the template directory; no walk-up) + match: + - v1: "The default value of PATH parameter .* references a path outside of the template directory" + + v1-binding-lag-utf8-length: + title: the published crate the bindings pin counts STRING minLength/maxLength in UTF-8 bytes + wrong: v1 + evidence: Template Schemas 2.1 counts characters; "😀" with maxLength 1 is refused as length 4 + match: + - v1: "^Parameter '[^']+': value length [0-9]+ exceeds maximum [0-9]+" + diff --git a/test/openjd/differential/test_differential.py b/test/openjd/differential/test_differential.py new file mode 100644 index 00000000..c11aa8e7 --- /dev/null +++ b/test/openjd/differential/test_differential.py @@ -0,0 +1,133 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""v0-vs-v1 differential tests. + +* Every template of the specification corpus and of a fixed-seed generated + set runs through both implementations; a difference that is not a known + class (known_differences.yaml) fails. +* A known class that no longer occurs fails too, so the file shrinks as the + implementations converge. +* A planted change in v1 is caught (the differential guards itself). + +The corpus tests need an openjd-specifications checkout +(``OPENJD_SPECIFICATIONS_DIR`` or a sibling directory) and are skipped +without one. The Hypothesis test is opt-in (``-m fuzz``). +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +import openjd.model._v1 as v1 + +from . import _corpus, _generate, _harness, _known + +GENERATED_SEED = 1 +GENERATED_COUNT = 1500 + +KNOWN = _known.load() +_SPEC_DIR = _corpus.specifications_dir() +SPEC = _SPEC_DIR if _SPEC_DIR is not None else Path("openjd-specifications") +needs_spec = pytest.mark.skipif(_SPEC_DIR is None, reason="no openjd-specifications checkout") + + +def _new(cases) -> tuple[list[_harness.Comparison], set[str]]: + new, seen = [], set() + for case in cases: + c = _harness.compare(case) + if c.agree: + continue + cls = _known.classify(c, KNOWN) + if cls is None: + new.append(c) + else: + seen.add(cls) + return new, seen + + +def _report(new: list[_harness.Comparison]) -> str: + return "\n".join(_harness.to_json(c) for c in new[:20]) + + +@needs_spec +def test_corpus_has_no_new_differences() -> None: + new, _ = _new(_corpus.spec_cases(SPEC)) + assert not new, f"{len(new)} new v0/v1 difference(s):\n{_report(new)}" + + +def test_generated_set_has_no_new_differences() -> None: + new, _ = _new(_generate.cases(GENERATED_COUNT, GENERATED_SEED)) + assert not new, f"{len(new)} new v0/v1 difference(s):\n{_report(new)}" + + +@needs_spec +def test_every_known_class_still_occurs() -> None: + cases = list(_corpus.spec_cases(SPEC)) + list(_generate.cases(GENERATED_COUNT, GENERATED_SEED)) + _, seen = _new(cases) + stale = sorted(set(KNOWN) - seen) + assert not stale, f"known classes that no case shows any more (delete them): {stale}" + + +@pytest.mark.fuzz +@settings(max_examples=300, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(st.integers(min_value=0, max_value=2**32 - 1)) +def test_generated_seed_has_no_new_differences(seed: int) -> None: + new, _ = _new(_generate.cases(1, seed)) + assert not new, f"replay: run_differential.py --generated 1 --seed {seed}\n{_report(new)}" + + +@needs_spec +def test_a_planted_change_in_v1_is_caught(monkeypatch: pytest.MonkeyPatch) -> None: + """Drop the last task of every step on the v1 side: the differential must + report it as a NEW difference, not as a known class.""" + + real = _harness.V1.iterator + + class DropLast: + def __init__(self, it): + self._items = list(it)[:-1] + + def __len__(self): + return len(self._items) + + def __iter__(self): + return iter(self._items) + + def __getitem__(self, i): + return self._items[i] + + monkeypatch.setattr(_harness.V1, "iterator", lambda self, space: DropLast(real(self, space))) + sample = [ + c + for c in _corpus.spec_cases(SPEC) + if "/base/jobs/" in c.name and "parameterSpace" in str(c.template) + ][:40] + new, _ = _new(sample) + assert new, "the planted change went unnoticed" + assert all(c.summary()["path"].endswith(".tasks.count") for c in new) + + +@pytest.mark.xfail( + strict=True, reason="v1 refuses an empty Python list for a LIST parameter; v0 accepts it" +) +def test_v1_accepts_an_empty_list_value() -> None: + doc = { + "specificationVersion": "jobtemplate-2023-09", + "extensions": ["EXPR"], + "name": "J", + "parameterDefinitions": [{"name": "L", "type": "LIST[STRING]"}], + "steps": [{"name": "S", "script": {"actions": {"onRun": {"command": "echo"}}}}], + } + t = v1.decode_job_template(doc, supported_extensions=["EXPR"]) + values = v1.preprocess_job_parameters( + job_template=t, + job_parameter_values={"L": []}, + job_template_dir=Path("/tmp"), + current_working_dir=Path("/tmp"), + ) + assert str(values["L"].value) == "[]"