Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/smoke-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,22 @@ jobs:
with:
path: workspace

- name: Reject tracked validation output
shell: bash
run: |
set -euo pipefail
git -C workspace ls-files -z > "$RUNNER_TEMP/tracked-paths"
bad=0
while IFS= read -r -d '' path; do
case "$path" in
test-results/*|*/test-results/*|*__script.json|smoke_timings.json|*/smoke_timings.json)
echo "::error::Tracked validation output: $path"
bad=1
;;
esac
done < "$RUNNER_TEMP/tracked-paths"
exit "$bad"

- name: Clone dependency chain + PyAutoHands (matching branch if it exists)
# DEPTH 1, on the clone and on the matching-branch fetch alike: nothing
# downstream reads this history. The libraries are `pip install`ed from
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/workspace-validation.yml
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,13 @@ jobs:
path: all-results
pattern: results-*
merge-multiple: true
- name: Checkout Heart result provenance guard
uses: actions/checkout@v4
with:
repository: PyAutoLabs/PyAutoHeart
path: PyAutoHeart
- name: Reject foreign result paths before aggregation
run: PYTHONPATH=PyAutoHeart python3 -m heart.result_provenance all-results --root "$GITHUB_WORKSPACE"
- name: Aggregate into report.json
run: |
export PYTHONPATH="$PYTHONPATH:$(pwd)/PyAutoHands"
Expand Down
3 changes: 3 additions & 0 deletions heart/checks/script_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import yaml

from heart import _workspace
from heart.result_provenance import trusted_results

HEART_STATE_DIR = Path(
os.environ.get("HEART_STATE_DIR")
Expand Down Expand Up @@ -312,6 +313,8 @@ def scan_latest_results(results_dir: Path) -> list[dict[str, Any]]:
data = json.loads(json_path.read_text())
except json.JSONDecodeError:
continue
if not trusted_results(data, json_path):
continue
project = data.get("project", "")
directory = data.get("directory", "")
for r in data.get("results", []):
Expand Down
3 changes: 3 additions & 0 deletions heart/checks/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from typing import Any, Callable

from heart import _workspace
from heart.result_provenance import trusted_results

# Reuse the same root/latest resolution as script_timing.py: the one shared
# resolver, via heart/_workspace.py, asked for the MAIN checkout — grading
Expand Down Expand Up @@ -209,6 +210,8 @@ def _from_per_job(results_dir: Path) -> dict[str, Any]:
data = _read_json(jp)
if not isinstance(data, dict):
continue
if not trusted_results(data, jp):
continue
found = True
s = data.get("summary", {}) or {}
proj = data.get("project", "?")
Expand Down
58 changes: 58 additions & 0 deletions heart/result_provenance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Reject foreign runner paths before result shards become validation evidence.

PYAUTO_RESULT_ROOT overrides GITHUB_WORKSPACE for replay/local collection. With
neither declared, historical local reports retain their existing interpretation.
CI must validate before aggregation: rejecting a shard invalidates that run's
completeness; it must not be reinterpreted as an all-passing smaller run.
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path
from typing import Any


def trusted_results(data: Any, source: Path, root: str | Path | None = None) -> bool:
root = root or os.environ.get("PYAUTO_RESULT_ROOT") or os.environ.get("GITHUB_WORKSPACE")
if not root or not isinstance(data, dict) or "results" not in data:
return True
root_path = Path(root).resolve()
results = data["results"]
if not isinstance(results, list):
print(f"WARNING: rejected result shard {source}: malformed results", file=sys.stderr)
return False
valid = True
for row in results:
file = row.get("file") if isinstance(row, dict) else None
path = Path(file) if isinstance(file, str) and file else None
if (path is None or not path.is_absolute() or ".." in path.parts
or not path.resolve().is_relative_to(root_path)):
print(f"WARNING: rejected result shard {source}: foreign file path {file!r} "
f"(runner root {root_path})", file=sys.stderr)
valid = False
return valid


def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
parser.add_argument("--root", required=True, type=Path)
args = parser.parse_args(argv)
invalid = False
for path in sorted(args.directory.rglob("*.json")):
try:
data = json.loads(path.read_text())
except (OSError, ValueError) as exc:
print(f"WARNING: unreadable result shard {path}: {exc}", file=sys.stderr)
invalid = True
continue
if not trusted_results(data, path, args.root):
invalid = True
return int(invalid)


if __name__ == "__main__":
raise SystemExit(main())
4 changes: 4 additions & 0 deletions heart/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
import json
import sys
from pathlib import Path
from heart.result_provenance import trusted_results
from typing import Any, Iterable, Sequence

from heart import freeze, state
Expand Down Expand Up @@ -610,6 +611,9 @@ def _fold(
acc.testpypi_version = txt.splitlines()[0].strip()
continue
data = _read_json(path)
if not trusted_results(data, path):
acc._force_fail = True
continue
kind = _classify(path.name, data)
if kind == "rehearsal":
acc.add_rehearsal(data)
Expand Down
5 changes: 3 additions & 2 deletions tests/test_monitoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,13 @@ def test_fresh_published_complete_timing_survives_empty_cloud_slice():
assert m["complete"] and m["score"] == 100


def test_source_run_timestamp_survives_reaggregation(tmp_path):
def test_source_run_timestamp_survives_reaggregation(tmp_path, monkeypatch):
monkeypatch.setenv("PYAUTO_RESULT_ROOT", str(tmp_path))
import json
import os
from heart.checks import script_timing
path = tmp_path / "example__script.json"
path.write_text(json.dumps({"project": "Example", "directory": "scripts", "results": [{"status": "passed", "file": "x.py", "duration_seconds": 2}]}))
path.write_text(json.dumps({"project": "Example", "directory": "scripts", "results": [{"status": "passed", "file": str(tmp_path / "x.py"), "duration_seconds": 2}]}))
old = dt.datetime(2026, 9, 1, tzinfo=dt.timezone.utc).timestamp()
os.utime(path, (old, old))
rows = script_timing.scan_latest_results(tmp_path)
Expand Down
81 changes: 81 additions & 0 deletions tests/test_result_provenance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import json
import os
import subprocess
from pathlib import Path

import pytest
import yaml

from heart import result_provenance as provenance
from heart.checks import script_timing, test_run


def shard(path):
return {"project": "WorkspaceA", "directory": "examples", "summary": {"passed": 1},
"results": [{"file": str(path), "status": "passed", "duration_seconds": 4}]}


@pytest.mark.parametrize("foreign", ["/home/other/scripts/test.py", "/runner-extra/test.py", "/runner/../outside/test.py", "scripts/relative.py"])
def test_foreign_paths_warn_and_invalidate_shard(foreign, capsys):
assert not provenance.trusted_results(shard(foreign), Path("shard.json"), "/runner")
warning = capsys.readouterr().err
assert "shard.json" in warning and foreign in warning


def test_collectors_exclude_foreign_counts_and_timings(tmp_path, monkeypatch, capsys):
runner = tmp_path / "runner"
monkeypatch.setenv("PYAUTO_RESULT_ROOT", str(runner))
(tmp_path / "good__script.json").write_text(json.dumps(shard(runner / "scripts/test.py")))
(tmp_path / "stale__script.json").write_text(json.dumps(shard(tmp_path / "foreign/test.py")))
assert len(script_timing.scan_latest_results(tmp_path)) == 1
result = test_run._from_per_job(tmp_path)
assert result["passed"] == 1
assert "stale__script.json" in capsys.readouterr().err
assert provenance.main([str(tmp_path), "--root", str(runner)]) == 1


def test_clean_shard_and_explicit_local_replay(tmp_path, monkeypatch):
monkeypatch.delenv("PYAUTO_RESULT_ROOT", raising=False)
monkeypatch.delenv("GITHUB_WORKSPACE", raising=False)
data = shard(tmp_path / "scripts/test.py")
assert provenance.trusted_results(data, Path("local.json"))
assert provenance.trusted_results(data, Path("local.json"), tmp_path)
(tmp_path / "good.json").write_text(json.dumps(data))
assert provenance.main([str(tmp_path), "--root", str(tmp_path)]) == 0


def test_symlink_escape_is_rejected(tmp_path):
root = tmp_path / "runner"
root.mkdir()
(root / "link").symlink_to(tmp_path, target_is_directory=True)
assert not provenance.trusted_results(shard(root / "link/test.py"), Path("a.json"), root)


def test_workflow_lint_rejects_tracked_not_untracked_reports(tmp_path):
workflow = Path(__file__).resolve().parents[1] / ".github/workflows/smoke-tests.yml"
steps = yaml.safe_load(workflow.read_text())["jobs"]["smoke"]["steps"]
command = next(s["run"] for s in steps if s.get("name") == "Reject tracked validation output")
workspace = tmp_path / "workspace"
workspace.mkdir()
subprocess.run(["git", "init", str(workspace)], check=True, capture_output=True)
env = {**os.environ, "RUNNER_TEMP": str(tmp_path)}
results = workspace / "test-results"
results.mkdir()
(results / "stale__script.json").write_text("{}")
assert subprocess.run(["bash", "-c", command], cwd=tmp_path, env=env).returncode == 0
subprocess.run(["git", "-C", str(workspace), "add", "test-results"], check=True)
run = subprocess.run(["bash", "-c", command], cwd=tmp_path, env=env, capture_output=True, text=True)
assert run.returncode == 1
assert "test-results/stale__script.json" in run.stdout


def test_foreign_shard_cannot_leave_passing_validation(tmp_path, monkeypatch):
from heart import validate

monkeypatch.setenv("PYAUTO_RESULT_ROOT", str(tmp_path / "runner"))
(tmp_path / "stage.json").write_text(json.dumps({"mode": "rehearsal", "index": "testpypi", "version": "1", "packages": ["demo"]}))
assert validate.ingest([tmp_path])["release_ready"] is True
(tmp_path / "foreign__script.json").write_text(json.dumps(shard("/home/other/stale.py")))
report = validate.ingest([tmp_path])
assert report["release_ready"] is False
assert report["validation_outcome"] == "fail"
3 changes: 3 additions & 0 deletions tests/test_script_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
@pytest.fixture
def tmp_state(tmp_path, monkeypatch):
"""Redirect HEART_STATE_DIR to a tmp dir and reload heart.checks.script_timing."""
# These fixtures model historical local reports, not CI-runner artifacts.
monkeypatch.delenv("GITHUB_WORKSPACE", raising=False)
monkeypatch.delenv("PYAUTO_RESULT_ROOT", raising=False)
monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path))
import heart.state as state_mod
importlib.reload(state_mod)
Expand Down
Loading