From 2c3ccfc4dfcb734ddffcffe1f5310d843139819e Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 12:58:15 -0700 Subject: [PATCH 01/29] feat(runs): runs export | import, a verified bundle of a run directory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A baseline pointer under results/ goes with the ephemeral CI runner that made it (#94 §2.3). `runs export RUN|baseline:NAME > bundle.tgz` writes the run directory (run.json, its plan, result and the artifacts it lists) as a gzipped tar led by bundle.json (run_bundle.v1), which gives the run's address, the plan_digest and the result's sha256, and the sha256 and size of every file. The tar holds no time, owner or mode, so one run always exports to the same bytes. `runs import BUNDLE [--as NAME [--expect-previous RUN_ID]]` reads it into memory and writes nothing until it holds: only regular members at the paths bundle.json lists (no links, devices, FIFOs, directories, absolute or `..` paths, or paths equal but for case), each with its hash, under a 256 MiB cap on the unpacked stream; run.json lists exactly the files, each artifact passes its schema and carries the run's run_id, the result names the plan's digest. The run goes to / through a staging directory and a rename; the same run already there is a no-op, another run with the run_id or a taken directory exits 2. --as points a baseline at it through runs/baseline.py's save, with --expect-previous as a compare-and-swap (exit 4). Refs #94 Signed-off-by: Vladislav Perevezentsev --- ...0_vlad-perevezentsev_runs-export-import.md | 16 + dokimi/docs/reference/cli-interface.json | 23 + dokimi/docs/run-directories.md | 7 +- dokimi/docs/runs.md | 82 +++- dokimi/dokimi/cli_flags.py | 1 + dokimi/dokimi/cli_routes.py | 2 + dokimi/dokimi/commands/runs.py | 3 +- dokimi/dokimi/commands/runs_bundle.py | 156 ++++++ dokimi/dokimi/runs/bundle.py | 447 ++++++++++++++++++ dokimi/dokimi/schemas/run_bundle.v1.json | 30 ++ .../fixtures/artifacts/run_bundle.v1.json | 29 ++ dokimi/tests/test_cli_output.py | 2 +- dokimi/tests/test_runs_bundle.py | 441 +++++++++++++++++ 13 files changed, 1231 insertions(+), 8 deletions(-) create mode 100644 dokimi/changelog.d/20261201_120000_vlad-perevezentsev_runs-export-import.md create mode 100644 dokimi/dokimi/commands/runs_bundle.py create mode 100644 dokimi/dokimi/runs/bundle.py create mode 100644 dokimi/dokimi/schemas/run_bundle.v1.json create mode 100644 dokimi/tests/fixtures/artifacts/run_bundle.v1.json create mode 100644 dokimi/tests/test_runs_bundle.py 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..0cb8cb879 --- /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; one run always exports to the same + bytes. `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 61dac17ee..5bf77a6bc 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -1761,6 +1761,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": [ @@ -1774,6 +1784,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 84e1f0922..2ed3ee0e9 100644 --- a/dokimi/docs/run-directories.md +++ b/dokimi/docs/run-directories.md @@ -13,9 +13,10 @@ SPDX-License-Identifier: Apache-2.0 A run directory keeps one run's record, plan, result and artifacts together, and 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`. No command writes -a run directory yet: the command families move to it one by one in later PRs -(arms first), each with its `--out-dir` and a run name. +The module that writes it is `dokimi/runs/rundir.py`. No command runs +into a run directory yet: the command families move to it one by one in later PRs +(arms first), 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 3c564219f..95e6e2bd8 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` @@ -19,8 +21,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. @@ -301,6 +304,74 @@ 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 ...`). 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), 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 a run always exports to the same bytes: the same run exported on two + machines is one file. +- **`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 `:`, a segment that ends in `.` or a space, and two + paths that differ only in case (one file on Windows and macOS) 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` 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); 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. `results/` + is made when it is missing (a fresh runner); 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. +- **`--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, an `--expect-previous` that is not a run + id or comes without `--as` exit 2 before anything is written. +- `--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. A workflow that needs that compares the address an +import prints with the one its export printed, or keeps the bundle where a pull request cannot +write. + ## Exit codes | Case | Exit | @@ -318,6 +389,11 @@ 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 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 `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 diff --git a/dokimi/dokimi/cli_flags.py b/dokimi/dokimi/cli_flags.py index fa2762805..a933c35d0 100644 --- a/dokimi/dokimi/cli_flags.py +++ b/dokimi/dokimi/cli_flags.py @@ -142,6 +142,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 66f5bdb28..a317ea88b 100644 --- a/dokimi/dokimi/cli_routes.py +++ b/dokimi/dokimi/cli_routes.py @@ -194,6 +194,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 2e13fafb1..6dab58641 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..60a04469d --- /dev/null +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -0,0 +1,156 @@ +# 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 +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) + + +def _import_root() -> 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(): + root.path.mkdir() + 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 _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``.""" + 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 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 + root = _import_root() + 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..e1e29029f --- /dev/null +++ b/dokimi/dokimi/runs/bundle.py @@ -0,0 +1,447 @@ +# 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 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 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]") # run.v1's artifact paths have none of them +_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), no ``\\``, ``:`` or control + character.""" + return not _UNSAFE.search(path) and all(part and not part.endswith((".", " ")) for part in path.split("/")) + + +def _check_paths(paths: Iterable[str], where: str) -> None: + """Raise ``InputError`` for a path :func:`safe_path` refuses, and for two that differ only in case: + Windows and macOS would write both to one file, after both were checked.""" + 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)") + other = folded.setdefault(path.casefold(), path) + if other != path: + raise InputError(f"{where}: {plain(path)} and {plain(other)} differ only in case, which Windows " + "and macOS read as one file") + + +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 + 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}") + 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") + 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 _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 bytes + 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 bytes.""" + text = json.dumps(manifest(bundle), indent=2) + "\n" + 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, text.encode("utf-8")) + 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) and the artifacts that + carry its run_id but are not in it (run.json does not list them).""" + + bundle: Bundle + directory: Path + left_out: 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) + held = {record.parent / path for path in bundle.files} + return Collected(bundle, record.parent, [p for p in carried if p not in held]) + + +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 _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 + 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}") + _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: + 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 (OSError, EOFError, 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 _holds(directory: Path, bundle: Bundle) -> bool: + """Whether every file of ``bundle`` is a regular file in ``directory`` with the same bytes.""" + for path, data in bundle.files.items(): + try: + if not stat.S_ISREG(os.lstat(directory / path).st_mode) or (directory / path).read_bytes() != data: + return False + except OSError: + return False + return True + + +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. + + Raises ``InputError`` when another run has the bundle's run_id under ``root`` (an import never + replaces a run) or the directory holds something, and ``OSError`` when the run cannot be written. + """ + 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} + if _holds(target, bundle) and all(path in held for path in carried): + return Installed(target.relative_to(root), False) + raise InputError(f"run {bundle.run_id} is already under the runs root ({plain(carried[0].as_posix())}) and " + "differs from the bundle's: an import never replaces a run (runs rm removes it)") 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/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 3f6ffcf50..0e4eca03d 100644 --- a/dokimi/tests/test_cli_output.py +++ b/dokimi/tests/test_cli_output.py @@ -638,7 +638,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..08f6bb7e6 --- /dev/null +++ b/dokimi/tests/test_runs_bundle.py @@ -0,0 +1,441 @@ +# 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 +from pathlib import Path + +import pytest + +from dokimi import cli +from dokimi.artifacts import save_artifact +from dokimi.runs import bundle +from dokimi.runs.rundir import open_run + +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)" + + +@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 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")) == ["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.startswith(f"Error: run {RUN} is already under the runs root (") + assert json.loads(changed.read_text(encoding="utf-8"))["model"] == "another" + + +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 + + +@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_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_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") == [] From e0befaf8100fbaef19b4dbac3d5a9ed121d9895e Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:24:22 -0700 Subject: [PATCH 02/29] docs(runs): indent the import checks as a nested list mkdocs reads mkdocs build --strict read the three checks under runs import at depth 1 while GitHub reads them at depth 2: indent them 4 spaces, with a blank line before and after the nested list. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 95e6e2bd8..3286e077d 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -337,16 +337,18 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none machines is one file. - **`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 `:`, a segment that ends in `.` or a space, and two - paths that differ only in case (one file on Windows and macOS) 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` 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); the result's `plan_digest` is the digest of the plan beside it; - and `bundle.json`'s run and address are the run's. + + - 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 `:`, a segment that ends in `.` or a space, and two + paths that differ only in case (one file on Windows and macOS) 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` 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); 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. `results/` From 98d8986efd1106f6abc5becb47a6810789501b15 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:25:47 -0700 Subject: [PATCH 03/29] fix(runs): refuse a bad --as store before runs import writes the run A name that differs from a saved baseline only in case, or a .baselines/ that is a link or cannot be locked, was refused by baseline.save only after the run was written, with a message that did not say so. Check them through baseline.listed before the write, and report a save that still refuses after it (a read-only store) as "run X is imported, but ..." with the import's data. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 7 ++++-- dokimi/dokimi/commands/runs_bundle.py | 21 ++++++++++++++++- dokimi/tests/test_runs_bundle.py | 33 +++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 3 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 3286e077d..794648792 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -362,8 +362,11 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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, an `--expect-previous` that is not a run - id or comes without `--as` exit 2 before anything is written. + 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. A save that + fails only once the run is written (a read-only `.baselines/`, which is read without a lock) + exits 2 too, and says 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`) diff --git a/dokimi/dokimi/commands/runs_bundle.py b/dokimi/dokimi/commands/runs_bundle.py index 60a04469d..329a04ffb 100644 --- a/dokimi/dokimi/commands/runs_bundle.py +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -14,7 +14,7 @@ from dokimi import cli_flags from dokimi.artifacts import is_run_id -from dokimi.exit_codes import EXIT_INFRA, EXIT_INVALID +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 @@ -64,6 +64,20 @@ def _check_baseline_flags(args: argparse.Namespace) -> None: 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: @@ -81,6 +95,7 @@ def _infra(args: argparse.Namespace, data: dict, message: str) -> NoReturn: 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: @@ -88,6 +103,9 @@ def _point(args: argparse.Namespace, root: Path, run_id: str, data: dict) -> bas 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}") @@ -98,6 +116,7 @@ def cmd_runs_import(args: argparse.Namespace) -> None: 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() data: dict[str, Any] = { "root": root.as_posix(), "run_id": found.run_id, "path": None, "written": False, diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 08f6bb7e6..c23572b7f 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -414,6 +414,39 @@ def test_bad_baseline_flags_are_refused_before_anything_is_written(src, dst, tmp 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_save_cannot_lock_says_the_run_is_imported(src, dst, tmp_path, monkeypatch, capsysbinary): + # docs/runs.md: a read-only .baselines/ is read without a lock, so only the save after the write refuses + 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"].startswith(f"run {RUN} is imported, but ") + assert "cannot lock" in doc["error"]["message"] + assert (doc["data"]["written"], doc["data"]["path"]) == (True, "nightly-7") + + 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) From 46829bba721f7c1ebd1822b62a67d8a56a5fc134 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:27:58 -0700 Subject: [PATCH 04/29] test(runs): pin export's refusals, a bundle with no result, a run with no name Export of a run whose listed file is missing, a symlink, a FIFO, behind a link out of the directory, unreadable or over the cap exits 2 with nothing on stdout; a re-signed bundle whose run.json lists no result is refused; a run with no name goes to /, and --as --json carries data.baseline. Signed-off-by: Vladislav Perevezentsev --- dokimi/tests/test_runs_bundle.py | 98 ++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index c23572b7f..b9f6edc97 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -185,6 +185,104 @@ def test_export_refuses_a_terminal_and_a_missing_baseline(src, monkeypatch, caps 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" + + +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) From 6316d06222a5e7848cfedc901a2625c009aac0bb Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:29:08 -0700 Subject: [PATCH 05/29] fix(runs): refuse at export a run whose bundle.json import would refuse verified() did not apply run_bundle.v1's caps (1000 files, a path of 1024 characters), so a run past them exported fine and no import could read its bundle. collect() now checks the manifest against the schema, as import checks it first. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 3 ++- dokimi/dokimi/runs/bundle.py | 14 ++++++++++---- dokimi/tests/test_runs_bundle.py | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 794648792..194276b1a 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -328,7 +328,8 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none left out and named (`left out: 1 artifact ...`). 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), and a stdout that is a terminal. + 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), 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 diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index e1e29029f..a39c87eeb 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -270,6 +270,7 @@ def collect(root: Path, run_id: str) -> Collected: 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 held = {record.parent / path for path in bundle.files} return Collected(bundle, record.parent, [p for p in carried if p not in held]) @@ -311,16 +312,21 @@ def _member_bytes(tar: tarfile.TarFile, member: tarfile.TarInfo, budget: int, wh 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 - 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}") + _check_manifest(document, where) _check_paths([entry["path"] for entry in document["files"]], where) return dict(document) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index b9f6edc97..5f2dafcc3 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -227,6 +227,22 @@ def test_export_refuses_a_listed_file_it_cannot_take_and_writes_nothing(src, tmp 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 From 08f9b51173658175747407bb69a10d567626638a Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:29:41 -0700 Subject: [PATCH 06/29] fix(runs): name the file that makes an existing run differ from the bundle The refusal named the newest artifact with the run_id, which may be identical to the bundle's. Name the first artifact with the run_id the bundle does not hold, else the first bundle file the directory does not hold as it is. Signed-off-by: Vladislav Perevezentsev --- dokimi/dokimi/runs/bundle.py | 23 ++++++++++++++--------- dokimi/tests/test_runs_bundle.py | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index a39c87eeb..2aca76e3e 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -396,15 +396,16 @@ class Installed: written: bool -def _holds(directory: Path, bundle: Bundle) -> bool: - """Whether every file of ``bundle`` is a regular file in ``directory`` with the same bytes.""" - for path, data in bundle.files.items(): +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 False + return path except OSError: - return False - return True + return path + return None def _is_empty_dir(path: Path) -> bool: @@ -447,7 +448,11 @@ def install(root: Path, bundle: Bundle) -> Installed: _publish(target, bundle) return Installed(target.relative_to(root), True) held = {Path(bundle.directory) / path for path in bundle.files} - if _holds(target, bundle) and all(path in held for path in carried): + 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) - raise InputError(f"run {bundle.run_id} is already under the runs root ({plain(carried[0].as_posix())}) and " - "differs from the bundle's: an import never replaces a run (runs rm removes it)") + 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/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 5f2dafcc3..4c8bbe4a8 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -325,10 +325,25 @@ def test_import_refuses_a_different_run_with_the_same_run_id(src, dst, tmp_path, code, _, err = _import(monkeypatch, capsysbinary, dst, path) assert code == 2 - assert err.startswith(f"Error: run {RUN} is already under the runs root (") + 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 From a26e805f63e1e0ba15d479059f3907851071e236 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:30:04 -0700 Subject: [PATCH 07/29] fix(runs): refuse a bundle that is not a regular file instead of waiting runs import opened BUNDLE before looking at it, so a FIFO with no writer blocked for good. Stat it first and refuse what is not a regular file, as runs show does. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 2 +- dokimi/dokimi/runs/bundle.py | 2 ++ dokimi/tests/test_runs_bundle.py | 11 +++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 194276b1a..95a2d791b 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -397,7 +397,7 @@ write. | `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 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 `DOKIMI_RUNS_DIR` that does not exist, a bad `--as` or `--expect-previous`, or `--expect-previous` without `--as` | 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 `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 | diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 2aca76e3e..b94fae2c5 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -368,6 +368,8 @@ def read(path: Path) -> Bundle: """ 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 diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 4c8bbe4a8..879a01630 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -496,6 +496,17 @@ def test_a_file_that_is_no_bundle_is_refused(dst, tmp_path, monkeypatch, capsysb assert message 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() From c2ecc42bf86fd86a004b1c26f4a1e3bfe40c21ad Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:30:28 -0700 Subject: [PATCH 08/29] docs(runs): say the bundle's tar is the same, its gzip bytes only per zlib The tar of a run is deterministic, but the .tgz is zlib's deflate output: CPython's Windows builds use zlib-ng, which compresses to other bytes. Name bundle.json (the address and each file's sha256) as what is the same on every machine, in runs.md, the fragment and write(). Signed-off-by: Vladislav Perevezentsev --- ...20261201_120000_vlad-perevezentsev_runs-export-import.md | 4 ++-- dokimi/docs/runs.md | 6 ++++-- dokimi/dokimi/runs/bundle.py | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) 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 index 0cb8cb879..b1bcb6820 100644 --- a/dokimi/changelog.d/20261201_120000_vlad-perevezentsev_runs-export-import.md +++ b/dokimi/changelog.d/20261201_120000_vlad-perevezentsev_runs-export-import.md @@ -5,8 +5,8 @@ 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; one run always exports to the same - bytes. `runs import bundle.tgz` writes nothing until every member is a + `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 diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 95a2d791b..1fd99fddc 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -334,8 +334,10 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none `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 a run always exports to the same bytes: the same run exported on two - machines is one file. + 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: diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index b94fae2c5..bb7d52ec2 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -178,14 +178,15 @@ def manifest(bundle: Bundle) -> dict[str, Any]: 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 bytes + 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 bytes.""" + 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).""" text = json.dumps(manifest(bundle), indent=2) + "\n" with gzip.GzipFile(filename="", mode="wb", fileobj=out, mtime=0) as zipped, \ tarfile.open(fileobj=zipped, mode="w|", format=tarfile.PAX_FORMAT) as tar: From 94d84af2f215231b176102a722925e77cc82518e Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Tue, 1 Dec 2026 13:30:50 -0700 Subject: [PATCH 09/29] fix(runs): refuse a bundle.json that lists one path twice The case check compared a path only with another spelling, and the members were matched through a dict, so a second entry for a path silently replaced the first. Signed-off-by: Vladislav Perevezentsev --- dokimi/dokimi/runs/bundle.py | 11 +++++++---- dokimi/tests/test_runs_bundle.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index bb7d52ec2..3bfb308e6 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -89,16 +89,19 @@ def safe_path(path: str) -> bool: def _check_paths(paths: Iterable[str], where: str) -> None: - """Raise ``InputError`` for a path :func:`safe_path` refuses, and for two that differ only in case: - Windows and macOS would write both to one file, after both were checked.""" + """Raise ``InputError`` for a path :func:`safe_path` refuses, one listed twice, and two that differ + only in case: Windows and macOS would write both to one file, after both were checked.""" 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)") - other = folded.setdefault(path.casefold(), path) - if other != path: + other = folded.get(path.casefold()) + if other == path: + raise InputError(f"{where}: {plain(path)} is listed twice") + folded[path.casefold()] = path + if other is not None: raise InputError(f"{where}: {plain(path)} and {plain(other)} differ only in case, which Windows " "and macOS read as one file") diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 879a01630..7d7e7b903 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -482,6 +482,20 @@ def test_a_file_past_the_cap_names_the_cap(src, dst, tmp_path, monkeypatch, caps 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"), From 86f04c8739c4aa48a9d9b86976b41fd9e0c0bc6e Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:28:41 -0800 Subject: [PATCH 10/29] fix(runs): refuse a bundle whose run.json lists a second run record rundir writes one run record per directory, its run.json, and never lists kind run. Import took such a bundle with exit 0, and the run then could not be exported again ("has 2 run.json files"). It now exits 2. Signed-off-by: Alexander Rybkin --- dokimi/dokimi/runs/bundle.py | 2 ++ dokimi/tests/test_runs_bundle.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 3bfb308e6..f78dc4ce3 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -129,6 +129,8 @@ def _listed(run: dict[str, Any], files: Mapping[str, bytes], where: str) -> dict 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") diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 7d7e7b903..b716c6ec2 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -626,3 +626,26 @@ def full(self, data): assert code == 5 assert err == f"Error: run {RUN}: cannot write: No space left on device\n" assert os.listdir(dst / "results") == [] + + +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() From 34ddd5a69485ca9698c398edcad6ea055b249079 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:29:12 -0800 Subject: [PATCH 11/29] fix(runs): refuse a bundle that holds a file and a path under it A run.json that lists x.json and x.json/y.json passed every check, then failed in the staging write with exit 5 "cannot write: File exists", the exit docs/runs.md keeps for a disk that cannot be written. _check_paths now refuses it with exit 2 before anything is written, also across case. Signed-off-by: Alexander Rybkin --- dokimi/dokimi/runs/bundle.py | 10 ++++++++-- dokimi/tests/test_runs_bundle.py | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index f78dc4ce3..e31676ab2 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -89,8 +89,9 @@ def safe_path(path: str) -> bool: def _check_paths(paths: Iterable[str], where: str) -> None: - """Raise ``InputError`` for a path :func:`safe_path` refuses, one listed twice, and two that differ - only in case: Windows and macOS would write both to one file, after both were checked.""" + """Raise ``InputError`` for a path :func:`safe_path` refuses, one listed twice, two that differ + only in case (Windows and macOS would write both to one file, after both were checked), and one + under another listed path, which no directory can hold.""" folded: dict[str, str] = {} for path in paths: if not safe_path(path): @@ -104,6 +105,11 @@ def _check_paths(paths: Iterable[str], where: str) -> None: if other is not None: raise InputError(f"{where}: {plain(path)} and {plain(other)} differ only in case, which Windows " "and macOS read 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") def _document(files: Mapping[str, bytes], path: str, kind: str, where: str) -> dict[str, Any]: diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index b716c6ec2..4e2acf4f9 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -649,3 +649,20 @@ def test_a_run_json_that_lists_a_second_run_record_is_refused(src, dst, tmp_path 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() From da1cb5c013841d63b4f0a196f7695c6c5fd1bbd4 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:30:13 -0800 Subject: [PATCH 12/29] fix(runs): refuse two bundle paths that macOS reads as one name _check_paths folded case only, so the NFC and NFD spellings of one name both passed, and macOS would write them to one file after both were checked. The key is now NFC, then casefold. docs/runs.md lists this check and the path-under-a-file check. Signed-off-by: Alexander Rybkin --- dokimi/docs/runs.md | 5 +++-- dokimi/dokimi/runs/bundle.py | 13 ++++++++----- dokimi/tests/test_runs_bundle.py | 16 ++++++++++++++++ 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 1fd99fddc..f6a91e0fb 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -343,8 +343,9 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none - 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 `:`, a segment that ends in `.` or a space, and two - paths that differ only in case (one file on Windows and macOS) are refused; + absolute path, a `..` segment, a `\` or `:`, 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), 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` and lists exactly the bundle's diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index e31676ab2..743088031 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -24,6 +24,7 @@ import shutil import stat import tarfile +import unicodedata import zlib from collections.abc import Iterable, Mapping from dataclasses import dataclass, field @@ -90,7 +91,7 @@ def safe_path(path: str) -> bool: 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 (Windows and macOS would write both to one file, after both were checked), and one + 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: @@ -98,13 +99,15 @@ def _check_paths(paths: Iterable[str], where: str) -> None: 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)") - other = folded.get(path.casefold()) + 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[path.casefold()] = path + folded[key] = path if other is not None: - raise InputError(f"{where}: {plain(path)} and {plain(other)} differ only in case, which Windows " - "and macOS read as one file") + 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) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 4e2acf4f9..57e58eda8 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -666,3 +666,19 @@ def test_a_file_and_a_path_under_it_are_refused_before_anything_is_written(src, 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() From 4a9f47eadef97d3546f372fd545e577f6057ab55 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:31:22 -0800 Subject: [PATCH 13/29] fix(runs): exit 5 with one line when runs import cannot make results/ The mkdir of the default runs root ran before the OSError handler of install, so a denied results/ crashed with a traceback. It now goes through the same infra exit as a run that cannot be written. Signed-off-by: Alexander Rybkin --- dokimi/dokimi/commands/runs_bundle.py | 10 +++++++--- dokimi/tests/test_runs_bundle.py | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/dokimi/dokimi/commands/runs_bundle.py b/dokimi/dokimi/commands/runs_bundle.py index 329a04ffb..9af277e18 100644 --- a/dokimi/dokimi/commands/runs_bundle.py +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -44,12 +44,16 @@ def cmd_runs_export(args: argparse.Namespace) -> None: f"does not list (first: {plain(found.left_out[0].as_posix())})", file=sys.stderr) -def _import_root() -> Path: +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(): - root.path.mkdir() + try: + root.path.mkdir() + 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 @@ -117,7 +121,7 @@ def cmd_runs_import(args: argparse.Namespace) -> None: _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() + 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, diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 57e58eda8..0968129bd 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -682,3 +682,17 @@ def test_paths_that_are_one_name_once_unicode_normalized_are_refused(src, dst, t assert code == 2 assert "differ only in Unicode normalization, which macOS reads as one file" 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" From d337d513d8decdd46fd6c25116612ea0075233f9 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:33:14 -0800 Subject: [PATCH 14/29] fix(runs): refuse at export a run whose bundle.json import would not read collect() checked the manifest against its schema caps only, so a run with many long artifact paths exported with exit 0 and a bundle.json over the 1 MiB import reads it under, which import then refused. Export now checks the serialized size write() produces. Signed-off-by: Alexander Rybkin --- dokimi/docs/runs.md | 3 ++- dokimi/dokimi/runs/bundle.py | 11 +++++++++-- dokimi/tests/test_runs_bundle.py | 15 +++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index f6a91e0fb..e41ccfa91 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -329,7 +329,8 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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), and a stdout that is a terminal. + 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 diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 743088031..aa62aaf2a 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -191,6 +191,10 @@ def manifest(bundle: Bundle) -> dict[str, Any]: 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 @@ -201,10 +205,9 @@ 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).""" - text = json.dumps(manifest(bundle), indent=2) + "\n" 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, text.encode("utf-8")) + _add(tar, MANIFEST, _manifest_bytes(bundle)) for path in sorted(bundle.files): _add(tar, PREFIX + path, bundle.files[path]) @@ -286,6 +289,10 @@ def collect(root: Path, run_id: str) -> Collected: 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} return Collected(bundle, record.parent, [p for p in carried if p not in held]) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 0968129bd..f18d87b8c 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -696,3 +696,18 @@ def denied(self, *args, **kwargs): 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 From f2687a719e45fd6e92c6986e725ed155e04c371f Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:33:39 -0800 Subject: [PATCH 15/29] test(runs): pin import's refusal of a run.json that does not match its files A re-signed bundle with a file run.json does not list, an artifact of an unknown kind, or one path listed twice had no test: each check could be dropped with the suite green, and the first lets unchecked bytes into the imported run directory. Signed-off-by: Alexander Rybkin --- dokimi/tests/test_runs_bundle.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index f18d87b8c..9f252a464 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -711,3 +711,29 @@ def test_export_refuses_a_run_whose_bundle_json_is_past_the_size_import_reads(sr 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() From 429944859e54c261b128df466db2ca962f3b7256 Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:34:04 -0800 Subject: [PATCH 16/29] fix(runs): name at export the run directory's files the bundle leaves out The bundle holds run.json and what it lists; the left-out line named only artifacts carrying the run_id, so a report or other file in the run directory stayed behind without a word. Export now names them on a second left-out line, and docs/runs.md says so. Signed-off-by: Alexander Rybkin --- dokimi/docs/runs.md | 4 +++- dokimi/dokimi/commands/runs_bundle.py | 3 +++ dokimi/dokimi/runs/bundle.py | 15 ++++++++++++--- dokimi/tests/test_runs_bundle.py | 13 +++++++++++++ 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index e41ccfa91..9c57900f4 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -325,7 +325,9 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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 ...`). It refuses, and writes nothing to stdout, a + 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 diff --git a/dokimi/dokimi/commands/runs_bundle.py b/dokimi/dokimi/commands/runs_bundle.py index 9af277e18..d0915d005 100644 --- a/dokimi/dokimi/commands/runs_bundle.py +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -42,6 +42,9 @@ def cmd_runs_export(args: argparse.Namespace) -> None: 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: diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index aa62aaf2a..917b41df0 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -214,12 +214,14 @@ def write(bundle: Bundle, out: IO[bytes]) -> None: @dataclass(frozen=True) class Collected: - """A run read for export: its bundle, its directory (relative to the root) and the artifacts that - carry its run_id but are not in it (run.json does not list them).""" + """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: @@ -294,7 +296,14 @@ def collect(root: Path, run_id: str) -> Collected: 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} - return Collected(bundle, record.parent, [p for p in carried if p not in held]) + 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): diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 9f252a464..18bd91e96 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -157,6 +157,19 @@ def test_export_names_the_artifacts_of_the_run_it_leaves_out(src, monkeypatch, c 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"), From 5f75c5e16aeab8fcb602a61ceaa887208ed4461a Mon Sep 17 00:00:00 2001 From: Alexander Rybkin Date: Tue, 1 Dec 2026 20:34:13 -0800 Subject: [PATCH 17/29] docs(runs): stop offering the import address as proof of who exported a bundle The address is the plan digest and the result sha256 only. A bundle with run.json or another artifact edited and bundle.json re-signed imports with exit 0 and prints the same address, so comparing it proves nothing there. Signed-off-by: Alexander Rybkin --- dokimi/docs/runs.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 9c57900f4..ea6656021 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -380,9 +380,10 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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. A workflow that needs that compares the address an -import prints with the one its export printed, or keeps the bundle where a pull request cannot -write. +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 From a9609c630f896abd9af5446db59ef99c1f131f6f Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:11:35 -0700 Subject: [PATCH 18/29] fix(runs): refuse bundle paths and run names Windows cannot write A run.v1 artifact path or run name may hold ?, <, >, ", |, * or be a device name such as CON or nul.json, which Linux and macOS write and Windows refuses. Export wrote such a run and import accepted it, then could not write it on Windows (exit 5). safe_path now refuses these characters and device names in every segment, and verified() checks the name of the run's directory with it, so export and import refuse the run (exit 2) before anything is written. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 6 ++++-- dokimi/dokimi/runs/bundle.py | 16 ++++++++++++---- dokimi/tests/test_runs_bundle.py | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index ea6656021..e749ffbbb 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -346,12 +346,14 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none - 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 `:`, a segment that ends in `.` or a space, two + absolute path, a `..` segment, a `\`, `:` or another character Windows refuses in a name + (`<>"|?*`), a Windows device name (`CON`, `nul.json`), 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), 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` and lists exactly the bundle's + - 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); the result's `plan_digest` is the digest of the plan beside it; and `bundle.json`'s run and address are the run's. diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 917b41df0..99f651a08 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -53,7 +53,9 @@ _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]") # run.v1's artifact paths have none of them +_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. +_DEVICES = frozenset({"CON", "PRN", "AUX", "NUL", *(f"{p}{d}" for p in ("COM", "LPT") for d in range(10))}) _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"} @@ -84,9 +86,11 @@ def _sha256(data: bytes) -> str: 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), no ``\\``, ``:`` or control - character.""" - return not _UNSAFE.search(path) and all(part and not part.endswith((".", " ")) for part in path.split("/")) + 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: @@ -168,6 +172,10 @@ def verified(files: Mapping[str, bytes], where: str) -> Bundle: 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(): diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 18bd91e96..5ca6ab5b3 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -750,3 +750,35 @@ def test_a_resigned_run_json_that_does_not_match_its_files_is_refused(src, dst, 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"]) +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) + + +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 From 7f3813f0e419d1eb9323dfb409e20f65ebac50d8 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:13:44 -0700 Subject: [PATCH 19/29] fix(runs): one import at a time looks for a run_id and writes its run install() scanned the root for the bundle's run_id and then renamed the run into place with nothing held between the two. Two imports of one run under two names both found no run, and both wrote it: two run.json files for one run_id, which export then refuses. Two imports under one name made the second fail with exit 5 (Directory not empty) instead of the no-op an identical run is. install() now holds .baselines/.lock, the lock baseline saves take, from the scan to the rename, so the second import finds the first's run. A store that cannot be locked (a read-only .baselines/) now refuses the import before the run is written; it was refused only by the save after it. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 12 +++--- dokimi/dokimi/runs/bundle.py | 12 +++++- dokimi/tests/test_runs_bundle.py | 70 ++++++++++++++++++++++++++++---- 3 files changed, 80 insertions(+), 14 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index e749ffbbb..ad64b2ed4 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -360,7 +360,9 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none - **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. `results/` + 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); 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 @@ -374,8 +376,8 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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. A save that - fails only once the run is written (a read-only `.baselines/`, which is read without a lock) - exits 2 too, and says the run is imported (`run ... is imported, but ...`). + fails only once the run is written (a baseline whose name differs only in case, saved + meanwhile) exits 2 too, and says 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`) @@ -406,13 +408,13 @@ pull request cannot write. | `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 `DOKIMI_RUNS_DIR` that does not exist, a bad `--as` or `--expect-previous`, or `--expect-previous` without `--as` | 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/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 99f651a08..1492dd72d 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -480,9 +480,17 @@ def _publish(target: Path, bundle: Bundle) -> None: def install(root: Path, bundle: Bundle) -> Installed: """Write ``bundle``'s run to ``/``, or nothing when that run is there, identical. - Raises ``InputError`` when another run has the bundle's run_id under ``root`` (an import never - replaces a run) or the directory holds something, and ``OSError`` when the run cannot be written. + 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: diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 5ca6ab5b3..f2d009906 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -13,6 +13,7 @@ import os import sys import tarfile +import threading from pathlib import Path import pytest @@ -21,6 +22,7 @@ from dokimi.artifacts import save_artifact from dokimi.runs import bundle from dokimi.runs.rundir import open_run +from dokimi.utils import InputError FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" RUN = "20261123T101500Z-1a2b3c4d" @@ -324,7 +326,7 @@ def test_import_of_the_run_already_there_writes_nothing(src, dst, tmp_path, monk 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")) == ["nightly-7"] # no staging directory left + 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): @@ -596,8 +598,9 @@ def test_as_a_name_that_differs_only_in_case_is_refused_before_the_run_is_writte @pytest.mark.skipif(sys.platform == "win32" or os.geteuid() == 0, reason="POSIX modes; root writes anyway") -def test_a_store_save_cannot_lock_says_the_run_is_imported(src, dst, tmp_path, monkeypatch, capsysbinary): - # docs/runs.md: a read-only .baselines/ is read without a lock, so only the save after the write refuses +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) @@ -609,9 +612,8 @@ def test_a_store_save_cannot_lock_says_the_run_is_imported(src, dst, tmp_path, m 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 "cannot lock" in doc["error"]["message"] - assert (doc["data"]["written"], doc["data"]["path"]) == (True, "nightly-7") + 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): @@ -638,7 +640,7 @@ def full(self, data): assert code == 5 assert err == f"Error: run {RUN}: cannot write: No space left on device\n" - assert os.listdir(dst / "results") == [] + assert os.listdir(dst / "results") == [".baselines"] # the import's lock, and no run def _resigned(found: bundle.Bundle, artifacts: list[dict] | None = None, @@ -782,3 +784,57 @@ def test_a_run_named_as_a_windows_device_is_refused_at_export(tmp_path, monkeypa 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"] From 85201e4b92e78fcd776f2647ff1357dfeff532ed Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:14:16 -0700 Subject: [PATCH 20/29] fix(runs): runs import takes a results/ another import made meanwhile Two imports on a fresh runner both found no results/; the one that made it second failed with exit 5 (cannot make it: File exists) and wrote no run. _import_root() now makes the default root with exist_ok, so the second goes on; a file at results/ still fails. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 2 +- dokimi/dokimi/commands/runs_bundle.py | 2 +- dokimi/tests/test_runs_bundle.py | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index ad64b2ed4..799bae629 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -363,7 +363,7 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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); a `DOKIMI_RUNS_DIR` that does not exist is + 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 diff --git a/dokimi/dokimi/commands/runs_bundle.py b/dokimi/dokimi/commands/runs_bundle.py index d0915d005..8f33a2683 100644 --- a/dokimi/dokimi/commands/runs_bundle.py +++ b/dokimi/dokimi/commands/runs_bundle.py @@ -53,7 +53,7 @@ def _import_root(args: argparse.Namespace) -> Path: root = runs_root() if not root.exists(): try: - root.path.mkdir() + 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}") diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index f2d009906..eed1f64de 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -22,6 +22,7 @@ from dokimi.artifacts import save_artifact from dokimi.runs import bundle from dokimi.runs.rundir import open_run +from dokimi.runs.scan import RunsRoot from dokimi.utils import InputError FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" @@ -838,3 +839,20 @@ def test_an_import_that_cannot_lock_the_root_writes_nothing(src, dst, tmp_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() From 0a960b39e01df21c19b68aab25b15cf46f2a0aa8 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:16:04 -0700 Subject: [PATCH 21/29] fix(runs): refuse a bundle artifact runs list would not find scan() finds an artifact by a name that ends in .json and JSON that opens with its schema_version. A bundle re-signed after its run.json was rewritten with sorted keys passed every import check, and the run it wrote could not be listed or exported again ("has no run directory"); a reordered artifact dropped out of the run's files the same way. verified() now refuses a listed file that scan() would skip, through scan.artifact_version(), the rule scan() applies by name and first bytes, so export and import check what runs list reads. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 4 +++- dokimi/dokimi/runs/bundle.py | 6 +++++- dokimi/dokimi/runs/scan.py | 13 ++++++++++++- dokimi/tests/test_runs_bundle.py | 33 ++++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 799bae629..ec835ee8d 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -355,7 +355,9 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none - 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); the result's `plan_digest` is the digest of the plan beside it; + (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, diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 1492dd72d..84de27421 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -42,7 +42,7 @@ from dokimi.runner.plan import plan_digest from dokimi.runs import baseline from dokimi.runs.rundir import RUN_FILE -from dokimi.runs.scan import inside, is_link, plain, read_error_reason, scan +from dokimi.runs.scan import artifact_version, inside, is_link, plain, read_error_reason, scan from dokimi.utils import InputError MANIFEST = "bundle.json" @@ -131,6 +131,10 @@ def _document(files: Mapping[str, bytes], path: str, kind: str, where: str) -> d 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 diff --git a/dokimi/dokimi/runs/scan.py b/dokimi/dokimi/runs/scan.py index 06a8b4db4..357d8f428 100644 --- a/dokimi/dokimi/runs/scan.py +++ b/dokimi/dokimi/runs/scan.py @@ -203,10 +203,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``. diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index eed1f64de..364f11393 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -856,3 +856,36 @@ def made_by_another(self): 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() From b09f05fbb1623f43b4585fca8d925635f0deb505 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:16:30 -0700 Subject: [PATCH 22/29] docs(runs): a pointer runs import --as cannot write exits 5, not 2 The paragraph said every save that fails once the run is written exits 2, while the command and the exit-code table give 5 for a pointer that cannot be written. Say which is which, and pin the 5 with a test. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 7 ++++--- dokimi/tests/test_runs_bundle.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index ec835ee8d..408e63246 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -377,9 +377,10 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none (`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. A save that - fails only once the run is written (a baseline whose name differs only in case, saved - meanwhile) exits 2 too, and says the run is imported (`run ... is imported, but ...`). + 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`) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 364f11393..29a23c8c7 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -889,3 +889,20 @@ def test_an_artifact_runs_list_would_not_find_is_refused(src, dst, tmp_path, mon 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() From 012a70655318ddd8a49f9b09809dbd2be65e0966 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:33:21 -0700 Subject: [PATCH 23/29] =?UTF-8?q?fix(runs):=20refuse=20CONIN$,=20CONOUT$?= =?UTF-8?q?=20and=20COM=C2=B9-LPT=C2=B3=20as=20bundle=20paths?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit safe_path() took the device names CON, PRN, AUX, NUL, COM0-9 and LPT0-9, but Windows also reserves CONIN$, CONOUT$ and COM/LPT with a superscript digit, which run.v1 allows in an artifact path. Use the set of CPython's ntpath.isreserved (3.13), keeping COM0 and LPT0. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 2 +- dokimi/dokimi/runs/bundle.py | 6 ++++-- dokimi/tests/test_runs_bundle.py | 3 ++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 408e63246..fe8ddc95c 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -347,7 +347,7 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none - 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`), a segment that ends in `.` or a space, two + (`<>"|?*`), 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), 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 diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 84de27421..0e9a207a4 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -54,8 +54,10 @@ _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. -_DEVICES = frozenset({"CON", "PRN", "AUX", "NUL", *(f"{p}{d}" for p in ("COM", "LPT") for d in range(10))}) +#: 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"} diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 29a23c8c7..b3dcd94a7 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -756,7 +756,8 @@ def test_a_resigned_run_json_that_does_not_match_its_files_is_refused(src, dst, @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"]) + "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) From b48b6c5c25db4b65fefb4720048a4df48644a9d7 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 07:33:46 -0700 Subject: [PATCH 24/29] test(runs): pin the exit 2 of a save the store refuses after import Since install() takes the lock first, no test reached the InputError branch of _point(), which docs/runs.md promises: a baseline saved meanwhile whose name differs only in case makes the save refuse once the run is written, with exit 2 and 'run ... is imported, but'. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/tests/test_runs_bundle.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index b3dcd94a7..91dc2ba4e 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -20,7 +20,7 @@ from dokimi import cli from dokimi.artifacts import save_artifact -from dokimi.runs import bundle +from dokimi.runs import baseline, bundle from dokimi.runs.rundir import open_run from dokimi.runs.scan import RunsRoot from dokimi.utils import InputError @@ -907,3 +907,24 @@ def full(*args, **kwargs): 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") From 11b6ad6c9966cab07b8cf59c809f4b7bca1e122d Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 08:27:27 -0700 Subject: [PATCH 25/29] fix(runs): runs list does not read a run an import is still writing The import writes a run into ...import under the runs root and renames it into place, but scan() walked that directory, so runs list, runs export and the run_id check of another import saw part of a run before the rename. scan() now skips such a directory at the root, as it skips .baselines; a run's own name never starts with a dot. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 1 + dokimi/dokimi/runs/scan.py | 10 +++++++--- dokimi/tests/test_runs_bundle.py | 19 ++++++++++++++++++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index fe8ddc95c..96e61bbed 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -371,6 +371,7 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none `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 diff --git a/dokimi/dokimi/runs/scan.py b/dokimi/dokimi/runs/scan.py index 357d8f428..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})"') @@ -324,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) @@ -338,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/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 91dc2ba4e..493e30bbb 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -22,7 +22,7 @@ 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 +from dokimi.runs.scan import RunsRoot, scan from dokimi.utils import InputError FIXTURES = Path(__file__).resolve().parent / "fixtures" / "artifacts" @@ -644,6 +644,23 @@ def full(self, data): 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.""" From c3537024fc40df631ac6efae923d8156569251c7 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 08:28:53 -0700 Subject: [PATCH 26/29] fix(runs): refuse a bundle that spells one directory two ways _check_paths() compared whole paths only, so Sub/a.json and sub/b.json passed. Windows and macOS write both into one directory; a later scan reads Sub/b.json, which the bundle does not list, so an identical second import exited 2 instead of being the no-op, and runs export reported the file as left out. A bundle (and a run on export) that spells one directory in two cases or two Unicode normalizations is now refused. Signed-off-by: Vladislav Perevezentsev --- dokimi/docs/runs.md | 3 ++- dokimi/dokimi/runs/bundle.py | 16 ++++++++++++++++ dokimi/tests/test_runs_bundle.py | 18 ++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/dokimi/docs/runs.md b/dokimi/docs/runs.md index 96e61bbed..fc3c6d017 100644 --- a/dokimi/docs/runs.md +++ b/dokimi/docs/runs.md @@ -349,7 +349,8 @@ saved baseline main -> 20261123T101500Z-1a2b3c4d; before: none 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), and a path under another listed path are refused; + (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 diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 0e9a207a4..0f39b6e05 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -119,6 +119,22 @@ def _check_paths(paths: Iterable[str], where: str) -> None: 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]: diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index 493e30bbb..ca75a479a 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -717,6 +717,24 @@ def test_paths_that_are_one_name_once_unicode_normalized_are_refused(src, dst, t 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) From b0ef938381b43d6a145fefdd2f4b922161669c97 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 10:28:30 -0700 Subject: [PATCH 27/29] test(cli): the RUN operand of runs export is a run_id, not a path The bad-path contract that came in with main (#1492) reads the operand as a path, since its help names run.json, and failed the command as one whose path parameter is never reached. RUN is a run_id or baseline:NAME, so list it in NOT_PATHS. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/tests/cli_faults.py | 1 + 1 file changed, 1 insertion(+) diff --git a/dokimi/tests/cli_faults.py b/dokimi/tests/cli_faults.py index 8034505a2..6a4d1bab1 100644 --- a/dokimi/tests/cli_faults.py +++ b/dokimi/tests/cli_faults.py @@ -49,6 +49,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"), From a609097edd07c28446d0271e0c13cedd4f1feaa8 Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 11:14:45 -0700 Subject: [PATCH 28/29] fix(runs): a tar header tarfile cannot parse is an input error tarfile parses a PAX sparse map with int(), so a malformed one raises ValueError while the archive is read; runs import let it through as an infrastructure crash (exit 5, a traceback). It is now refused like any other archive that is not a run bundle (exit 2). Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/dokimi/runs/bundle.py | 5 ++++- dokimi/tests/test_runs_bundle.py | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/dokimi/dokimi/runs/bundle.py b/dokimi/dokimi/runs/bundle.py index 0f39b6e05..f462bb73e 100644 --- a/dokimi/dokimi/runs/bundle.py +++ b/dokimi/dokimi/runs/bundle.py @@ -439,7 +439,10 @@ def read(path: Path) -> Bundle: 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 (OSError, EOFError, zlib.error, tarfile.TarError) as exc: + 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), diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index ca75a479a..a63e1f39d 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -526,6 +526,24 @@ def test_a_file_that_is_no_bundle_is_refused(dst, tmp_path, monkeypatch, capsysb 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 From 620507d0f40efa1288da0f4b718976a76c6e015b Mon Sep 17 00:00:00 2001 From: Vladislav Perevezentsev Date: Wed, 2 Dec 2026 11:14:45 -0700 Subject: [PATCH 29/29] test(runs): skip the export of a run named con on Windows The test makes the run's directory 'con' first, which Windows refuses, so it fails in its setup there before export is reached. Refs #94 Signed-off-by: Vladislav Perevezentsev --- dokimi/tests/test_runs_bundle.py | 1 + 1 file changed, 1 insertion(+) diff --git a/dokimi/tests/test_runs_bundle.py b/dokimi/tests/test_runs_bundle.py index a63e1f39d..ba43a373b 100644 --- a/dokimi/tests/test_runs_bundle.py +++ b/dokimi/tests/test_runs_bundle.py @@ -830,6 +830,7 @@ 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")