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/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion .github/actions/cache-warp/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
279 changes: 279 additions & 0 deletions .github/scripts/report_nightly_failures.py
Original file line number Diff line number Diff line change
@@ -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/<category>/<sample>/). 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"<details><summary><code>{test_id}</code></summary>",
"",
code_block(detail),
"",
"</details>",
]
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"<!-- nightly-failure-key: {key} -->"

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())
32 changes: 32 additions & 0 deletions .github/workflows/newton-main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions .github/workflows/quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 22 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,39 @@
# Contributing to Newton Samples

Contributions are currently limited to Nvidians only.

## Contributor Expectations

1. Examples must come with tests to verify their correctness automatically.
2. Examples must run against the **latest minor version** of Newton.
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/<category>/<sample>/
__init__.py
example_<sample>.py # run with: uv run -m examples <sample>
README.md # usage, configuration, and validation
images/ # screenshots referenced by README.md
tests/
__init__.py
test_<sample>.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/<category>/<sample>/ @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.
3. After 28 days of no remediation the contribution will be removed from Newton Samples. You may request an extension in the Github issue.
Loading