diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..3f9e90c --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,16 @@ +# The last matching rule wins: keep shared rules first and sample rules below. + +# Repository infrastructure: CI, the example runner, and project configuration. +# Owners of .github/workflows/newton-main.yml are assigned nightly failures that +# cannot be attributed to a sample (dependency install, timeouts). +/.github/ @felixmey +/conftest.py @felixmey +/pyproject.toml @felixmey +/uv.lock @felixmey +/examples/__init__.py @felixmey +/examples/__main__.py @felixmey + +# Sample maintainers. Each sample's folder holds its code, README, images, and +# tests; own the whole folder. The nightly Newton-main workflow assigns failure +# issues to these owners. See CONTRIBUTING.md. +/examples/multiphysics/franka_pulley_mechanical_advantage/ @felixmey diff --git a/.github/actions/cache-warp/action.yml b/.github/actions/cache-warp/action.yml index 0c9132e..8b00f58 100644 --- a/.github/actions/cache-warp/action.yml +++ b/.github/actions/cache-warp/action.yml @@ -26,7 +26,7 @@ runs: uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5 with: path: ${{ env.WARP_CACHE_PATH }} - key: warp-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.runtime.outputs.identity }}-${{ hashFiles('pyproject.toml', 'uv.lock', 'examples/**/*.py', 'tests/**/*.py') }} + key: warp-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.runtime.outputs.identity }}-${{ hashFiles('pyproject.toml', 'uv.lock', 'conftest.py', 'examples/**/*.py') }} # Warp hashes module contents, so unchanged kernels remain reusable # when Newton or the examples change. New kernels compile normally. restore-keys: | diff --git a/.github/scripts/report_nightly_failures.py b/.github/scripts/report_nightly_failures.py new file mode 100644 index 0000000..b8bbf46 --- /dev/null +++ b/.github/scripts/report_nightly_failures.py @@ -0,0 +1,279 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Open or update one GitHub issue per sample that fails the nightly Newton-main run. + +Failing JUnit test cases are grouped by sample folder +(examples///). Owners of the failing test files come from +CODEOWNERS; users are assigned and teams are mentioned. An open issue for the +same sample receives a comment instead of a duplicate issue. Failures that +cannot be attributed to a test file (dependency resolution, timeouts, missing +results) are reported in a single infrastructure issue assigned to the +CODEOWNERS of the nightly workflow file. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.request +import xml.etree.ElementTree as ET +from collections import defaultdict +from pathlib import Path + +LABEL = "nightly-failure" +INFRA_KEY = "infrastructure" +# Unattributed failures go to whoever owns the nightly workflow. +INFRA_OWNER_PATH = ".github/workflows/newton-main.yml" +MAX_DETAIL_CHARS = 3000 +MAX_TESTS_WITH_DETAIL = 5 + + +def codeowners_rules(path: Path) -> list[tuple[re.Pattern[str], list[str]]]: + rules = [] + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.split("#", 1)[0].strip() + if not line: + continue + pattern, *owners = line.split() + rules.append((_pattern_regex(pattern), owners)) + return rules + + +def _pattern_regex(pattern: str) -> re.Pattern[str]: + # Gitignore-style subset used by CODEOWNERS: leading or inner "/" anchors to + # the root, "**" spans directories, "*" and "?" stay within one segment. + anchored = "/" in pattern.rstrip("/") + body = pattern.strip("/") + regex = "" + i = 0 + while i < len(body): + if body.startswith("**/", i): + regex += "(?:.*/)?" + i += 3 + elif body.startswith("**", i): + regex += ".*" + i += 2 + elif body[i] == "*": + regex += "[^/]*" + i += 1 + elif body[i] == "?": + regex += "[^/]" + i += 1 + else: + regex += re.escape(body[i]) + i += 1 + prefix = "" if anchored else "(?:.*/)?" + return re.compile(f"^{prefix}{regex}(?:/.*)?$") + + +def owners_for(rules, path: str) -> list[str]: + owners: list[str] = [] + for regex, rule_owners in rules: + if regex.match(path): + owners = rule_owners # The last matching rule wins. + return owners + + +def test_file(root: Path, dotted: str) -> str | None: + """Map a pytest JUnit classname (or collection-error name) to a repo path.""" + parts = dotted.split("[", 1)[0].split(".") + for end in range(len(parts), 0, -1): + candidate = Path(*parts[:end]).with_suffix(".py") + if (root / candidate).is_file(): + return candidate.as_posix() + return None + + +def sample_key(path: str) -> str: + """Group a test file by its sample folder, or by the file outside one.""" + parts = path.split("/") + return "/".join(parts[:3]) if len(parts) > 3 and parts[0] == "examples" else path + + +def failing_tests(junit: Path, root: Path) -> dict[str, list[tuple[str, str, str | None]]]: + by_key: dict[str, list[tuple[str, str, str | None]]] = defaultdict(list) + for case in ET.parse(junit).getroot().iter("testcase"): + problem = case.find("failure") + if problem is None: + problem = case.find("error") + if problem is None: + continue + classname = case.get("classname", "") + name = case.get("name", "") + # Collection errors have an empty classname and the module as the name. + path = test_file(root, classname or name) + test_id = f"{classname}::{name}" if classname else name + detail = (problem.text or problem.get("message") or "").strip() + by_key[sample_key(path) if path else INFRA_KEY].append((test_id, detail, path)) + return by_key + + +def newton_revision(environment: Path) -> str | None: + if not environment.is_file(): + return None + for line in environment.read_text(encoding="utf-8").splitlines(): + match = re.match(r"newton\s*@\s*git\+(https://github\.com/[^@\s]+?)(?:\.git)?@([0-9a-f]{7,40})", line) + if match: + return f"[`{match[2][:12]}`]({match[1]}/commit/{match[2]})" + return None + + +def code_block(text: str) -> str: + if len(text) > MAX_DETAIL_CHARS: + text = "...\n" + text[-MAX_DETAIL_CHARS:] + # A fence longer than any backtick run in the text keeps it literal, which + # also stops "@name" strings in test output from notifying anyone. + fence = "`" * max(3, max((len(run) for run in re.findall(r"`+", text)), default=0) + 1) + return f"{fence}text\n{text}\n{fence}" + + +def report_body(key, tests, repo_url, run_url, revision, users, teams) -> str: + lines = [f"The [nightly Newton-main run]({run_url}) failed."] + if revision: + lines.append(f"Newton revision: {revision}") + lines.append("") + owners = " ".join(f"@{login}" for login in users + teams) + if key == INFRA_KEY: + lines.append("The failure could not be attributed to a sample. Check the run log. ") + lines.append(f"Workflow owners (CODEOWNERS): {owners or '_none listed_'}") + else: + lines.append( + f"Sample: [`{key}`]({repo_url}/tree/main/{key}) \nMaintainers (CODEOWNERS): {owners or '_none listed_'}" + ) + if tests: + lines += ["", f"### Failing tests ({len(tests)})", ""] + lines += [f"- `{test_id}`" for test_id, _, _ in tests] + for test_id, detail, _ in tests[:MAX_TESTS_WITH_DETAIL]: + if detail: + lines += [ + "", + f"
{test_id}", + "", + code_block(detail), + "", + "
", + ] + if key != INFRA_KEY: + lines += [ + "", + ( + "Newton main is ahead of the latest release, so this may be an upcoming API or behavior change. " + f"See the remediation process in [CONTRIBUTING.md]({repo_url}/blob/main/CONTRIBUTING.md#remediation-process)." + ), + ] + return "\n".join(lines) + + +class GitHub: + def __init__(self, repo: str, token: str, dry_run: bool): + self.base = f"https://api.github.com/repos/{repo}" + self.token = token + self.dry_run = dry_run + + def request(self, method: str, path: str, data=None): + if self.dry_run and method != "GET": + print(f"[dry-run] {method} {path}\n{json.dumps(data, indent=2)}\n") + return {"number": 0, "assignees": []} + request = urllib.request.Request( + self.base + path, + method=method, + data=None if data is None else json.dumps(data).encode(), + headers={ + "Accept": "application/vnd.github+json", + "Authorization": f"Bearer {self.token}", + "X-GitHub-Api-Version": "2022-11-28", + }, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.loads(response.read() or "null") + + def ensure_label(self): + try: + self.request( + "POST", "/labels", {"name": LABEL, "color": "d73a4a", "description": "Nightly Newton-main failure"} + ) + except urllib.error.HTTPError as error: + if error.code != 422: # 422: the label already exists. + raise + + def open_issues(self) -> list[dict]: + issues, page = [], 1 + while True: + batch = self.request("GET", f"/issues?state=open&labels={LABEL}&per_page=100&page={page}") + issues += [issue for issue in batch if "pull_request" not in issue] + if len(batch) < 100: + return issues + page += 1 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--junit", type=Path, required=True) + parser.add_argument("--environment", type=Path) + parser.add_argument("--codeowners", type=Path, default=Path(".github/CODEOWNERS")) + parser.add_argument("--root", type=Path, default=Path(".")) + parser.add_argument("--dry-run", action="store_true", help="Print issue writes instead of sending them.") + args = parser.parse_args() + + repo = os.environ["GITHUB_REPOSITORY"] + server = os.environ.get("GITHUB_SERVER_URL", "https://github.com") + repo_url = f"{server}/{repo}" + run_url = f"{repo_url}/actions/runs/{os.environ.get('GITHUB_RUN_ID', '0')}" + github = GitHub(repo, os.environ.get("GH_TOKEN", ""), args.dry_run) + + if args.junit.is_file(): + failures = failing_tests(args.junit, args.root) + else: + print(f"::warning::{args.junit} not found; reporting an infrastructure failure") + failures = {} + if not failures: + # The job failed but no test case did: setup, collection, or a timeout. + failures = {INFRA_KEY: []} + + rules = codeowners_rules(args.codeowners) if args.codeowners.is_file() else [] + revision = newton_revision(args.environment) if args.environment else None + existing = github.open_issues() if not args.dry_run or os.environ.get("GH_TOKEN") else [] + github.ensure_label() + + for key, tests in sorted(failures.items()): + paths = [INFRA_OWNER_PATH] if key == INFRA_KEY else [path for _, _, path in tests if path] + owners = [] + for path in dict.fromkeys(paths): + owners += [owner for owner in owners_for(rules, path) if owner not in owners] + users = [owner[1:] for owner in owners if owner.startswith("@") and "/" not in owner] + teams = [owner[1:] for owner in owners if owner.startswith("@") and "/" in owner] + if not owners: + print(f"::warning::No CODEOWNERS entry for {paths[0]}; the issue will be unassigned") + body = report_body(key, tests, repo_url, run_url, revision, users, teams) + marker = f"" + + issue = next((issue for issue in existing if marker in (issue.get("body") or "")), None) + if issue: + github.request("POST", f"/issues/{issue['number']}/comments", {"body": body}) + print(f"Commented on #{issue['number']} for {key}") + continue + + title = ( + "Nightly Newton-main run failed outside the sample tests" + if key == INFRA_KEY + else f"Nightly Newton main: {key.rsplit('/', 1)[-1]} is failing" + ) + issue = github.request("POST", "/issues", {"title": title, "body": f"{marker}\n{body}", "labels": [LABEL]}) + if users: + # Assigning separately means an owner without repository access + # is skipped instead of failing the issue creation. + assigned = github.request("POST", f"/issues/{issue['number']}/assignees", {"assignees": users}) + missing = set(users) - {assignee["login"] for assignee in assigned.get("assignees", [])} + if missing and not args.dry_run: + print(f"::warning::Could not assign {', '.join(sorted(missing))} to #{issue['number']}") + print(f"Opened #{issue['number']} for {key}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/newton-main.yml b/.github/workflows/newton-main.yml index 6991f9f..dff4a24 100644 --- a/.github/workflows/newton-main.yml +++ b/.github/workflows/newton-main.yml @@ -58,3 +58,35 @@ jobs: uv.lock retention-days: 14 if-no-files-found: warn + + report: + # Open or update an issue per failing sample, assigned to its CODEOWNERS. + # Runs separately so the job executing Newton main never holds a token + # that can write issues. + name: Report failing samples + needs: cuda + if: ${{ always() && needs.cuda.result == 'failure' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Download test results + # Missing results (e.g. dependency resolution failed) are reported as + # an infrastructure failure. + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: tests-newton-main-cuda + path: nightly-results + - name: Open or update issues + env: + GH_TOKEN: ${{ github.token }} + run: >- + python3 .github/scripts/report_nightly_failures.py + --junit nightly-results/test-results/cuda.xml + --environment nightly-results/test-results/environment.txt diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 62eef47..201c251 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -39,8 +39,8 @@ jobs: run: uv sync --locked --dev - name: Lint tested code run: | - uv run --locked ruff check tests examples/multiphysics/example_franka_pulley_mechanical_advantage.py - uv run --locked ruff format --check tests examples/multiphysics/example_franka_pulley_mechanical_advantage.py + uv run --locked ruff check conftest.py .github/scripts examples/*/*/ + uv run --locked ruff format --check conftest.py .github/scripts examples/*/*/ - name: Run CPU tests run: uv run --locked pytest -m "not cuda" --junitxml=test-results/cpu.xml - name: Upload test results diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 90c3264..38d2e8e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,7 @@ # Contributing to Newton Samples +Contributions are currently limited to Nvidians only. + ## Contributor Expectations 1. Examples must come with tests to verify their correctness automatically. @@ -7,13 +9,31 @@ 3. Examples must be continually updated to resolve any detected vulnerabilities. +## Sample Layout + +Each sample lives in its own folder, which holds everything that belongs to it: + +``` +examples/// + __init__.py + example_.py # run with: uv run -m examples + README.md # usage, configuration, and validation + images/ # screenshots referenced by README.md + tests/ + __init__.py + test_.py +``` + +Add a card for the sample to the table in the top-level [README](README.md#examples). + + ## Registering as a Contributor -To register as a contributor, please add yourself to `CODEOWNERS`. This is how you identify yourself as a maintainer for your example. +To register as a contributor, please add your sample's folder to [`.github/CODEOWNERS`](.github/CODEOWNERS) with your GitHub handle, for example `/examples/// @your-handle`. This is how you identify yourself as a maintainer for your example. When the nightly run against Newton `main` fails, the issue is assigned to the owners of the failing sample. ## Remediation Process 1. When your contribution falls out of compliance we will open a Github issue and assign it to you. 2. After 7, 14, and 21 days of no remediation we will ping the issue. -3. After 28 days of no remediation the contribution will be removed from Newton Samples. You may request an extension in the Github issue. \ No newline at end of file +3. After 28 days of no remediation the contribution will be removed from Newton Samples. You may request an extension in the Github issue. diff --git a/README.md b/README.md index 9a0d57b..585bd4c 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ Choose a sample below for launch instructions, configuration, and validation. - - Franka robot grasping a cable end beside a block-and-tackle pulley mechanism and guided load + + Franka robot grasping a cable end beside a block-and-tackle pulley mechanism and guided load @@ -59,7 +59,7 @@ Choose a sample below for launch instructions, configuration, and validation. - Franka Pulley Mechanical Advantage + Franka Pulley Mechanical Advantage diff --git a/tests/conftest.py b/conftest.py similarity index 100% rename from tests/conftest.py rename to conftest.py diff --git a/examples/__init__.py b/examples/__init__.py index 3c72eb0..608447a 100644 --- a/examples/__init__.py +++ b/examples/__init__.py @@ -239,17 +239,24 @@ def run(example, args): def get_examples() -> dict[str, str]: - """Return a dict mapping example short names to their full module paths.""" + """Return a dict mapping example short names to their full module paths. + + Each sample lives in its own folder: ``examples///example_.py``. + """ example_map = {} examples_dir = get_source_directory() - for module in sorted(os.listdir(examples_dir)): - module_dir = os.path.join(examples_dir, module) - if not os.path.isdir(module_dir) or module.startswith("_"): + for category in sorted(os.listdir(examples_dir)): + category_dir = os.path.join(examples_dir, category) + if not os.path.isdir(category_dir) or category.startswith("_"): continue - for filename in sorted(os.listdir(module_dir)): - if filename.startswith("example_") and filename.endswith(".py"): - example_name = filename[8:-3] - example_map[example_name] = f"examples.{module}.{filename[:-3]}" + for sample in sorted(os.listdir(category_dir)): + sample_dir = os.path.join(category_dir, sample) + if not os.path.isdir(sample_dir) or sample.startswith("_"): + continue + for filename in sorted(os.listdir(sample_dir)): + if filename.startswith("example_") and filename.endswith(".py"): + example_name = filename[8:-3] + example_map[example_name] = f"examples.{category}.{sample}.{filename[:-3]}" return example_map diff --git a/docs/examples/franka_pulley_mechanical_advantage.md b/examples/multiphysics/franka_pulley_mechanical_advantage/README.md similarity index 91% rename from docs/examples/franka_pulley_mechanical_advantage.md rename to examples/multiphysics/franka_pulley_mechanical_advantage/README.md index 5fc4f03..913072b 100644 --- a/docs/examples/franka_pulley_mechanical_advantage.md +++ b/examples/multiphysics/franka_pulley_mechanical_advantage/README.md @@ -1,9 +1,9 @@ # Franka Pulley Mechanical Advantage -[Back to Newton Samples](../../README.md#examples) · -[Source](../../examples/multiphysics/example_franka_pulley_mechanical_advantage.py) +[Back to Newton Samples](../../../README.md#examples) · +[Source](example_franka_pulley_mechanical_advantage.py) -![Franka robot pulling a cable through a pulley mechanism](../images/examples/example_franka_pulley_mechanical_advantage.jpg) +![Franka robot pulling a cable through a pulley mechanism](images/preview.jpg) A MuJoCo-simulated Franka robot follows an inverse-kinematics trajectory, grasps a box attached to the free end of a VBD cable, and pulls downward 0.4 m to @@ -13,7 +13,7 @@ and mechanism; the robot has no fixed attachment to the cable. ## Run -After completing the repository's [setup](../../README.md#quickstart), launch +After completing the repository's [setup](../../../README.md#quickstart), launch the default 4:1 mechanism with a 5 kg load: ```bash @@ -32,7 +32,7 @@ from Newton's public asset collection on first use. The first run requires internet access and Git on `PATH`. The pulley, cable, and weight are generated in Python; no local asset files or Git LFS setup are required. The URDF and meshes are not bundled in this repository or its Python package. See -[third-party notices](../../THIRD_PARTY_NOTICES.md) for the asset's source, pinned +[third-party notices](../../../THIRD_PARTY_NOTICES.md) for the asset's source, pinned revision, and upstream Apache-2.0 license and additional Willow Garage BSD notice. ## Configuration and Measurements diff --git a/examples/multiphysics/franka_pulley_mechanical_advantage/__init__.py b/examples/multiphysics/franka_pulley_mechanical_advantage/__init__.py new file mode 100644 index 0000000..51bebe3 --- /dev/null +++ b/examples/multiphysics/franka_pulley_mechanical_advantage/__init__.py @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Franka Pulley Mechanical Advantage sample.""" diff --git a/examples/multiphysics/example_franka_pulley_mechanical_advantage.py b/examples/multiphysics/franka_pulley_mechanical_advantage/example_franka_pulley_mechanical_advantage.py similarity index 100% rename from examples/multiphysics/example_franka_pulley_mechanical_advantage.py rename to examples/multiphysics/franka_pulley_mechanical_advantage/example_franka_pulley_mechanical_advantage.py diff --git a/docs/images/examples/example_franka_pulley_mechanical_advantage.jpg b/examples/multiphysics/franka_pulley_mechanical_advantage/images/preview.jpg similarity index 100% rename from docs/images/examples/example_franka_pulley_mechanical_advantage.jpg rename to examples/multiphysics/franka_pulley_mechanical_advantage/images/preview.jpg diff --git a/examples/multiphysics/franka_pulley_mechanical_advantage/tests/__init__.py b/examples/multiphysics/franka_pulley_mechanical_advantage/tests/__init__.py new file mode 100644 index 0000000..52a7a9d --- /dev/null +++ b/examples/multiphysics/franka_pulley_mechanical_advantage/tests/__init__.py @@ -0,0 +1,2 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/tests/test_franka_pulley.py b/examples/multiphysics/franka_pulley_mechanical_advantage/tests/test_franka_pulley.py similarity index 98% rename from tests/test_franka_pulley.py rename to examples/multiphysics/franka_pulley_mechanical_advantage/tests/test_franka_pulley.py index 7cc2853..1a9408e 100644 --- a/tests/test_franka_pulley.py +++ b/examples/multiphysics/franka_pulley_mechanical_advantage/tests/test_franka_pulley.py @@ -9,7 +9,9 @@ import pytest import warp as wp -from examples.multiphysics import example_franka_pulley_mechanical_advantage as pulley +from examples.multiphysics.franka_pulley_mechanical_advantage import ( + example_franka_pulley_mechanical_advantage as pulley, +) @pytest.mark.parametrize("force", [0.0, pulley.DEFAULT_WEIGHT_MASS * pulley.GRAVITY / 4]) diff --git a/pyproject.toml b/pyproject.toml index 722f44b..ee9895c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ dev = [ ] [tool.pytest.ini_options] -testpaths = ["tests"] +testpaths = ["examples"] addopts = "--strict-config --strict-markers -ra" markers = [ "cuda: requires an NVIDIA GPU and a working CUDA driver", @@ -34,6 +34,8 @@ markers = [ [tool.uv.build-backend] module-name = "examples" module-root = "" +# Keep the wheel to runnable code; tests, docs, and images stay in the repository. +wheel-exclude = ["examples/*/*/tests", "examples/*/*/images", "examples/*/*/README.md"] [[tool.uv.index]] url = "https://pypi.org/simple"