diff --git a/dokimi/changelog.d/20261201_120000_vlad-perevezentsev_runs-export-import.md b/dokimi/changelog.d/20261201_120000_vlad-perevezentsev_runs-export-import.md new file mode 100644 index 000000000..b1bcb6820 --- /dev/null +++ b/dokimi/changelog.d/20261201_120000_vlad-perevezentsev_runs-export-import.md @@ -0,0 +1,16 @@ +### Added + +- **`runs export` and `runs import`: a run directory moves to another machine + as one checked bundle** (#94 §2.3, R3), so a baseline outlives the CI runner + that made it. `runs export RUN|baseline:NAME > bundle.tgz` writes `run.json`, + the plan, the result and the run's artifacts as a gzipped tar led by + `bundle.json` (new schema `run_bundle.v1`), addressed by the plan's + `plan_digest` and the result's sha256, which `bundle.json` gives the same + on every machine. `runs import bundle.tgz` writes nothing until every member is a + regular file at a path `bundle.json` lists with its sha256, under a 256 MiB + cap, and the run passes its schemas and its plan digest; links, devices, + FIFOs, absolute and `..` paths are refused. The run goes to + `//`; the same run already there is a no-op, and + another run with its `run_id` exits 2. `--as NAME` points a baseline at it, + with `--expect-previous` as in `runs baseline save` (exit 4 when it moved). + See `docs/runs.md`. diff --git a/dokimi/docs/reference/cli-interface.json b/dokimi/docs/reference/cli-interface.json index cfa22e21f..86a04dec4 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -1776,6 +1776,16 @@ } } }, + "export": { + "allow_abbrev": true, + "params": [ + {"key": "run", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "argument", "nargs": null, "position": 0, "required": true, "type": null}, + {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null} + ], + "path": "dokimi runs export", + "subcommand_required": null, + "subcommands": {} + }, "gc": { "allow_abbrev": true, "params": [ @@ -1789,6 +1799,19 @@ "subcommand_required": null, "subcommands": {} }, + "import": { + "allow_abbrev": true, + "params": [ + {"key": "bundle", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "argument", "nargs": null, "position": 0, "required": true, "type": null}, + {"key": "--as", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, + {"key": "--expect-previous", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, + {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--json", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null} + ], + "path": "dokimi runs import", + "subcommand_required": null, + "subcommands": {} + }, "list": { "allow_abbrev": true, "params": [ diff --git a/dokimi/docs/run-directories.md b/dokimi/docs/run-directories.md index 4f45553f8..563a1821e 100644 --- a/dokimi/docs/run-directories.md +++ b/dokimi/docs/run-directories.md @@ -15,7 +15,8 @@ it still holds a result when the run is stopped part way: a signal, Ctrl-C or the spend cap ([#94](https://github.com/intel/dokimi/issues/94) §2.3, stage R2). The module that writes it is `dokimi/runs/rundir.py`. `subjects run` writes one (see below); the other command families move to it one by one in later -PRs, each with its `--out-dir` and a run name. +PRs, each with its `--out-dir` and a run name. `runs export` and +`runs import` move one to another machine ([runs.md](runs.md#moving-a-run-runs-export-and-runs-import)). ## Layout diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index effc910f1..93712f483 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -2,13 +2,15 @@ depends_on: - dokimi/dokimi/runs/** - dokimi/dokimi/commands/runs.py + - dokimi/dokimi/commands/runs_bundle.py + - dokimi/dokimi/schemas/run_bundle.v1.json --- -# The runs root: `runs list`, `runs show`, `runs rm`, `runs gc` and `runs baseline` +# The runs root: `runs list`, `runs show`, `runs rm`, `runs gc`, `runs baseline`, `runs export` and `runs import` Catalog static receipts (`catalog_eval.v1`) are supported too: the subject is the catalog root, and `runs show` counts skill rows and problems. Point `DOKIMI_RUNS_DIR` @@ -23,8 +25,9 @@ Most commands that run an evaluation write their artifacts under `results/` by default (a few write elsewhere, listed below). `runs list` shows what is there, one run's artifacts together, and `runs show` opens one artifact or one run. Both only read files: no model call, no network access, nothing written. `runs rm` and `runs gc` remove runs from the root -([below](#removing-runs-runs-rm-and-runs-gc)), and `runs baseline` names a run -([baselines](#baselines-runs-baseline-save-list-rm)). +([below](#removing-runs-runs-rm-and-runs-gc)), `runs baseline` names a run +([baselines](#baselines-runs-baseline-save-list-rm)), and `runs export` and `runs import` +move a run directory to another machine ([moving a run](#moving-a-run-runs-export-and-runs-import)). The runs root is `results/` in the working directory. Set `DOKIMI_RUNS_DIR` to read another directory. @@ -305,6 +308,96 @@ saved baseline skill/a@main -> 20261029T140211Z-3f9a0c1e (1 artifact); before: 2 store: `runs baseline` does not read or change them. `runs gc --keep-baselines` keeps the runs of both. +## Moving a run: `runs export` and `runs import` + +A baseline under `results/` goes with the CI runner that made it. `runs export` writes one +[run directory](run-directories.md) as a file, and `runs import` puts it under the runs root of +another machine, checked first ([#94](https://github.com/intel/dokimi/issues/94) §2.3): a cache +or an artifact store a pull request can write to may hand back a poisoned bundle, so import +trusts none of it. + +```text +$ python cli.py runs export baseline:main > baseline.tgz +exported run 20261123T101500Z-1a2b3c4d from nightly-7/: 4 files, 6,954 bytes; plan sha256:6bbd76a2642039efd7b9d8fee6ffe85ec785ee3ec0985f4fc0fcd56c521f2348, result sha256:fc5d04c63d4d8e3d674992d325a34a271c48cf68ffa6d08c9dedfa6d24e9062f +$ python cli.py runs import baseline.tgz --as main # on the next runner +imported run 20261123T101500Z-1a2b3c4d into results/nightly-7/: 4 files, 6,954 bytes; plan sha256:6bbd76a2642039efd7b9d8fee6ffe85ec785ee3ec0985f4fc0fcd56c521f2348, result sha256:fc5d04c63d4d8e3d674992d325a34a271c48cf68ffa6d08c9dedfa6d24e9062f +saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none +``` + +- **`runs export RUN|baseline:NAME`** writes the bundle of one run to stdout, and what it holds + to stderr. `RUN` is a `run_id` whose artifacts include a `run.json`; `baseline:NAME` is the + run a [baseline](#baselines-runs-baseline-save-list-rm) points to. The bundle holds `run.json` + and every artifact it lists: the plan, the result and the run's own artifacts. An artifact + that carries the `run_id` but that `run.json` does not list (saved outside the directory) is + left out and named (`left out: 1 artifact ...`), and so is any other file in the run directory + that `run.json` does not list, such as a report (`left out: 1 file in the run directory ...`). + It refuses, and writes nothing to stdout, a + run with no `run.json`, more than one, a run without exactly one plan and one result (the + bundle is addressed by them), a listed file that is missing, is not a regular file or leads out + of the run directory, anything an import would refuse (below), a `bundle.json` past its + schema's caps (1000 files, a path of 1024 characters) or over the 1 MiB an import reads, and + a stdout that is a terminal. +- **The bundle** is a gzipped tar: `bundle.json` first (`run_bundle.v1`, + `dokimi/schemas/run_bundle.v1.json`), then the run's files under `run/`. `bundle.json` names + the run (`run_id`, `name`), its address, which is the plan's `plan_digest` and the sha256 of + `result.v1.json` (`result_sha256`), and the sha256 and size of every file. It holds no time, + owner or mode, so the tar of a run is the same each time. The `.tgz` is the same bytes + where the same zlib compresses it; another build (zlib-ng in CPython's Windows builds) may + compress it to other bytes. What stays the same on every machine is `bundle.json`: the + address and each file's sha256. +- **`runs import BUNDLE`** reads the bundle into memory and checks all of it before it writes + anything: + + - the members: only regular files, `bundle.json` first, then exactly the files it lists, each + with its sha256 and size. A symlink, a hard link, a directory, a FIFO or a device member, an + absolute path, a `..` segment, a `\`, `:` or another character Windows refuses in a name + (`<>"|?*`), a Windows device name (`CON`, `nul.json`, `CONIN$`, `COM¹`), a segment that ends in `.` or a space, two + paths that differ only in case (one file on Windows and macOS) or in Unicode normalization + (one file on macOS), two spellings of one directory (`Sub/a.json` beside `sub/b.json`), and + a path under another listed path are refused; + - the size: the files together are at most 256 MiB once unpacked, and reading stops there, so + a small file that unpacks to much more is refused, not read; + - the run: `run.json` is a valid `run.v1` with a `run_id`, a name (or `run_id`) that can name + its directory on every platform (no `con`, nothing that ends in `.`), and lists exactly the bundle's + files; each is a valid artifact of the kind it is listed as and carries the run's `run_id` + (an input kind carries none), and is one `runs list` finds (a name that ends in `.json`, + JSON that opens with its `schema_version`, as dokimi writes it), so the run can be exported + again; the result's `plan_digest` is the digest of the plan beside it; + and `bundle.json`'s run and address are the run's. + +- **Where it goes**: `/`, or `/` for a run with no name, + as [a run's own directory](run-directories.md#layout) is named. The run is written to a + directory beside it, then renamed into place, so a reader sees all of it or none. From the + look for its `run_id` to the rename it holds `.baselines/.lock` (made when missing), so of two + imports of one run at once the second finds the first's run. `results/` + is made when it is missing (a fresh runner; also when another import makes it meanwhile); a `DOKIMI_RUNS_DIR` that does not exist is + refused. When the run is there already with the same files, nothing is written and the exit + code is 0 (`nothing written`). An import never replaces a run: another run with the bundle's + `run_id` under the root (a file that differs, or one in another place) or a directory of that + name that holds anything exits 2 and leaves them as they are. An import killed part way can + leave the directory it was writing, `...import` beside the run's place; remove it. + No `runs` command reads such a directory, so a run is listed and exported only once it is whole. +- **`--as NAME`** then points the baseline `NAME` at the run, as `runs baseline save NAME RUN` + does, also after an import that wrote nothing. **`--expect-previous RUN_ID`** (with `--as` + only) makes that a compare-and-swap: when `NAME` does not point to `RUN_ID` it exits 4 + (`invalid`, `stale_baseline`, with `expected` and `found` under `data`), the pointer is left as + it was, and the run stays imported. A bad `--as` name, one that differs from a saved baseline + only in case, a `.baselines/` that is a link or cannot be locked, and an `--expect-previous` + that is not a run id or comes without `--as` exit 2 before anything is written. Once the run + is written, a save the store refuses (a baseline whose name differs only in case, saved + meanwhile, or a `.baselines/` that can no longer be locked) exits 2, and a pointer that cannot + be written (a full disk) exits 5; both say the run is imported (`run ... is imported, but ...`). +- `--json` prints one `cli_output.v1` document (`kind` `runs import`) with `root`, `run_id`, + `path` (the run's directory, relative to the root), `written`, `files`, `size_bytes`, + `plan_digest`, `result_sha256` and `baseline` (`name` and `previous`, `null` without `--as`) + under `data`. + +The bundle proves that its files are the ones the export read, and that they make one valid +run; it does not prove who exported it. The address an import prints covers only the plan and +the result: a bundle whose `run.json` or other artifacts were edited and `bundle.json` re-signed +prints the same one. A workflow that needs to know who exported it keeps the bundle where a +pull request cannot write. + ## Exit codes | Case | Exit | @@ -322,10 +415,15 @@ saved baseline skill/a@main -> 20261029T140211Z-3f9a0c1e (1 artifact); before: 2 | `runs baseline save`, `rm`: no root, a name that is not one or differs from a saved one only in case, a `RUN` or `--expect-previous` that is not a run id, a `RUN` no artifact carries, `rm` of a baseline that does not exist, a `.baselines/` that cannot be locked or listed (a file, no permission) or is a link; `runs baseline list`: a `DOKIMI_RUNS_DIR` that does not exist, or a `.baselines/` that cannot be listed or locked (a file, a `.lock` it may not open or that is a link) or is a link | 2 | | `runs baseline save --expect-previous RUN_ID`: the baseline does not point to `RUN_ID` (the pointer is left as it was) | 4 | | `runs baseline save`, `rm`: the pointer could not be written or removed | 5 | +| `runs export`: exported; `runs import`: imported, or the run is there already with the same files | 0 | +| `runs export`: no root, a `RUN` that is not a run id or has no run directory (or more than one), a missing baseline, a run without one plan and one result, a listed file that is missing, not a regular file or leads out of the run directory, a run an import would refuse, or a stdout that is a terminal | 2 | +| `runs import`: a file that cannot be read, is not a regular file (a FIFO) or is not a gzipped tar, a member or a run that fails a check (above), a bundle over the size cap, another run with its `run_id` or a directory of its name that holds anything, a `.baselines/` that cannot be locked, a `DOKIMI_RUNS_DIR` that does not exist, a bad `--as` or `--expect-previous`, or `--expect-previous` without `--as` | 2 | +| `runs import --as NAME --expect-previous RUN_ID`: the baseline does not point to `RUN_ID` (the run is imported, the pointer left as it was) | 4 | +| `runs import`: the run or the pointer could not be written | 5 | On a file system that does not lock (`flock` fails with `ENOLCK`, as on an NFS mount with no lock daemon), every command that takes `.baselines/.lock` exits 2 -(`cannot lock: No locks available`): `save` and `rm`, and while a `.baselines/` +(`cannot lock: No locks available`): `save` and `rm`, `runs import`, and while a `.baselines/` is there, `list` and `runs gc --keep-baselines`, `--dry-run` too. `list` refuses rather than read without the lock, since a read it does not hold the lock for is the one a save on Windows fails on; with no `.baselines/` there is nothing to diff --git a/dokimi/dokimi/cli_flags.py b/dokimi/dokimi/cli_flags.py index df111b544..6e644a641 100644 --- a/dokimi/dokimi/cli_flags.py +++ b/dokimi/dokimi/cli_flags.py @@ -154,6 +154,7 @@ class Concept: Flag("--baseline-arm", "NAME", "text"), Flag("--expect-previous", "RUN_ID", "text", meaning="save a baseline only while it points to this run (compare-and-swap)"), + Flag("--as", "NAME", "text", meaning="the baseline to point at the run runs import writes"), ), banned=("--baseline-json", "--plugin-json", "--base"), ), diff --git a/dokimi/dokimi/cli_routes.py b/dokimi/dokimi/cli_routes.py index b7d00249e..e1ee2c976 100644 --- a/dokimi/dokimi/cli_routes.py +++ b/dokimi/dokimi/cli_routes.py @@ -201,6 +201,8 @@ class Tombstone: Leaf(("runs", "show"), FREE), Leaf(("runs", "rm"), FREE), Leaf(("runs", "gc"), FREE), + Leaf(("runs", "export"), FREE), + Leaf(("runs", "import"), FREE), Leaf(("runs", "baseline", "save"), FREE), Leaf(("runs", "baseline", "list"), FREE), Leaf(("runs", "baseline", "rm"), FREE), diff --git a/dokimi/dokimi/commands/runs.py b/dokimi/dokimi/commands/runs.py index 6b18836d2..5b7628cb2 100644 --- a/dokimi/dokimi/commands/runs.py +++ b/dokimi/dokimi/commands/runs.py @@ -16,7 +16,7 @@ from pathlib import Path from dokimi import cli_flags -from dokimi.commands import runs_baseline +from dokimi.commands import runs_baseline, runs_bundle from dokimi.artifacts import INPUT_KINDS, SCHEMA_VERSIONS from dokimi.exit_codes import EXIT_INFRA from dokimi.runs import baseline @@ -478,4 +478,5 @@ def register(sub: argparse._SubParsersAction, positive_int) -> None: help="Print cli_output.v1 on stdout (the runs removed and kept under data)") gc_p.set_defaults(func=cmd_runs_gc, emits_cli_output=True, cli_kind="runs gc") + runs_bundle.register(runs_sub) runs_baseline.register(runs_sub) diff --git a/dokimi/dokimi/commands/runs_bundle.py b/dokimi/dokimi/commands/runs_bundle.py new file mode 100644 index 000000000..8f33a2683 --- /dev/null +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -0,0 +1,182 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""runs export | import: move a run directory between machines as one verified bundle (#94 §2.3, +R3), and point a baseline at the run it brings. Never spends.""" + +from __future__ import annotations + +import argparse +import io +import sys +from pathlib import Path +from typing import Any, NoReturn + +from dokimi import cli_flags +from dokimi.artifacts import is_run_id +from dokimi.exit_codes import EXIT_INFRA, EXIT_INVALID, EXIT_USAGE +from dokimi.runs import baseline, bundle +from dokimi.runs.scan import existing_root, plain, runs_root +from dokimi.utils import InputError + + +def _count(n: int, noun: str) -> str: + return f"{n} {noun}" if n == 1 else f"{n} {noun}s" + + +def cmd_runs_export(args: argparse.Namespace) -> None: + """Write the bundle of one run directory to stdout; what it holds goes to stderr.""" + root = existing_root().path + if sys.stdout.isatty(): # as `docker save`: a terminal is no place for a gzipped tar + raise InputError("runs export writes the bundle to stdout, which is a terminal here: redirect it " + "(runs export RUN > bundle.tgz)") + found = bundle.collect(root, bundle.resolve(root, args.run)) + data = io.BytesIO() # all of it first: a refusal never leaves half a bundle on stdout + bundle.write(found.bundle, data) + sys.stdout.buffer.write(data.getvalue()) + sys.stdout.buffer.flush() + b = found.bundle + print(f"exported run {b.run_id} from {plain(found.directory.as_posix())}/: " + f"{_count(len(b.files), 'file')}, {b.size_bytes:,} bytes; plan {b.plan_digest}, " + f"result sha256:{b.result_sha256}", file=sys.stderr) + if found.left_out: + print(f"left out: {_count(len(found.left_out), 'artifact')} with this run_id that {bundle.RUN_FILE} " + f"does not list (first: {plain(found.left_out[0].as_posix())})", file=sys.stderr) + if found.unlisted: + print(f"left out: {_count(len(found.unlisted), 'file')} in the run directory that {bundle.RUN_FILE} " + f"does not list (first: {plain(found.unlisted[0].as_posix())})", file=sys.stderr) + + +def _import_root(args: argparse.Namespace) -> Path: + """The runs root, made when it is the default ``results/`` and missing (a fresh CI runner); a + ``DOKIMI_RUNS_DIR`` that does not exist is refused, as every ``runs`` command refuses it.""" + root = runs_root() + if not root.exists(): + try: + root.path.mkdir(exist_ok=True) # another import may make it since exists(); a file there still fails + except OSError as exc: # exit 5, as a run that cannot be written: one line, no traceback + where = root.path.as_posix() + _infra(args, {"root": where}, f"runs root {plain(where)}: cannot make it: {exc.strerror or exc}") + return root.path + + +def _check_baseline_flags(args: argparse.Namespace) -> None: + """Refuse a bad ``--as`` or ``--expect-previous`` before anything is written.""" + if args.as_name is None: + if args.expect_previous is not None: + raise InputError("--expect-previous needs --as NAME: it is the compare-and-swap of that pointer") + return + baseline.check_name(args.as_name) + if args.expect_previous is not None and not is_run_id(args.expect_previous): + raise InputError(f"--expect-previous {plain(args.expect_previous)!r} is not a run id") + + +def _check_store(args: argparse.Namespace) -> None: + """``--as``: refuse before the run is written what ``baseline.save`` refuses by the store: a name + that differs from a saved one only in case, a ``.baselines/`` that is a link or cannot be locked.""" + root = runs_root() + if args.as_name is None or not root.exists(): # no root yet: no store either + return + folded = args.as_name.casefold() + other = next((p.name for p in baseline.listed(root.path).pointers + if p.name != args.as_name and p.name.casefold() == folded), None) + if other is not None: + raise InputError(f"baseline {args.as_name} differs from baseline {plain(other)} only in case, " + "which Windows and macOS read as one name") + + +def _fail(args: argparse.Namespace, data: dict, message: str, code: int, **status: object) -> NoReturn: + from dokimi import cli_output + if args.json: + cli_output.emit_leaf("runs import", data, status="failed", **status) + else: + print(f"Error: {message}", file=sys.stderr) + sys.exit(code) + + +def _infra(args: argparse.Namespace, data: dict, message: str) -> NoReturn: + """A run or a pointer that could not be written: exit 5, as ``runs baseline save`` exits (#94 §2.6).""" + from dokimi import cli_output + _fail(args, data, message, EXIT_INFRA, reason="infra", error=cli_output.error_object("infra", message)) + + +def _point(args: argparse.Namespace, root: Path, run_id: str, data: dict) -> baseline.Saved | None: + """``--as``: point the baseline at the run, a compare-and-swap with ``--expect-previous``.""" + from dokimi import cli_output + if args.as_name is None: + return None + try: + return baseline.save(root, args.as_name, run_id, args.expect_previous) + except baseline.Conflict as conflict: # exit 4, a stale baseline, as `runs baseline save` (§2.6) + _fail(args, {**data, "expected": conflict.expected, "found": conflict.found}, + f"run {run_id} is imported, but {conflict}", EXIT_INVALID, verdict="invalid", reason="stale_baseline") + except InputError as exc: # a store that changed since _check_store, or cannot be locked for a write + message = f"run {run_id} is imported, but {exc}" + _fail(args, data, message, EXIT_USAGE, reason=message, error=cli_output.error_object("input", message)) + except OSError as exc: + _infra(args, data, f"run {run_id} is imported, but baseline {args.as_name}: cannot write: " + f"{exc.strerror or exc}") + + +def cmd_runs_import(args: argparse.Namespace) -> None: + """Check a bundle, write its run under the runs root (nothing when it is there, identical), and + with ``--as`` point a baseline at it.""" + _check_baseline_flags(args) + found = bundle.read(Path(args.bundle)) # before the root is made: a refused bundle writes nothing + _check_store(args) + root = _import_root(args) + data: dict[str, Any] = { + "root": root.as_posix(), "run_id": found.run_id, "path": None, "written": False, + "files": sorted(found.files), "size_bytes": found.size_bytes, + "plan_digest": found.plan_digest, "result_sha256": found.result_sha256, "baseline": None} + try: + installed = bundle.install(root, found) + except OSError as exc: + _infra(args, data, f"run {found.run_id}: cannot write: {exc.strerror or exc}") + data.update(path=installed.path.as_posix(), written=installed.written) + saved = _point(args, root, found.run_id, data) + if saved is not None: + data["baseline"] = {"name": saved.name, "previous": saved.previous} + _print_import(args, data, saved) + + +def _print_import(args: argparse.Namespace, data: dict, saved: baseline.Saved | None) -> None: + from dokimi import cli_output + if args.json: + cli_output.emit_leaf("runs import", data, summary={"written": data["written"]}) + return + where = plain(f"{data['root'].rstrip('/')}/{data['path']}/") + if data["written"]: + print(f"imported run {data['run_id']} into {where}: {_count(len(data['files']), 'file')}, " + f"{data['size_bytes']:,} bytes; plan {data['plan_digest']}, result sha256:{data['result_sha256']}") + else: + print(f"run {data['run_id']} is already in {where}, as the bundle holds it: nothing written") + if saved is not None: + before = "none" if saved.previous is None else plain(saved.previous) or "(empty)" + print(f"saved baseline {saved.name} -> {saved.run_id}; before: {before}") + + +def register(runs_sub: argparse._SubParsersAction) -> None: + export_p = runs_sub.add_parser( + "export", + help="Write one run directory (run.json, its plan, result and artifacts) to stdout as a bundle, " + "a gzipped tar that runs import checks: runs export RUN > bundle.tgz. Reads only.") + export_p.add_argument("run", metavar="RUN|baseline:NAME", + help="A run_id from runs list whose artifacts include a run.json, or " + "baseline:NAME for the run a baseline points to") + export_p.set_defaults(func=cmd_runs_export, cli_kind="runs export") + + import_p = runs_sub.add_parser( + "import", + help="Check a bundle from runs export (each file's sha256, each artifact's schema, the plan " + "digest) and write its run under the runs root; nothing is written when a check fails, " + "and nothing when that run is there already, identical") + import_p.add_argument("bundle", metavar="BUNDLE", help="The .tgz runs export wrote") + cli_flags.add(import_p, "baseline", "--as", metavar="NAME", dest="as_name", + help="Point the baseline NAME at the imported run, as runs baseline save does") + cli_flags.add(import_p, "baseline", "--expect-previous", metavar="RUN_ID", + help="With --as: point it only while NAME points to RUN_ID (exit 4 otherwise, the " + "pointer left as it was and the run imported)") + cli_flags.add(import_p, "output", "--json", action="store_true", + help="Print cli_output.v1 on stdout (the run, its files and the baseline under data)") + import_p.set_defaults(func=cmd_runs_import, emits_cli_output=True, cli_kind="runs import") diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py new file mode 100644 index 000000000..f462bb73e --- /dev/null +++ b/dokimi/dokimi/runs/bundle.py @@ -0,0 +1,532 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""A run directory as one file: ``runs export`` writes it, ``runs import`` checks it and unpacks +it under the runs root (#94 §2.3, R3), so a baseline survives an ephemeral CI runner. + +A bundle is a gzipped tar of ``bundle.json`` (``run_bundle.v1``), then the run's files under +``run/``: ``run.json`` and every artifact it lists. ``bundle.json`` names the run, its address +(the plan's ``plan_digest`` and the sha256 of ``result.v1.json``) and the sha256 and size of each +file. Import trusts none of it: it reads only regular members at the paths ``bundle.json`` lists, +up to :data:`MAX_BYTES`, checks each hash, each artifact's schema and the plan digest, and writes +nothing until all of it holds. Layout and rules: ``docs/runs.md``. Nothing here prints or exits. +""" + +from __future__ import annotations + +import gzip +import hashlib +import io +import json +import os +import re +import secrets +import shutil +import stat +import tarfile +import unicodedata +import zlib +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from pathlib import Path +from typing import IO, Any, cast + +from dokimi.artifacts import ( + INPUT_KINDS, + SCHEMA_VERSIONS, + ArtifactValidationError, + is_run_id, + schema_errors, + validate_artifact, +) +from dokimi.runner.plan import plan_digest +from dokimi.runs import baseline +from dokimi.runs.rundir import RUN_FILE +from dokimi.runs.scan import artifact_version, inside, is_link, plain, read_error_reason, scan +from dokimi.utils import InputError + +MANIFEST = "bundle.json" +SCHEMA = "run_bundle.v1" +PREFIX = "run/" # the run's files, so no artifact name can clash with bundle.json +#: The run's files together, uncompressed: what an import reads into memory at most. +MAX_BYTES = 256 * 1024 * 1024 +_MAX_MANIFEST = 1024 * 1024 +_SLACK = 8 * 1024 * 1024 # tar headers and padding read past the files' bytes +_BASELINE = "baseline:" +_UNSAFE = re.compile(r'[\\:<>"|?*\x00-\x1f]') # what Windows refuses in a name; run.v1 refuses \ and : +#: The names Windows reads as a device, with any extension (``CON.json``) and in any case: the set of +#: CPython's ``ntpath.isreserved`` (3.13), and COM0 and LPT0. +_DEVICES = frozenset({"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", + *(f"{p}{d}" for p in ("COM", "LPT") for d in "0123456789\u00b9\u00b2\u00b3")}) +_MEMBER_KINDS = {tarfile.SYMTYPE: "a symlink", tarfile.LNKTYPE: "a hard link", tarfile.CHRTYPE: "a device", + tarfile.BLKTYPE: "a device", tarfile.FIFOTYPE: "a FIFO", tarfile.DIRTYPE: "a directory"} + + +@dataclass(frozen=True) +class Bundle: + """A run's files, checked: each path relative to the run directory, and its bytes.""" + + run_id: str + name: str | None + plan_digest: str + result_sha256: str + files: dict[str, bytes] = field(repr=False) + + @property + def directory(self) -> str: + """Its directory under the runs root: the run's name, else its run_id (docs/run-directories.md).""" + return self.name or self.run_id + + @property + def size_bytes(self) -> int: + return sum(len(data) for data in self.files.values()) + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def safe_path(path: str) -> bool: + """Whether ``path`` names a file inside a directory on every platform: segments joined by ``/``, + none empty, ``..`` or ending in ``.`` or a space (Windows drops those), none a Windows device name + (``CON``, ``nul.json``), and no ``\\``, ``:``, ``<>"|?*`` or control character.""" + return not _UNSAFE.search(path) and all( + part and not part.endswith((".", " ")) and part.split(".")[0].rstrip(" ").upper() not in _DEVICES + for part in path.split("/")) + + +def _check_paths(paths: Iterable[str], where: str) -> None: + """Raise ``InputError`` for a path :func:`safe_path` refuses, one listed twice, two that differ + only in case or Unicode normalization (Windows or macOS would write both to one file), and one + under another listed path, which no directory can hold.""" + folded: dict[str, str] = {} + for path in paths: + if not safe_path(path): + raise InputError(f"{where}: the path {plain(path)!r} would leave the run directory or cannot name " + "a file on every platform: a bundle holds relative paths joined by '/', with no " + "'.' or '..' segment (docs/runs.md)") + key = unicodedata.normalize("NFC", path).casefold() # macOS also reads NFC and NFD as one name + other = folded.get(key) + if other == path: + raise InputError(f"{where}: {plain(path)} is listed twice") + folded[key] = path + if other is not None: + how = ("in case, which Windows and macOS read" if other.casefold() == path.casefold() + else "in Unicode normalization, which macOS reads") + raise InputError(f"{where}: {plain(path)} and {plain(other)} differ only {how} as one file") + for key, path in folded.items(): # no directory holds a file and a file under that name + parents = ("/".join(key.split("/")[:end]) for end in range(1, key.count("/") + 1)) + parent = next((folded[p] for p in parents if p in folded), None) + if parent is not None: + raise InputError(f"{where}: {plain(parent)} is a file, so {plain(path)} cannot be a file under it") + _check_directories(folded.values(), where) + + +def _check_directories(paths: Iterable[str], where: str) -> None: + """Raise ``InputError`` for two spellings of one directory (``Sub/a.json``, ``sub/b.json``): + Windows and macOS make one directory of them, so the run read back would not have the bundle's + paths, and importing it again would refuse it.""" + spelled: dict[str, str] = {} + for path in paths: + parts = path.split("/")[:-1] + for end in range(1, len(parts) + 1): + directory = "/".join(parts[:end]) + other = spelled.setdefault(unicodedata.normalize("NFC", directory).casefold(), directory) + if other != directory: + raise InputError(f"{where}: {plain(path)} spells the directory {plain(other)} as " + f"{plain(directory)}, which Windows and macOS read as one directory") + + +def _document(files: Mapping[str, bytes], path: str, kind: str, where: str) -> dict[str, Any]: + """The file at ``path`` as a ``kind`` artifact. Raises ``InputError`` when it is not one.""" + try: + data = json.loads(files[path].decode("utf-8")) + except (ValueError, RecursionError) as exc: # not UTF-8, not JSON, nested past what Python reads + raise InputError(f"{where}: {plain(path)}: {read_error_reason(exc)}") from exc + if not isinstance(data, dict): + raise InputError(f"{where}: {plain(path)} is not a {kind} artifact: not a JSON object") + try: + validate_artifact(kind, data) + except ArtifactValidationError as exc: + raise InputError(f"{where}: {plain(path)} is not a valid {kind} artifact: {exc}") from exc + if artifact_version(path.rsplit("/", 1)[-1], files[path]) != data["schema_version"]: + raise InputError(f"{where}: {plain(path)} is a {kind} artifact runs list would not find, so its run " + "could not be exported again: an artifact's name ends in .json and its JSON opens " + "with its schema_version, as dokimi writes it") + return data + + +def _listed(run: dict[str, Any], files: Mapping[str, bytes], where: str) -> dict[str, str]: + """The artifacts ``run.json`` lists, path -> kind, which must be the bundle's files but run.json.""" + listed = {entry["path"]: entry["kind"] for entry in run["artifacts"]} + if len(listed) != len(run["artifacts"]): + raise InputError(f"{where}: run.json lists one path twice") + unknown = sorted(kind for kind in listed.values() if kind not in SCHEMA_VERSIONS) + if unknown: + raise InputError(f"{where}: run.json lists an artifact of the unknown kind {plain(unknown[0])!r}") + if "run" in listed.values(): # rundir._OWN_KINDS: export could never write it back + raise InputError(f"{where}: run.json lists a run record: a run directory holds one, its {RUN_FILE}") + missing = sorted(set(listed) - set(files)) + if missing: + raise InputError(f"{where}: run.json lists {plain(missing[0])}, which the run does not hold") + extra = sorted(set(files) - {RUN_FILE, *listed}) + if extra: + raise InputError(f"{where}: {plain(extra[0])} is not an artifact run.json lists") + for kind in ("plan", "result"): + count = sum(1 for k in listed.values() if k == kind) + if count != 1: # the address is the plan's digest and the result's sha (#94 §2.3) + raise InputError(f"{where}: run.json lists {count} {kind} artifacts: a bundle moves a run with " + "one plan and its result") + return listed + + +def verified(files: Mapping[str, bytes], where: str) -> Bundle: + """``files`` (path relative to the run directory -> bytes) as a :class:`Bundle`, once they are + a run: a valid ``run.json`` with a ``run_id``, exactly the artifacts it lists, each valid for its + kind and carrying that ``run_id`` (an input kind carries none), and a result of the plan beside it. + + Raises ``InputError``, its message led by ``where``, for the first thing that does not hold. + """ + _check_paths(files, where) + if RUN_FILE not in files: + raise InputError(f"{where}: no {RUN_FILE}: a bundle moves a run directory (docs/run-directories.md)") + run = _document(files, RUN_FILE, "run", where) + run_id = run.get("run_id") + if not is_run_id(run_id): + raise InputError(f"{where}: {RUN_FILE} carries no run_id: it was saved before the run envelope") + directory = run["name"] or str(run_id) # what names its directory under the runs root + if not safe_path(directory): + raise InputError(f"{where}: the run's directory {plain(directory)!r} cannot be made on every " + "platform: Windows reads it as a device or drops its last '.'") + listed = _listed(run, files, where) + by_kind: dict[str, dict[str, Any]] = {} + for path, kind in listed.items(): + data = _document(files, path, kind, where) + if kind not in INPUT_KINDS and data.get("run_id") != run_id: # docs/run-directories.md: one run's envelope + raise InputError(f"{where}: {plain(path)} carries the run_id {plain(str(data.get('run_id')))}, " + f"not the run's {run_id}") + by_kind[kind] = data + digest, result_path = plan_digest(by_kind["plan"]), next(p for p, k in listed.items() if k == "result") + if by_kind["result"]["plan_digest"] != digest: + raise InputError(f"{where}: {plain(result_path)} is the result of the plan " + f"{plain(by_kind['result']['plan_digest'])}, not of the run's plan {digest}") + return Bundle(str(run_id), run["name"], digest, _sha256(files[result_path]), dict(files)) + + +def manifest(bundle: Bundle) -> dict[str, Any]: + """The ``bundle.json`` of ``bundle``.""" + return {"schema_version": SCHEMA, "run_id": bundle.run_id, "name": bundle.name, + "plan_digest": bundle.plan_digest, "result_sha256": bundle.result_sha256, + "files": [{"path": path, "sha256": _sha256(data), "size_bytes": len(data)} + for path, data in sorted(bundle.files.items())]} + + +def _manifest_bytes(bundle: Bundle) -> bytes: + return (json.dumps(manifest(bundle), indent=2) + "\n").encode("utf-8") + + +def _add(tar: tarfile.TarFile, name: str, data: bytes) -> None: + info = tarfile.TarInfo(name) # mtime 0, owner 0, no names: the same run makes the same tar + info.size, info.mode = len(data), 0o644 + tar.addfile(info, io.BytesIO(data)) + + +def write(bundle: Bundle, out: IO[bytes]) -> None: + """Write ``bundle`` to ``out``: ``bundle.json``, then the run's files by path, with no time, owner + or mode of their own, so one run always makes the same tar (the gzip bytes are zlib's: another + zlib build may compress it to others; ``bundle.json`` stays the same).""" + with gzip.GzipFile(filename="", mode="wb", fileobj=out, mtime=0) as zipped, \ + tarfile.open(fileobj=zipped, mode="w|", format=tarfile.PAX_FORMAT) as tar: + _add(tar, MANIFEST, _manifest_bytes(bundle)) + for path in sorted(bundle.files): + _add(tar, PREFIX + path, bundle.files[path]) + + +@dataclass(frozen=True) +class Collected: + """A run read for export: its bundle, its directory (relative to the root), the artifacts that + carry its run_id but are not in it, and the other files of its directory it leaves out (run.json + lists neither).""" + + bundle: Bundle + directory: Path + left_out: list[Path] + unlisted: list[Path] + + +def resolve(root: Path, target: str) -> str: + """The run_id ``target`` names: a run_id, or ``baseline:NAME``, the run that baseline points to. + Raises ``InputError`` for neither, and for a baseline that is not there.""" + if not target.startswith(_BASELINE): + if not is_run_id(target): + raise InputError(f"{plain(target)!r} is not a run id, nor baseline:NAME") + return target + name = baseline.check_name(target[len(_BASELINE):]) + listing = baseline.listed(root) + pointer = next((p for p in listing.pointers if p.name == name), None) + if pointer is None: + unread = len(listing.unreadable) + note = f"; {unread} {'entry' if unread == 1 else 'entries'} of .baselines/ could not be read" if unread else "" + raise InputError(f"no baseline {name} under the runs root {plain(root.as_posix())}/{note}") + return pointer.run_id + + +def _run_record(root: Path, run_id: str) -> tuple[Path, list[Path]]: + """The ``run.json`` (relative to the root) of ``run_id``, and every artifact that carries it.""" + result = scan(root) + found = [a for a in result.artifacts if a.run_id == run_id] + records = [a.path for a in found if a.kind == "run" and a.path.name == RUN_FILE] + if not found: + unread = len(result.unreadable) + note = f"; {unread} {'entry' if unread == 1 else 'entries'} under the root could not be read" if unread else "" + raise InputError(f"no artifact under the runs root {plain(root.as_posix())}/ has the run_id {run_id}{note}") + if not records: + raise InputError(f"run {run_id} has no run directory: none of its {len(found)} artifacts is a " + f"{RUN_FILE}, and a bundle moves a run directory (docs/run-directories.md)") + if len(records) > 1: + raise InputError(f"run {run_id} has {len(records)} {RUN_FILE} files under the root " + f"({', '.join(plain(p.as_posix()) for p in records)}): which is its directory is not known") + return records[0], [a.path for a in found] + + +def _read_file(directory: Path, path: str, budget: int, where: str) -> bytes: + """The regular file ``path`` in ``directory``, at most ``budget`` bytes. Raises ``InputError``.""" + file = directory / path + if not inside(os.path.realpath(directory), os.path.realpath(file)): + raise InputError(f"{where}: {plain(path)} leads out of the run directory") + try: + found = os.lstat(file) + if not stat.S_ISREG(found.st_mode): + raise InputError(f"{where}: {plain(path)} is not a regular file (a link, a FIFO or a device)") + if found.st_size > budget: + raise InputError(f"{where}: the run's files are over {MAX_BYTES:,} bytes, the cap of a bundle") + return file.read_bytes() + except FileNotFoundError as exc: + raise InputError(f"{where}: {RUN_FILE} lists {plain(path)}, which is not there") from exc + except OSError as exc: + raise InputError(f"{where}: {plain(path)}: {read_error_reason(exc)}") from exc + + +def collect(root: Path, run_id: str) -> Collected: + """The run directory of ``run_id`` under ``root``, read and checked as :func:`verified` checks a + bundle on import, so an export never writes one that import refuses. Raises ``InputError``.""" + record, carried = _run_record(root, run_id) + where = f"run {run_id}" + directory = root / record.parent + files = {RUN_FILE: _read_file(directory, RUN_FILE, MAX_BYTES, where)} + run = _document(files, RUN_FILE, "run", where) + paths = [entry["path"] for entry in run["artifacts"]] + _check_paths(paths, where) + for path in paths: + files[path] = _read_file(directory, path, MAX_BYTES - sum(map(len, files.values())), where) + bundle = verified(files, where) + _check_manifest(manifest(bundle), where) # what import checks first: past its caps no import could read it + size = len(_manifest_bytes(bundle)) + if size > _MAX_MANIFEST: + raise InputError(f"{where}: its {MANIFEST} would be {size:,} bytes, past the {_MAX_MANIFEST:,} " + "an import reads") + held = {record.parent / path for path in bundle.files} + left_out = [p for p in carried if p not in held] + return Collected(bundle, record.parent, left_out, _unlisted(directory, record.parent, held | set(left_out))) + + +def _unlisted(directory: Path, prefix: Path, known: set[Path]) -> list[Path]: + """The files in ``directory`` (``prefix`` under the root) not in ``known``, by path.""" + found = (prefix / Path(top, name).relative_to(directory) for top, _, names in os.walk(directory) for name in names) + return sorted(path for path in found if path not in known) + + +class _Capped(io.RawIOBase): + """A reader of ``stream`` that refuses to read past ``limit`` bytes: a gzip bomb stops there.""" + + def __init__(self, stream: io.BufferedIOBase, limit: int, where: str) -> None: + self._stream, self._left, self._where = stream, limit, where + + def readable(self) -> bool: + return True + + def read(self, size: int | None = -1) -> bytes: + want = self._left + 1 if size is None or size < 0 else min(size, self._left + 1) + data = self._stream.read(want) + self._left -= len(data) + if self._left < 0: + raise InputError(f"{self._where}: over {MAX_BYTES:,} bytes once unpacked, the cap of a bundle") + return data + + +def _check_member(member: tarfile.TarInfo, where: str) -> None: + """Refuse a member that is not a regular file, and one whose path would leave the run directory.""" + if member.type not in (tarfile.REGTYPE, tarfile.AREGTYPE): + what = _MEMBER_KINDS.get(member.type, f"of tar type {member.type!r}") + raise InputError(f"{where}: member {plain(member.name)} is {what}, not a regular file: a bundle " + "holds only files (docs/runs.md)") + inner = member.name[len(PREFIX):] if member.name.startswith(PREFIX) else member.name + if not safe_path(inner): + raise InputError(f"{where}: member {plain(member.name)} would leave the run directory: a bundle " + "holds relative paths joined by '/', with no '.' or '..' segment (docs/runs.md)") + + +def _member_bytes(tar: tarfile.TarFile, member: tarfile.TarInfo, budget: int, where: str) -> bytes: + if member.size > budget: + raise InputError(f"{where}: member {plain(member.name)} ({member.size:,} bytes) is past the cap of " + f"{MAX_BYTES:,} bytes for a bundle's files, or of {_MAX_MANIFEST:,} for {MANIFEST}") + return cast(IO[bytes], tar.extractfile(member)).read() # a regular member always has its data + + +def _check_manifest(document: object, where: str) -> None: + """Raise ``InputError`` when ``document`` is not a ``run_bundle.v1`` manifest (its item and length caps too).""" + errors = schema_errors(SCHEMA, document) + if errors: + more = f" (and {len(errors) - 1} more)" if len(errors) > 1 else "" + raise InputError(f"{where}: {MANIFEST} is not a {SCHEMA} manifest: {plain(errors[0])}{more}") + + +def _read_manifest(data: bytes, where: str) -> dict[str, Any]: + """``bundle.json``, a ``run_bundle.v1`` document with paths a bundle may hold. Raises ``InputError``.""" + try: + document = json.loads(data.decode("utf-8")) + except (ValueError, RecursionError) as exc: + raise InputError(f"{where}: {MANIFEST}: {read_error_reason(exc)}") from exc + _check_manifest(document, where) + _check_paths([entry["path"] for entry in document["files"]], where) + return dict(document) + + +def _members(tar: tarfile.TarFile, where: str) -> tuple[dict[str, Any], dict[str, bytes]]: + """``bundle.json`` (the first member) and the run's files, each one it lists, matching its hash.""" + members = iter(tar) # one pass: a stream is read once + first = next(members, None) + if first is None: + raise InputError(f"{where}: an empty tar, with no {MANIFEST}") + _check_member(first, where) + if first.name != MANIFEST: + raise InputError(f"{where}: the first member is {plain(first.name)}, not {MANIFEST}") + listing = _read_manifest(_member_bytes(tar, first, _MAX_MANIFEST, where), where) + expected = {PREFIX + entry["path"]: entry for entry in listing["files"]} + files: dict[str, bytes] = {} + for member in members: + _check_member(member, where) + entry = expected.get(member.name) + if entry is None or entry["path"] in files: + raise InputError(f"{where}: member {plain(member.name)} is not a file {MANIFEST} lists, or is " + "there twice") + data = _member_bytes(tar, member, MAX_BYTES - sum(map(len, files.values())), where) + if len(data) != entry["size_bytes"] or _sha256(data) != entry["sha256"]: + raise InputError(f"{where}: member {plain(member.name)} does not match its sha256 and size in " + f"{MANIFEST}: it changed since the export") + files[entry["path"]] = data + missing = sorted(set(expected) - {PREFIX + path for path in files}) + if missing: + raise InputError(f"{where}: {MANIFEST} lists {plain(missing[0])}, which the bundle does not hold") + return listing, files + + +def read(path: Path) -> Bundle: + """The bundle at ``path``, checked: every member against ``bundle.json``, then the run as + :func:`verified` checks it, then ``bundle.json``'s run and address against the run's. + + Raises ``InputError`` for a file that cannot be read, is not a gzipped tar, or fails a check. + """ + where = plain(path.as_posix()) + try: + if not stat.S_ISREG(os.stat(path).st_mode): # opening a FIFO would wait for a writer + raise InputError(f"{where}: not a regular file (a directory, a FIFO or a device)") + raw = open(path, "rb") # noqa: SIM115 - closed by the with below + except OSError as exc: + raise InputError(f"{where}: {read_error_reason(exc)}") from exc + with raw: + try: + with gzip.GzipFile(fileobj=raw, mode="rb") as unzipped, \ + tarfile.open(fileobj=cast(IO[bytes], _Capped(unzipped, MAX_BYTES + _SLACK, where)), mode="r|") as tar: + listing, files = _members(tar, where) + except InputError: + raise + # tarfile parses some header fields (a PAX sparse map) with int(): a bad one is a ValueError + except (OSError, EOFError, ValueError, zlib.error, tarfile.TarError) as exc: + raise InputError(f"{where}: not a run bundle (a gzipped tar): {exc}") from exc + bundle = verified(files, where) + for key, value in (("run_id", bundle.run_id), ("name", bundle.name), + ("plan_digest", bundle.plan_digest), ("result_sha256", bundle.result_sha256)): + if listing[key] != value: + raise InputError(f"{where}: {MANIFEST} gives {key} {plain(str(listing[key]))}, but the run in " + f"the bundle has {plain(str(value))}") + return bundle + + +@dataclass(frozen=True) +class Installed: + """Where :func:`install` put a run (relative to the root), and whether it wrote it: ``False`` + when that run was there already, identical.""" + + path: Path + written: bool + + +def _first_difference(directory: Path, bundle: Bundle) -> str | None: + """The first file of ``bundle`` (by path) that is not a regular file in ``directory`` with the same + bytes; ``None`` when there is none.""" + for path, data in sorted(bundle.files.items()): + try: + if not stat.S_ISREG(os.lstat(directory / path).st_mode) or (directory / path).read_bytes() != data: + return path + except OSError: + return path + return None + + +def _is_empty_dir(path: Path) -> bool: + return not is_link(path) and path.is_dir() and not any(path.iterdir()) + + +def _publish(target: Path, bundle: Bundle) -> None: + """Write the run into a directory beside ``target``, then rename it to ``target``: a reader sees + all of it or none. Raises ``InputError`` when ``target`` holds anything, ``OSError`` as writing does.""" + taken = InputError(f"run directory {plain(target.as_posix())} already exists: an import never writes " + "into another run's directory (docs/run-directories.md)") + if os.path.lexists(target) and not _is_empty_dir(target): + raise taken + staging = target.with_name(f".{target.name}.{secrets.token_hex(4)}.import") + try: + for path, data in bundle.files.items(): + (staging / path).parent.mkdir(parents=True, exist_ok=True) + (staging / path).write_bytes(data) + if os.path.lexists(target): + target.rmdir() # empty, as checked: Windows renames no directory onto one + try: + os.rename(staging, target) + except OSError as exc: + if os.path.lexists(target): # another run took it since the check + raise taken from exc + raise + finally: + shutil.rmtree(staging, ignore_errors=True) # gone already when the rename went through + + +def install(root: Path, bundle: Bundle) -> Installed: + """Write ``bundle``'s run to ``/``, or nothing when that run is there, identical. + + It holds the baselines' lock (``.baselines/.lock``, :func:`baseline.locked`) from the scan for the + run_id to the rename, so of two imports of one run_id into one root, under two names or one, the + second sees the first's run. Raises ``InputError`` when another run has the bundle's run_id under + ``root`` (an import never replaces a run), the directory holds something or the lock cannot be + taken, and ``OSError`` when the run cannot be written. + """ + with baseline.locked(root): + return _install(root, bundle) + + +def _install(root: Path, bundle: Bundle) -> Installed: + target = root / bundle.directory + carried = [a.path for a in scan(root).artifacts if a.run_id == bundle.run_id] + if not carried: + _publish(target, bundle) + return Installed(target.relative_to(root), True) + held = {Path(bundle.directory) / path for path in bundle.files} + stray = next((path for path in carried if path not in held), None) + differs = _first_difference(target, bundle) + if stray is None and differs is None: + return Installed(target.relative_to(root), False) + where = (stray or Path(bundle.directory) / str(differs)).as_posix() + why = "is not in the bundle" if stray else "differs from the bundle's" + raise InputError(f"run {bundle.run_id} is already under the runs root, and its {plain(where)} {why}: an " + "import never replaces a run (runs rm removes it)") diff --git a/dokimi/dokimi/runs/scan.py b/dokimi/dokimi/runs/scan.py index 06a8b4db4..66041d632 100644 --- a/dokimi/dokimi/runs/scan.py +++ b/dokimi/dokimi/runs/scan.py @@ -32,6 +32,9 @@ DEFAULT_ROOT = Path("results") #: The baseline pointers (:mod:`dokimi.runs.baseline`): not artifacts, so the scan does not walk it. BASELINE_POINTERS = ".baselines" +#: A run ``runs import`` is writing beside its place (:mod:`dokimi.runs.bundle`), renamed into it +#: once whole: not walked, so no reader sees part of a run. A run's own name never starts with ".". +IMPORT_STAGING = re.compile(r"\.[^/]+\.[0-9a-f]{8}\.import") #: ``save_artifact`` writes ``{"schema_version": ".vN", ...`` with ``indent=2``. HEAD_BYTES = 256 _HEAD = re.compile(rb'\A\s*\{\s*"schema_version"\s*:\s*"([^"\\\x00-\x1f]{1,100})"') @@ -203,10 +206,21 @@ def plain(text: str) -> str: def head_version(path: Path) -> str | None: """The ``schema_version`` a file opens with, read from its first bytes; ``None`` if none.""" with open(path, "rb") as fh: - match = _HEAD.match(fh.read(HEAD_BYTES)) + return leading_version(fh.read(HEAD_BYTES)) + + +def leading_version(head: bytes) -> str | None: + """The ``schema_version`` that ``head`` opens with within its first :data:`HEAD_BYTES`; ``None`` if none.""" + match = _HEAD.match(head[:HEAD_BYTES]) return match.group(1).decode("utf-8", errors="replace") if match else None +def artifact_version(name: str, head: bytes) -> str | None: + """The ``schema_version`` :func:`scan` reads a file named ``name`` that opens with ``head`` as, or + ``None`` when it skips the file (by its name, or bytes that do not open with one).""" + return None if _skip_reason(name) else leading_version(head) + + def load_document(path: Path, version: str) -> dict: """The JSON object at ``path``, whose first bytes declared ``version``. @@ -313,8 +327,9 @@ def newest_first(artifacts: list[Artifact]) -> list[Artifact]: def scan(root: Path) -> ScanResult: - """Every artifact under ``root`` (a directory), newest first. Symlinked directories are not - walked, and a file symlink is read only when it resolves inside the root.""" + """Every artifact under ``root`` (a directory), newest first. Symlinked directories, the root's + ``.baselines`` and the runs an import is still writing are not walked, and a file symlink is read + only when it resolves inside the root.""" result = ScanResult(root=root) real_root = os.path.realpath(root) @@ -327,7 +342,7 @@ def unlisted(exc: OSError) -> None: linked = {d for d in dirnames if is_link(base / d)} result.skipped["linked_directory"] += len(linked) dirnames[:] = sorted(d for d in dirnames if d not in linked - and not (d == BASELINE_POINTERS and base == root)) + and not (base == root and (d == BASELINE_POINTERS or IMPORT_STAGING.fullmatch(d)))) for name in sorted(filenames): _scan_file(result, base / name, real_root) result.artifacts = newest_first(result.artifacts) diff --git a/dokimi/dokimi/schemas/run_bundle.v1.json b/dokimi/dokimi/schemas/run_bundle.v1.json new file mode 100644 index 000000000..e54b010bd --- /dev/null +++ b/dokimi/dokimi/schemas/run_bundle.v1.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/intel/dokimi/schemas/run_bundle.v1.json", + "title": "Run bundle manifest v1", + "description": "bundle.json, the first member of the gzipped tar runs export writes (docs/runs.md, #94 §2.3): the run it moves, its address (the plan's plan_digest and the sha256 of its result.v1.json) and the sha256 and size of each file under run/ in the tar. Written by dokimi.runs.bundle; runs import checks every member against it, and the run against its schemas, before it writes anything.", + "type": "object", + "required": ["schema_version", "run_id", "name", "plan_digest", "result_sha256", "files"], + "properties": { + "schema_version": {"const": "run_bundle.v1"}, + "run_id": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}(?![\\s\\S])", "description": "The run's run_id, which every artifact of the run carries."}, + "name": {"type": ["string", "null"], "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}(?![\\s\\S])", "description": "The run's name from run.json, which names its directory under the runs root; null when the directory is named by run_id."}, + "plan_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])", "description": "dokimi.runner.plan.plan_digest of the run's plan, which its result names."}, + "result_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}(?![\\s\\S])", "description": "The sha256 of the run's result.v1.json, as stored."}, + "files": { + "type": "array", + "minItems": 1, + "maxItems": 1000, + "description": "Every file of the run, sorted by path: run.json and the artifacts it lists. Each is the tar member run/.", + "items": { + "type": "object", + "required": ["path", "sha256", "size_bytes"], + "properties": { + "path": {"type": "string", "minLength": 1, "maxLength": 1024, "description": "Relative to the run directory, with / separators."}, + "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}(?![\\s\\S])"}, + "size_bytes": {"type": "integer", "minimum": 0} + } + } + } + } +} diff --git a/dokimi/tests/cli_faults.py b/dokimi/tests/cli_faults.py index 72de4eb57..8fb8741e4 100644 --- a/dokimi/tests/cli_faults.py +++ b/dokimi/tests/cli_faults.py @@ -50,6 +50,7 @@ ("arms matrix-run", "--arm"), ("arms run", "--arm"), ("report eval", "--name"), + ("runs export", "run"), ("skill novelty analyze", "--model"), ("tasks run", "--command-template"), ("tasks run", "--tasks"), diff --git a/dokimi/tests/fixtures/artifacts/run_bundle.v1.json b/dokimi/tests/fixtures/artifacts/run_bundle.v1.json new file mode 100644 index 000000000..e08997827 --- /dev/null +++ b/dokimi/tests/fixtures/artifacts/run_bundle.v1.json @@ -0,0 +1,29 @@ +{ + "schema_version": "run_bundle.v1", + "run_id": "20261123T101500Z-1a2b3c4d", + "name": "nightly-7", + "plan_digest": "sha256:6bbd76a2642039efd7b9d8fee6ffe85ec785ee3ec0985f4fc0fcd56c521f2348", + "result_sha256": "fc5d04c63d4d8e3d674992d325a34a271c48cf68ffa6d08c9dedfa6d24e9062f", + "files": [ + { + "path": "arms.v1.json", + "sha256": "a1cafaa0d3c6a5376a1a75e53a0c19389dffafce9bd5c30d9b5a54ec2969b4b6", + "size_bytes": 3521 + }, + { + "path": "plan.v1.json", + "sha256": "06cc2b0385081ef09b669d16ecbdbc5acd82a20ad5add090f2e7afcfb182f7e8", + "size_bytes": 1869 + }, + { + "path": "result.v1.json", + "sha256": "fc5d04c63d4d8e3d674992d325a34a271c48cf68ffa6d08c9dedfa6d24e9062f", + "size_bytes": 976 + }, + { + "path": "run.json", + "sha256": "d0d554fae27bcfcb5a89915e17e24e6cadd75da65278d5e622a42a8a1bf1bcc3", + "size_bytes": 588 + } + ] +} diff --git a/dokimi/tests/test_cli_output.py b/dokimi/tests/test_cli_output.py index f9d14159b..4ea0f3d40 100644 --- a/dokimi/tests/test_cli_output.py +++ b/dokimi/tests/test_cli_output.py @@ -639,7 +639,7 @@ def test_a_leaf_usage_error_without_json_prints_its_message_on_stderr_only(monke ("delivery", "release"), ("delivery", "report"), ("delivery", "scan"), ("docs", "llms-txt"), ("eval", "check"), ("eval", "graph"), ("eval", "inspect"), ("memory", "lint"), ("repo", "budget"), ("repo", "compare"), ("repo", "fetch"), - ("repo", "hits", "judge"), ("repo", "report"), ("runs", "gc"), ("runs", "rm"), ("runs", "show"), + ("repo", "hits", "judge"), ("repo", "report"), ("runs", "gc"), ("runs", "import"), ("runs", "rm"), ("runs", "show"), ("runs", "baseline", "list"), ("runs", "baseline", "rm"), ("runs", "baseline", "save"), ("skill", "routing"), ("trace", "consistency"), ("trace", "inspect"), ("trace", "prefilter"), } diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py new file mode 100644 index 000000000..ba43a373b --- /dev/null +++ b/dokimi/tests/test_runs_bundle.py @@ -0,0 +1,984 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""`runs export | import` (#94 §2.3, R3): a run directory moves between machines as one bundle, +and import checks it before it writes anything (docs/runs.md, "Moving a run").""" + +from __future__ import annotations + +import dataclasses +import gzip +import io +import json +import os +import sys +import tarfile +import threading +from pathlib import Path + +import pytest + +from dokimi import cli +from dokimi.artifacts import save_artifact +from dokimi.runs import baseline, bundle +from dokimi.runs.rundir import open_run +from dokimi.runs.scan import RunsRoot, scan +from dokimi.utils import InputError + +FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" +RUN = "20261123T101500Z-1a2b3c4d" +OTHER = "20261124T101500Z-0000000b" + + +def _fixture(version: str) -> dict: + return json.loads((FIXTURES / f"{version}.json").read_text(encoding="utf-8")) + + +def _make_run(results: Path, monkeypatch, run_id: str = RUN, name: str | None = "nightly-7", + plan: bool = True) -> Path: + """A run directory as docs/run-directories.md lays it out: run.json, plan, result, arms.""" + monkeypatch.setenv("DOKIMI_RUN_ID", run_id) + with open_run(results, name=name) as run: + if plan: + planned = run.write_plan(_fixture("plan.v1")) + for cell in planned["cells"]: + run.record_cell(cell["cell_id"], "pass") + save_artifact("arms", _fixture("arms.v1"), run.artifact_path("arms")) + monkeypatch.delenv("DOKIMI_RUN_ID") + return run.path + + +@pytest.fixture +def src(tmp_path, monkeypatch): + """A runs root with the run ``RUN`` in ``nightly-7/``; DOKIMI_RUNS_DIR names it.""" + results = tmp_path / "src" + _make_run(results, monkeypatch) + monkeypatch.setenv("DOKIMI_RUNS_DIR", str(results)) + return results + + +@pytest.fixture +def dst(tmp_path): + """A fresh working directory, as on a new CI runner: no ``results/`` yet.""" + work = tmp_path / "dst" + work.mkdir() + return work + + +def _run(monkeypatch, capsysbinary, *argv: str) -> tuple[int, bytes, str]: + monkeypatch.setattr("sys.argv", ["dokimi", "runs", *argv]) + code = 0 + try: + cli.main() + except SystemExit as exc: + code = exc.code if isinstance(exc.code, int) else 1 + captured = capsysbinary.readouterr() + return code, captured.out, captured.err.decode("utf-8") + + +def _export(monkeypatch, capsysbinary, tmp_path, target: str = RUN) -> Path: + code, out, err = _run(monkeypatch, capsysbinary, "export", target) + assert code == 0, err + path = tmp_path / "bundle.tgz" + path.write_bytes(out) + return path + + +def _import(monkeypatch, capsysbinary, dst: Path, path: Path, *flags: str) -> tuple[int, bytes, str]: + monkeypatch.delenv("DOKIMI_RUNS_DIR", raising=False) + monkeypatch.chdir(dst) + return _run(monkeypatch, capsysbinary, "import", str(path), *flags) + + +def _tree(directory: Path) -> dict[str, bytes]: + return {p.relative_to(directory).as_posix(): p.read_bytes() for p in sorted(directory.rglob("*")) if p.is_file()} + + +Member = tuple[str, bytes, bytes] # name, data, tar type + + +def _tar(members: list[Member], links: dict[str, str] | None = None) -> bytes: + """A gzipped tar of ``members`` as given, with no check: what a hostile bundle can hold.""" + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as zipped, \ + tarfile.open(fileobj=zipped, mode="w|", format=tarfile.PAX_FORMAT) as tar: + for name, data, kind in members: + info = tarfile.TarInfo(name) + info.type = kind + info.linkname = (links or {}).get(name, "") + info.size = len(data) if kind == tarfile.REGTYPE else 0 + tar.addfile(info, io.BytesIO(data) if kind == tarfile.REGTYPE else None) + return out.getvalue() + + +def _rebuilt(found: bundle.Bundle, files: dict[str, bytes], extra: list[Member] = ()) -> bytes: + """A bundle of ``files`` whose bundle.json lists them with their own hashes: one re-signed + after an edit, so only the checks past the hashes can catch it.""" + listing = bundle.manifest(dataclasses.replace(found, files=files)) + members = [(bundle.MANIFEST, json.dumps(listing).encode(), tarfile.REGTYPE)] + members += [(bundle.PREFIX + path, data, tarfile.REGTYPE) for path, data in sorted(files.items())] + return _tar(members + list(extra)) + + +def test_a_run_round_trips_and_its_bundle_is_the_same_bytes_again(src, dst, tmp_path, monkeypatch, + capsysbinary): + # docs/runs.md "Moving a run": export, import on a runner with no results/, --as names it; one run, one bundle + path = _export(monkeypatch, capsysbinary, tmp_path) + + code, out, err = _import(monkeypatch, capsysbinary, dst, path, "--as", "main") + + assert code == 0, err + lines = out.decode().splitlines() + assert lines[0].startswith(f"imported run {RUN} into results/nightly-7/: 4 files, ") + assert lines[1] == f"saved baseline main -> {RUN}; before: none" + assert _tree(dst / "results" / "nightly-7") == _tree(src / "nightly-7") + assert (dst / "results" / ".baselines" / "main").read_text(encoding="utf-8") == RUN + "\n" + monkeypatch.setenv("DOKIMI_RUNS_DIR", str(dst / "results")) + assert _run(monkeypatch, capsysbinary, "export", "baseline:main")[1] == path.read_bytes() + + +def test_export_prints_the_address_on_stderr_and_keeps_stdout_for_the_bundle(src, monkeypatch, capsysbinary): + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + + found = bundle.collect(src, RUN).bundle + assert code == 0 + assert out[:2] == b"\x1f\x8b" # gzip + assert err == (f"exported run {RUN} from nightly-7/: 4 files, {found.size_bytes:,} bytes; plan " + f"{found.plan_digest}, result sha256:{found.result_sha256}\n") + assert found.plan_digest == json.loads((src / "nightly-7" / "result.v1.json").read_text())["plan_digest"] + + +def test_export_names_the_artifacts_of_the_run_it_leaves_out(src, monkeypatch, capsysbinary): + # docs/runs.md: an artifact with the run_id that run.json does not list is not moved, and is named + monkeypatch.setenv("DOKIMI_RUN_ID", RUN) + save_artifact("eval", _fixture("eval.v1"), src / "loose" / "eval.json") + monkeypatch.delenv("DOKIMI_RUN_ID") + + code, _, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert code == 0 + assert err.splitlines()[1] == "left out: 1 artifact with this run_id that run.json does not list (first: loose/eval.json)" + + +def test_export_names_the_files_of_the_run_directory_it_leaves_out(src, monkeypatch, capsysbinary): + # docs/runs.md: a file of the run directory that run.json does not list (a report) is not moved, and is named + (src / "nightly-7" / "reports").mkdir() + (src / "nightly-7" / "reports" / "scorecard.md").write_text("# report\n", encoding="utf-8") + + code, _, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert code == 0 + assert err.splitlines()[1:] == [ + "left out: 1 file in the run directory that run.json does not list (first: nightly-7/reports/scorecard.md)"] + assert "reports/scorecard.md" not in bundle.collect(src, RUN).bundle.files + + +@pytest.mark.parametrize("make, message", [ + (lambda root, mp: save_artifact("arms", _fixture("arms.v1"), root / "arms.json"), + f"run {OTHER} has no run directory: none of its 1 artifacts is a run.json"), + (lambda root, mp: _make_run(root, mp, run_id=OTHER, name="planless", plan=False), + f"run {OTHER}: run.json lists 0 plan artifacts: a bundle moves a run with one plan and its result"), +]) +def test_export_refuses_a_run_a_bundle_cannot_address(src, monkeypatch, capsysbinary, make, message): + # #94 §2.3: a bundle is a run directory, addressed by its plan_digest and its result's sha + monkeypatch.setenv("DOKIMI_RUN_ID", OTHER) + make(src, monkeypatch) + monkeypatch.delenv("DOKIMI_RUN_ID", raising=False) + + code, out, err = _run(monkeypatch, capsysbinary, "export", OTHER) + + assert (code, out) == (2, b"") + assert err.startswith(f"Error: {message}") + + +def test_export_refuses_a_terminal_and_a_missing_baseline(src, monkeypatch, capsysbinary): + code, _, err = _run(monkeypatch, capsysbinary, "export", "baseline:main") + assert (code, err) == (2, f"Error: no baseline main under the runs root {src.as_posix()}/\n") + + monkeypatch.setattr(sys.stdout, "isatty", lambda: True) + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + assert (code, out) == (2, b"") + assert "which is a terminal here: redirect it (runs export RUN > bundle.tgz)" in err + + +def _relist(run_dir: Path, paths: dict[str, str]) -> None: + """Rewrite run.json's ``artifacts`` to ``paths`` (path -> kind), as a hand edit would.""" + record = json.loads((run_dir / "run.json").read_text(encoding="utf-8")) + record["artifacts"] = [{"kind": kind, "path": path} for path, kind in paths.items()] + (run_dir / "run.json").write_text(json.dumps(record, indent=2), encoding="utf-8") + + +LISTED = {"plan.v1.json": "plan", "result.v1.json": "result", "arms.v1.json": "arms"} + + +def _link_out(run_dir: Path, outside: Path) -> None: + (outside / "arms.v1.json").write_bytes((run_dir / "arms.v1.json").read_bytes()) + (run_dir / "sub").symlink_to(outside, target_is_directory=True) + _relist(run_dir, {**LISTED, "sub/arms.v1.json": "arms"}) + + +def _fifo(run_dir: Path, outside: Path) -> None: + os.mkfifo(run_dir / "f.json") + _relist(run_dir, {**LISTED, "f.json": "arms"}) + + +@pytest.mark.parametrize("make, message", [ + (lambda d, o: (d / "arms.v1.json").unlink(), "run.json lists arms.v1.json, which is not there"), + (_link_out, "sub/arms.v1.json leads out of the run directory"), + (lambda d, o: ((d / "arms.v1.json").unlink(), (d / "arms.v1.json").symlink_to(d / "plan.v1.json")), + "arms.v1.json is not a regular file (a link, a FIFO or a device)"), + pytest.param(_fifo, "f.json is not a regular file (a link, a FIFO or a device)", + marks=pytest.mark.skipif(sys.platform == "win32", reason="no FIFO on Windows")), +], ids=["missing", "link-out", "symlink", "fifo"]) +def test_export_refuses_a_listed_file_it_cannot_take_and_writes_nothing(src, tmp_path, monkeypatch, capsysbinary, + make, message): + # docs/runs.md: export refuses a listed file that is missing, is not a regular file or leads out + outside = tmp_path / "outside" + outside.mkdir() + make(src / "nightly-7", outside) + + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert (code, out) == (2, b"") + assert err == f"Error: run {RUN}: {message}\n" + + +@pytest.mark.skipif(sys.platform == "win32", reason="a path over 260 characters") +def test_export_refuses_a_run_whose_bundle_json_import_would_refuse(src, monkeypatch, capsysbinary): + # run_bundle.v1 caps a path at 1024 characters: such a run would export, and no import could read it + deep = Path(*(["d" * 180] * 6)) / "arms.v1.json" + run_dir = src / "nightly-7" + (run_dir / deep).parent.mkdir(parents=True) + (run_dir / deep).write_bytes((run_dir / "arms.v1.json").read_bytes()) + _relist(run_dir, {**LISTED, deep.as_posix(): "arms"}) + + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert (code, out) == (2, b"") + assert err.startswith(f"Error: run {RUN}: bundle.json is not a run_bundle.v1 manifest: files/1/path: ") + assert "is too long" in err + + +def test_export_refuses_a_run_over_the_cap(src, monkeypatch, capsysbinary): + monkeypatch.setattr(bundle, "MAX_BYTES", 3000) # run.json and the plan fit, arms.v1.json does not + + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert (code, out) == (2, b"") + assert err == f"Error: run {RUN}: the run's files are over 3,000 bytes, the cap of a bundle\n" + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="POSIX modes; root reads anyway") +def test_export_refuses_a_listed_file_it_cannot_read(src, monkeypatch, capsysbinary): + arms = src / "nightly-7" / "arms.v1.json" + arms.chmod(0) + try: + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + finally: + arms.chmod(0o644) + + assert (code, out) == (2, b"") + assert err == f"Error: run {RUN}: arms.v1.json: cannot read: Permission denied\n" + + +def test_a_bundle_whose_run_has_no_result_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary): + # #94 §2.3: a bundle is addressed by the plan's digest and its result's sha, so it holds one of each + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + record = json.loads(found.files["run.json"]) + record["artifacts"] = [a for a in record["artifacts"] if a["kind"] != "result"] + files = {p: d for p, d in found.files.items() if p != "result.v1.json"} + files["run.json"] = json.dumps(record).encode() + path = tmp_path / "noresult.tgz" + path.write_bytes(_rebuilt(found, files)) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert err == (f"Error: {path.as_posix()}: run.json lists 0 result artifacts: a bundle moves a run with " + "one plan and its result\n") + assert not (dst / "results").exists() + + +def test_a_run_with_no_name_goes_to_its_run_id_and_json_names_the_baseline(tmp_path, dst, monkeypatch, + capsysbinary): + # docs/runs.md: / for a run with no name; --json gives baseline {name, previous} + results = tmp_path / "src" + _make_run(results, monkeypatch, name=None) + monkeypatch.setenv("DOKIMI_RUNS_DIR", str(results)) + path = _export(monkeypatch, capsysbinary, tmp_path) + + code, out, _ = _import(monkeypatch, capsysbinary, dst, path, "--as", "skill/a@main", "--json") + + data = json.loads(out)["data"] + assert (code, data["path"], data["written"]) == (0, RUN, True) + assert data["baseline"] == {"name": "skill/a@main", "previous": None} + assert _tree(dst / "results" / RUN) == _tree(results / RUN) + + +def test_import_of_the_run_already_there_writes_nothing(src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: a run that is there, identical, is a no-op that exits 0 + path = _export(monkeypatch, capsysbinary, tmp_path) + _import(monkeypatch, capsysbinary, dst, path) + before = {p: p.stat().st_mtime_ns for p in (dst / "results" / "nightly-7").iterdir()} + + code, out, _ = _import(monkeypatch, capsysbinary, dst, path, "--json") + + doc = json.loads(out) + assert (code, doc["kind"], doc["status"]) == (0, "runs import", "complete") + assert (doc["data"]["written"], doc["data"]["path"]) == (False, "nightly-7") + assert {p: p.stat().st_mtime_ns for p in (dst / "results" / "nightly-7").iterdir()} == before + assert sorted(os.listdir(dst / "results")) == [".baselines", "nightly-7"] # no staging directory left + + +def test_import_refuses_a_different_run_with_the_same_run_id(src, dst, tmp_path, monkeypatch, capsysbinary): + # #94 R3: an import never overwrites a run; one that differs keeps its files + path = _export(monkeypatch, capsysbinary, tmp_path) + _import(monkeypatch, capsysbinary, dst, path) + changed = dst / "results" / "nightly-7" / "arms.v1.json" + arms = json.loads(changed.read_text(encoding="utf-8")) + changed.write_text(json.dumps({**arms, "model": "another"}, indent=2), encoding="utf-8") + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert err == (f"Error: run {RUN} is already under the runs root, and its nightly-7/arms.v1.json differs " + "from the bundle's: an import never replaces a run (runs rm removes it)\n") + assert json.loads(changed.read_text(encoding="utf-8"))["model"] == "another" + + +def test_import_into_the_root_it_came_from_names_the_artifact_left_out(src, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: another run with the bundle's run_id "in another place" is refused, and named + monkeypatch.setenv("DOKIMI_RUN_ID", RUN) + save_artifact("eval", _fixture("eval.v1"), src / "loose" / "eval.json") + monkeypatch.delenv("DOKIMI_RUN_ID") + path = _export(monkeypatch, capsysbinary, tmp_path) + + monkeypatch.setenv("DOKIMI_RUNS_DIR", str(src)) + code, _, err = _run(monkeypatch, capsysbinary, "import", str(path)) + + assert (code, err) == (2, f"Error: run {RUN} is already under the runs root, and its loose/eval.json is " + "not in the bundle: an import never replaces a run (runs rm removes it)\n") + + +def test_import_refuses_a_directory_another_run_holds(src, dst, tmp_path, monkeypatch, capsysbinary): + path = _export(monkeypatch, capsysbinary, tmp_path) + taken = _make_run(dst / "results", monkeypatch, run_id=OTHER) # also named nightly-7 + held = _tree(taken) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert "results/nightly-7 already exists: an import never writes into another run's directory" in err + assert _tree(taken) == held + + +def test_a_tampered_member_is_refused_and_nothing_is_written(src, dst, tmp_path, monkeypatch, capsysbinary): + # #94 §2.3: import verifies the hash; the member changed, bundle.json did not + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + files = dict(found.files) + listing = json.dumps(bundle.manifest(found)).encode() + files["result.v1.json"] = files["result.v1.json"].replace(b'"pass"', b'"fail"', 1) + path = tmp_path / "tampered.tgz" + path.write_bytes(_tar([(bundle.MANIFEST, listing, tarfile.REGTYPE)] + + [(bundle.PREFIX + p, d, tarfile.REGTYPE) for p, d in sorted(files.items())])) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert err == (f"Error: {path.as_posix()}: member run/result.v1.json does not match its sha256 and size " + "in bundle.json: it changed since the export\n") + assert not (dst / "results").exists() + + +@pytest.mark.parametrize("member, links, message", [ + (("/etc/cron.d/x", b"x", tarfile.REGTYPE), None, "member /etc/cron.d/x would leave the run directory"), + (("run/../../x.json", b"x", tarfile.REGTYPE), None, "member run/../../x.json would leave the run directory"), + (("run/sub\\..\\x.json", b"x", tarfile.REGTYPE), None, "would leave the run directory"), + (("run/link.json", b"", tarfile.SYMTYPE), {"run/link.json": "/etc/passwd"}, "is a symlink, not a regular file"), + (("run/hard.json", b"", tarfile.LNKTYPE), {"run/hard.json": "run/run.json"}, "is a hard link, not a regular file"), + (("run/fifo", b"", tarfile.FIFOTYPE), None, "member run/fifo is a FIFO, not a regular file"), + (("run/dev", b"", tarfile.CHRTYPE), None, "member run/dev is a device, not a regular file"), + (("run/sub", b"", tarfile.DIRTYPE), None, "member run/sub is a directory, not a regular file"), + (("run/extra.json", b"{}", tarfile.REGTYPE), None, "member run/extra.json is not a file bundle.json lists"), +]) +def test_a_malicious_member_is_refused_and_nothing_is_written(src, dst, tmp_path, monkeypatch, capsysbinary, + member, links, message): + # docs/runs.md: only regular files at the paths bundle.json lists; nothing may leave the run directory + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + path = tmp_path / "hostile.tgz" + listing = json.dumps(bundle.manifest(found)).encode() + path.write_bytes(_tar([(bundle.MANIFEST, listing, tarfile.REGTYPE), member], links)) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert message in err + assert not (dst / "results").exists() + assert not (tmp_path / "x.json").exists() + + +def test_an_artifact_that_fails_its_schema_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary): + # #94 §2.3: import verifies each artifact's schema, also when bundle.json was re-signed to match + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + arms = json.loads(found.files["arms.v1.json"]) + del arms["arms"] + path = tmp_path / "invalid.tgz" + path.write_bytes(_rebuilt(found, {**found.files, "arms.v1.json": json.dumps(arms).encode()})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert err.startswith(f"Error: {path.as_posix()}: arms.v1.json is not a valid arms artifact: ") + assert "'arms' is a required property" in err + assert not (dst / "results").exists() + + +@pytest.mark.parametrize("edit, message", [ + (lambda r: {**r, "plan_digest": "sha256:" + "0" * 64}, + "result.v1.json is the result of the plan sha256:0000"), + (lambda r: {**r, "run_id": OTHER}, f"result.v1.json carries the run_id {OTHER}, not the run's {RUN}"), +]) +def test_a_result_of_another_plan_or_run_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary, edit, message): + # docs/run-directories.md: a result is tied to its plan by plan_digest; a run's files share its envelope + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + result = edit(json.loads(found.files["result.v1.json"])) + files = {**found.files, "result.v1.json": json.dumps(result).encode()} + path = tmp_path / "other.tgz" + path.write_bytes(_rebuilt(dataclasses.replace(found, result_sha256=bundle._sha256(files["result.v1.json"])), files)) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert message in err + + +def test_bundle_json_that_names_another_address_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary): + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + path = tmp_path / "address.tgz" + path.write_bytes(_rebuilt(dataclasses.replace(found, plan_digest="sha256:" + "1" * 64), found.files)) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert err == (f"Error: {path.as_posix()}: bundle.json gives plan_digest sha256:{'1' * 64}, but the run in " + f"the bundle has {found.plan_digest}\n") + + +def test_paths_that_differ_only_in_case_are_refused(src, dst, tmp_path, monkeypatch, capsysbinary): + # Windows and macOS would write both to one file after both were checked + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + path = tmp_path / "case.tgz" + path.write_bytes(_rebuilt(found, {**found.files, "ARMS.v1.json": found.files["arms.v1.json"]})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert "arms.v1.json and ARMS.v1.json differ only in case, which Windows and macOS read as one file" in err + + +def test_a_bundle_past_the_cap_once_unpacked_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: the stream itself is capped, so a gzip bomb stops at the cap, not at the end of memory + path = _export(monkeypatch, capsysbinary, tmp_path) + monkeypatch.setattr(bundle, "MAX_BYTES", 100) + monkeypatch.setattr(bundle, "_SLACK", 0) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert (code, err) == (2, f"Error: {path.as_posix()}: over 100 bytes once unpacked, the cap of a bundle\n") + assert not (dst / "results").exists() + + +def test_a_file_past_the_cap_names_the_cap(src, dst, tmp_path, monkeypatch, capsysbinary): + path = _export(monkeypatch, capsysbinary, tmp_path) + monkeypatch.setattr(bundle, "MAX_BYTES", 2000) # bundle.json fits; arms.v1.json (3.5 kB) does not + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert "member run/arms.v1.json (3,5" in err and "past the cap of 2,000 bytes" in err + + +def test_bundle_json_that_lists_a_path_twice_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary): + # the module's contract: bundle.json is the list of the bundle's files, each once + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + listing = bundle.manifest(found) + listing["files"].insert(0, {**listing["files"][0], "sha256": "0" * 64}) + path = tmp_path / "twice.tgz" + path.write_bytes(_tar([(bundle.MANIFEST, json.dumps(listing).encode(), tarfile.REGTYPE)] + + [(bundle.PREFIX + p, d, tarfile.REGTYPE) for p, d in sorted(found.files.items())])) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert (code, err) == (2, f"Error: {path.as_posix()}: arms.v1.json is listed twice\n") + + +@pytest.mark.parametrize("data, message", [ + (b"not a tar", "not a run bundle (a gzipped tar)"), + (gzip.compress(b"\0" * 1024, mtime=0), "an empty tar, with no bundle.json"), +], ids=["not-gzip", "empty-tar"]) +def test_a_file_that_is_no_bundle_is_refused(dst, tmp_path, monkeypatch, capsysbinary, data, message): + path = tmp_path / "x.tgz" + path.write_bytes(data) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert message in err + + +def test_a_tar_whose_header_tarfile_cannot_parse_is_an_input_error(dst, tmp_path, monkeypatch, capsysbinary): + # tarfile reads a PAX sparse map with int(): a malformed one is a ValueError, not a TarError + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as zipped, \ + tarfile.open(fileobj=zipped, mode="w|", format=tarfile.PAX_FORMAT) as tar: + info = tarfile.TarInfo(bundle.MANIFEST) + info.size, info.pax_headers = 2, {"GNU.sparse.map": "x"} + tar.addfile(info, io.BytesIO(b"{}")) + path = tmp_path / "sparse.tgz" + path.write_bytes(out.getvalue()) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert f"Error: {path.as_posix()}: not a run bundle (a gzipped tar): " in err + assert "Traceback" not in err + + +@pytest.mark.skipif(sys.platform == "win32", reason="no FIFO on Windows") +def test_a_bundle_that_is_not_a_regular_file_is_refused_not_waited_on(dst, tmp_path, monkeypatch, capsysbinary): + # as runs show refuses a FIFO (docs/runs.md): opening one would wait for a writer + fifo = tmp_path / "bundle.tgz" + os.mkfifo(fifo) + + code, _, err = _import(monkeypatch, capsysbinary, dst, fifo) + + assert (code, err) == (2, f"Error: {fifo.as_posix()}: not a regular file (a directory, a FIFO or a device)\n") + + +def test_bundle_json_must_come_first_and_list_every_member(src, dst, tmp_path, monkeypatch, capsysbinary): + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + listing = json.dumps(bundle.manifest(found)).encode() + first = tmp_path / "first.tgz" + first.write_bytes(_tar([("run/run.json", found.files["run.json"], tarfile.REGTYPE), + (bundle.MANIFEST, listing, tarfile.REGTYPE)])) + short = tmp_path / "short.tgz" + short.write_bytes(_tar([(bundle.MANIFEST, listing, tarfile.REGTYPE), + ("run/run.json", found.files["run.json"], tarfile.REGTYPE)])) + + assert "the first member is run/run.json, not bundle.json" in _import( + monkeypatch, capsysbinary, dst, first)[2] + assert "bundle.json lists run/arms.v1.json, which the bundle does not hold" in _import( + monkeypatch, capsysbinary, dst, short)[2] + + +def test_expect_previous_that_does_not_hold_exits_4_with_the_run_imported(src, dst, tmp_path, monkeypatch, + capsysbinary): + # docs/runs.md: --expect-previous is the pointer's compare-and-swap, as in runs baseline save + path = _export(monkeypatch, capsysbinary, tmp_path) + + code, out, _ = _import(monkeypatch, capsysbinary, dst, path, "--as", "main", "--expect-previous", OTHER, + "--json") + + doc = json.loads(out) + assert (code, doc["status"], doc["verdict"], doc["reason"]) == (4, "failed", "invalid", "stale_baseline") + assert (doc["data"]["expected"], doc["data"]["found"], doc["data"]["written"]) == (OTHER, None, True) + assert (dst / "results" / "nightly-7" / "run.json").is_file() + assert not (dst / "results" / ".baselines" / "main").exists() + + +@pytest.mark.parametrize("flags, message", [ + (("--expect-previous", RUN), "--expect-previous needs --as NAME"), + (("--as=bad.",), "'bad.' is not a baseline name: a segment ends in '.'"), + (("--as", "main", "--expect-previous", "not/a run"), "--expect-previous 'not/a run' is not a run id"), +]) +def test_bad_baseline_flags_are_refused_before_anything_is_written(src, dst, tmp_path, monkeypatch, capsysbinary, + flags, message): + path = _export(monkeypatch, capsysbinary, tmp_path) + + code, _, err = _import(monkeypatch, capsysbinary, dst, path, *flags) + + assert code == 2 + assert message in err + assert not (dst / "results").exists() + + +def test_as_a_name_that_differs_only_in_case_is_refused_before_the_run_is_written( + src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: a bad --as name exits 2 before anything is written; runs baseline save refuses Main beside main + path = _export(monkeypatch, capsysbinary, tmp_path) + _import(monkeypatch, capsysbinary, dst, path, "--as", "main") + (dst / "results" / "nightly-7").rename(dst / "moved") + + code, _, err = _import(monkeypatch, capsysbinary, dst, path, "--as", "Main") + + assert (code, err) == (2, "Error: baseline Main differs from baseline main only in case, which Windows " + "and macOS read as one name\n") + assert not (dst / "results" / "nightly-7").exists() + + +@pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="POSIX modes; root writes anyway") +def test_a_store_that_cannot_be_locked_is_refused_before_the_run_is_written(src, dst, tmp_path, monkeypatch, + capsysbinary): + # install() takes .baselines/.lock first: a read-only store, where no .lock can be made, writes no run + path = _export(monkeypatch, capsysbinary, tmp_path) + store = dst / "results" / ".baselines" + store.mkdir(parents=True) + store.chmod(0o555) + try: + code, out, _ = _import(monkeypatch, capsysbinary, dst, path, "--as", "main", "--json") + finally: + store.chmod(0o755) + + doc = json.loads(out) + assert (code, doc["status"], doc["error"]["code"]) == (2, "failed", "input") + assert doc["error"]["message"] == "results/.baselines/: cannot lock: Permission denied" + assert sorted(os.listdir(dst / "results")) == [".baselines"] + + +def test_a_missing_runs_dir_is_refused_not_made(src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: only the default results/ is made; a DOKIMI_RUNS_DIR that does not exist is refused + path = _export(monkeypatch, capsysbinary, tmp_path) + monkeypatch.setenv("DOKIMI_RUNS_DIR", str(tmp_path / "nowhere")) + + code, _, err = _run(monkeypatch, capsysbinary, "import", str(path)) + + assert code == 2 + assert "does not exist" in err + assert not (tmp_path / "nowhere").exists() + + +def test_a_write_that_fails_exits_5_and_leaves_no_staging_directory(src, dst, tmp_path, monkeypatch, + capsysbinary): + path = _export(monkeypatch, capsysbinary, tmp_path) + + def full(self, data): + raise OSError(28, "No space left on device") + + monkeypatch.setattr(Path, "write_bytes", full) + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 5 + assert err == f"Error: run {RUN}: cannot write: No space left on device\n" + assert os.listdir(dst / "results") == [".baselines"] # the import's lock, and no run + + +def test_a_run_being_imported_is_not_seen_before_it_is_whole(src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: a reader sees all of an imported run or none, also while the import writes it + path = _export(monkeypatch, capsysbinary, tmp_path) + rename, seen = os.rename, [] + + def scanned_first(staging, target): + seen.append(sorted(a.path.as_posix() for a in scan(dst / "results").artifacts)) + rename(staging, target) + + monkeypatch.setattr(bundle.os, "rename", scanned_first) + code, _, _ = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 0 + assert seen == [[]] + assert {a.run_id for a in scan(dst / "results").artifacts} == {RUN} + + +def _resigned(found: bundle.Bundle, artifacts: list[dict] | None = None, + files: dict[str, bytes] | None = None) -> bytes: + """``found`` with ``artifacts`` added to run.json and ``files`` to the run, bundle.json re-signed.""" + record = json.loads(found.files["run.json"]) + record["artifacts"] += artifacts or [] + return _rebuilt(found, {**found.files, **(files or {}), "run.json": json.dumps(record).encode()}) + + +@pytest.mark.parametrize("path", ["sub/run.json", "copy.json"]) +def test_a_run_json_that_lists_a_second_run_record_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary, + path): + # rundir writes one run record, run.json: a second one is a run export could never write again + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + bad = tmp_path / "two-records.tgz" + bad.write_bytes(_resigned(found, [{"kind": "run", "path": path}], {path: found.files["run.json"]})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + assert "run.json lists a run record: a run directory holds one, its run.json" in err + assert not (dst / "results").exists() + + +@pytest.mark.parametrize("parent, child", [("x.json", "x.json/y.json"), ("X.json", "x.json/y.json")]) +def test_a_file_and_a_path_under_it_are_refused_before_anything_is_written(src, dst, tmp_path, monkeypatch, + capsysbinary, parent, child): + # docs/runs.md exit codes: a run that fails a check exits 2; 5 is a run that could not be written + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + arms = found.files["arms.v1.json"] + bad = tmp_path / "prefix.tgz" + bad.write_bytes(_resigned(found, [{"kind": "arms", "path": parent}, {"kind": "arms", "path": child}], + {parent: arms, child: arms})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + assert f"{parent} is a file, so {child} cannot be a file under it" in err + assert not (dst / "results").exists() + + +def test_paths_that_are_one_name_once_unicode_normalized_are_refused(src, dst, tmp_path, monkeypatch, + capsysbinary): + # macOS reads the NFC and the NFD spelling of a name as one file, after both were checked + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + arms, composed, decomposed = found.files["arms.v1.json"], "\u00e9.json", "e\u0301.json" + bad = tmp_path / "nfd.tgz" + bad.write_bytes(_resigned(found, [{"kind": "arms", "path": composed}, {"kind": "arms", "path": decomposed}], + {composed: arms, decomposed: arms})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + assert "differ only in Unicode normalization, which macOS reads as one file" in err + assert not (dst / "results").exists() + + +@pytest.mark.parametrize("first, second", [("Sub/a.json", "sub/b.json"), ("d/\u00e9/a.json", "d/e\u0301/b.json")], + ids=["case", "normalization"]) +def test_two_spellings_of_one_directory_are_refused(src, dst, tmp_path, monkeypatch, capsysbinary, first, second): + # macOS and Windows write both into one directory, so a second import would find a file it does not list + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + arms = found.files["arms.v1.json"] + bad = tmp_path / "spellings.tgz" + bad.write_bytes(_resigned(found, [{"kind": "arms", "path": first}, {"kind": "arms", "path": second}], + {first: arms, second: arms})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + one, two = sorted(path.rsplit("/", 1)[0] for path in (first, second)) # a bundle lists its files sorted + assert f"spells the directory {one} as {two}, which Windows and macOS read as one directory" in err + assert not (dst / "results").exists() + + +def test_a_runs_root_that_cannot_be_made_exits_5_with_one_line(src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md exit codes: a run that could not be written exits 5 with a message, not a traceback + path = _export(monkeypatch, capsysbinary, tmp_path) + + def denied(self, *args, **kwargs): + raise PermissionError(13, "Permission denied", str(self)) + + monkeypatch.setattr(Path, "mkdir", denied) + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 5 + assert err == "Error: runs root results: cannot make it: Permission denied\n" + + +def test_export_refuses_a_run_whose_bundle_json_is_past_the_size_import_reads(src, dst, tmp_path, monkeypatch, + capsysbinary): + # collect(): an export never writes a bundle.json past the cap import reads it under + size = len(bundle._manifest_bytes(bundle.collect(src, RUN).bundle)) + monkeypatch.setattr(bundle, "_MAX_MANIFEST", size - 1) + + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert (code, out) == (2, b"") + assert f"its bundle.json would be {size:,} bytes, past the {size - 1:,} an import reads" in err + monkeypatch.setattr(bundle, "_MAX_MANIFEST", size) # at the cap, export and import both take it + code, _, err = _import(monkeypatch, capsysbinary, dst, _export(monkeypatch, capsysbinary, tmp_path)) + assert code == 0, err + + +def _rekinded(found: bundle.Bundle, kind: str) -> bytes: + record = json.loads(found.files["run.json"]) + record["artifacts"] = [{**a, "kind": kind} if a["kind"] == "arms" else a for a in record["artifacts"]] + return _rebuilt(found, {**found.files, "run.json": json.dumps(record).encode()}) + + +@pytest.mark.parametrize("make, message", [ + (lambda found: _rebuilt(found, {**found.files, "notes.sh": b"#!/bin/sh\necho unchecked\n"}), + "notes.sh is not an artifact run.json lists"), + (lambda found: _rekinded(found, "nonesuch"), "run.json lists an artifact of the unknown kind 'nonesuch'"), + (lambda found: _resigned(found, [{"kind": "arms", "path": "arms.v1.json"}]), "run.json lists one path twice"), +]) +def test_a_resigned_run_json_that_does_not_match_its_files_is_refused(src, dst, tmp_path, monkeypatch, + capsysbinary, make, message): + # docs/runs.md: run.json lists exactly the bundle's files, each a valid artifact of a known kind + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + bad = tmp_path / "relisted.tgz" + bad.write_bytes(make(found)) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + assert message in err + assert not (dst / "results").exists() + + +@pytest.mark.parametrize("path", ["arms?.json", "a.json", 'a"b.json', "a|b.json", "a*.json", "CON.json", + "sub/nul.json", "com1.json", "LPT9", "aux .json", "CONIN$.json", + "conout$", "com\u00b9.json", "LPT\u00b3.txt"]) +def test_a_path_windows_cannot_write_is_refused_before_anything_is_written(src, dst, tmp_path, monkeypatch, + capsysbinary, path): + # a bundle made on Linux must unpack on Windows: no character it refuses, no device name (CON, NUL) + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + bad = tmp_path / "windows.tgz" + bad.write_bytes(_resigned(found, [{"kind": "arms", "path": path}], {path: found.files["arms.v1.json"]})) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + assert f"the path {path!r} would leave the run directory or cannot name a file on every platform" in err + assert not (dst / "results").exists() + + +@pytest.mark.parametrize("path", ["CONSOLE.json", "nullable.json", "com10.json", "lpt.json", "sub/aux-1.json"]) +def test_names_that_only_start_like_a_windows_device_are_taken(path): + assert bundle.safe_path(path) + + +@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot make the run's directory 'con'") +def test_a_run_named_as_a_windows_device_is_refused_at_export(tmp_path, monkeypatch, capsysbinary): + # the run's name names its directory: CON is one run.v1 allows and Windows cannot make + _make_run(tmp_path / "src", monkeypatch, name="con") + monkeypatch.setenv("DOKIMI_RUNS_DIR", str(tmp_path / "src")) + + code, out, err = _run(monkeypatch, capsysbinary, "export", RUN) + + assert (code, out) == (2, b"") + assert f"run {RUN}: the run's directory 'con' cannot be made on every platform" in err + + +@pytest.mark.parametrize("names", [("nightly-7", "copy-7"), ("nightly-7", "nightly-7")]) +def test_two_imports_of_one_run_at_once_write_it_once(src, tmp_path, monkeypatch, capsysbinary, names): + # the second import scans for the run_id only once the first has renamed its run into place + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + root = tmp_path / "dst" + root.mkdir() + first_scanned, second_done = threading.Event(), threading.Event() + real_scan = bundle.scan + + def slow_scan(path): + result = real_scan(path) + if threading.current_thread().name == "first": + first_scanned.set() + second_done.wait(1) # without the lock the second import writes its run here + return result + + monkeypatch.setattr(bundle, "scan", slow_scan) + outcomes: dict[str, object] = {} + + def run(name: str, directory: str) -> None: + try: + outcomes[name] = bundle.install(root, dataclasses.replace(found, name=directory)).written + except InputError as exc: + outcomes[name] = str(exc) + if name == "second": + second_done.set() + + first = threading.Thread(target=run, args=("first", names[0]), name="first") + first.start() + assert first_scanned.wait(5) + second = threading.Thread(target=run, args=("second", names[1]), name="second") + second.start() + first.join(5) + second.join(5) + + assert outcomes["first"] is True + assert (outcomes["second"] is False if names[0] == names[1] + else "is already under the runs root" in str(outcomes["second"])) + assert [p.name for p in root.rglob("run.json")] == ["run.json"] + + +def test_an_import_that_cannot_lock_the_root_writes_nothing(src, dst, tmp_path, monkeypatch, capsysbinary): + # install() takes .baselines/.lock before it looks for the run_id: no lock, no run written + path = _export(monkeypatch, capsysbinary, tmp_path) + (dst / "results").mkdir() + (dst / "results" / ".baselines").write_text("not a store\n", encoding="utf-8") + + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 2 + assert err == "Error: results/.baselines/: cannot lock: not a directory\n" + assert sorted(p.name for p in (dst / "results").iterdir()) == [".baselines"] + + +def test_a_runs_root_another_import_makes_meanwhile_is_taken(src, dst, tmp_path, monkeypatch, capsysbinary): + # two imports on a fresh runner: both find no results/, the other one makes it first + path = _export(monkeypatch, capsysbinary, tmp_path) + real_exists = RunsRoot.exists + + def made_by_another(self): + found = real_exists(self) + (dst / "results").mkdir(exist_ok=True) + return found + + monkeypatch.setattr(RunsRoot, "exists", made_by_another) + code, _, err = _import(monkeypatch, capsysbinary, dst, path) + + assert code == 0, err + assert (dst / "results" / "nightly-7" / "run.json").is_file() + + +def _reordered(found: bundle.Bundle, path: str) -> bytes: + """``found`` with the file at ``path`` written with its keys sorted, so it no longer opens with schema_version.""" + data = json.loads(found.files[path]) + return _rebuilt(found, {**found.files, path: json.dumps(data, sort_keys=True).encode()}) + + +def _renamed_arms(found: bundle.Bundle) -> bytes: + record = json.loads(found.files["run.json"]) + record["artifacts"] = [{**a, "path": "arms.v1.txt"} if a["kind"] == "arms" else a for a in record["artifacts"]] + files = {p: d for p, d in found.files.items() if p != "arms.v1.json"} + return _rebuilt(found, {**files, "arms.v1.txt": found.files["arms.v1.json"], "run.json": json.dumps(record).encode()}) + + +@pytest.mark.parametrize("make, path", [ + (lambda found: _reordered(found, "run.json"), "run.json"), + (lambda found: _reordered(found, "arms.v1.json"), "arms.v1.json"), + (lambda found: _rebuilt(found, {**found.files, "arms.v1.json": b" " * 300 + found.files["arms.v1.json"]}), + "arms.v1.json"), + (_renamed_arms, "arms.v1.txt"), +]) +def test_an_artifact_runs_list_would_not_find_is_refused(src, dst, tmp_path, monkeypatch, capsysbinary, make, path): + # scan() finds an artifact by its name and first bytes: one it skips leaves a run export cannot find + found = bundle.read(_export(monkeypatch, capsysbinary, tmp_path)) + bad = tmp_path / "unfindable.tgz" + bad.write_bytes(make(found)) + + code, _, err = _import(monkeypatch, capsysbinary, dst, bad) + + assert code == 2 + assert f"{path} is a" in err and "artifact runs list would not find" in err + assert not (dst / "results").exists() + + +def test_a_pointer_that_cannot_be_written_exits_5_with_the_run_imported(src, dst, tmp_path, monkeypatch, + capsysbinary): + # docs/runs.md: a store that refuses the save is 2, a pointer the disk cannot take is 5 + path = _export(monkeypatch, capsysbinary, tmp_path) + + def full(*args, **kwargs): + raise OSError(28, "No space left on device") + + monkeypatch.setattr("dokimi.runs.baseline.write_text_atomic", full) + code, _, err = _import(monkeypatch, capsysbinary, dst, path, "--as", "main") + + assert code == 5 + assert err == f"Error: run {RUN} is imported, but baseline main: cannot write: No space left on device\n" + assert (dst / "results" / "nightly-7" / "run.json").is_file() + assert not (dst / "results" / ".baselines" / "main").exists() + + +def test_a_save_the_store_refuses_after_the_write_exits_2_with_the_run_imported(src, dst, tmp_path, monkeypatch, + capsysbinary): + # docs/runs.md: a case twin saved between the import's write and its save is refused by the store (2) + path = _export(monkeypatch, capsysbinary, tmp_path) + real_install = bundle.install + + def install_then_twin(root, found): + installed = real_install(root, found) + baseline.save(root, "Main", found.run_id, None) # another job, meanwhile + return installed + + monkeypatch.setattr(bundle, "install", install_then_twin) + code, out, _ = _import(monkeypatch, capsysbinary, dst, path, "--as", "main", "--json") + + doc = json.loads(out) + assert (code, doc["status"], doc["error"]["code"]) == (2, "failed", "input") + assert doc["error"]["message"].startswith(f"run {RUN} is imported, but ") + assert "only in case" in doc["error"]["message"] + assert (doc["data"]["written"], doc["data"]["path"]) == (True, "nightly-7")