Metadata-Version: 2.4
Name: simready-validate
Version: 2026.10.0
Summary: SimReady Validation Library
Author: NVIDIA Corporation
License-Expression: Apache-2.0
Project-URL: Homepage, https://www.nvidia.com
Keywords: nvidia,simready,validate
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: usd-validation-nvidia>=1.23.0
Requires-Dist: usd-profiles-nvidia>=1.23.0
Provides-Extra: usd
Requires-Dist: usd-core>=22.11; extra == "usd"
Dynamic: license-file

# simready.validate

## Catalog selection and profile verdict

Use the user's exact profile ID and version from the loaded registry. For installed
tier wheels, call `sv.initialize([], [], [])`, then inspect
`sv.get_available_profiles()` (a mapping of profile ID to registered versions).
Do not guess a retired split-profile name, add an alias, or silently select a
successor. Filesystem paths passed to `initialize` explicitly select that catalog
instead of installed tiers. In Kit, inspect the already-loaded registry first.
The examples below use `profile_id` and `profile_version` selected from that
mapping; these variables must match the user's requested contract exactly.

Profile success is `sv.features_summary_passed(result.features_summary)`, not
`all(entry["passed"] ...)`. It requires a nonempty summary and no blocking
failure. An optional feature can retain `passed: false` and
`blocking_failure: false` while the profile passes. Keep every feature failure
and its requirement details visible; `sv.is_blocking_failure(entry)` interprets
blocking status including legacy entries. A missing result (`None`) is an
unresolved/unavailable validation, and an empty summary is no evaluated profile
coverage, not PASS. Neither is evidence that the asset failed a measured rule.

The CLI and [HTML report](docs/api.md#html-reports) distinguish measured profile
failures from unavailable results and no feature coverage. HTML preserves the
requested identity where supplied; unavailable rows point to logs without
guessing a missing-profile cause. An empty request list exits nonzero and does
not create or update JSON, though an explicitly requested zero-row HTML report
is written.

Standalone Python library for validating USD assets against SimReady profiles. Reports
which features passed or failed, with per-requirement detail on failures.

---

## Installation

```bash
pip install simready-validate
```

Install `simready-validate[usd]` if the calling Python environment does not
already supply OpenUSD (`pxr`). Do not combine `usd-core` with USD Exchange.

## Quick start

```python
import simready.validate as sv

# Discover installed tiers (omit if the host already registered them).
sv.initialize([], [], [])
print(sv.get_available_profiles())

result = sv.validate_asset(sv.AssetValidationConfig(
    asset_path="/assets/props/crate_01/crate_01.usd",
    profile_id=profile_id,
    profile_version=profile_version,
))

if result is None:
    print("UNAVAILABLE: validation did not complete — see the logs.")
elif not result.features_summary:
    print(f"{result.profile_id} v{result.profile_version}: NO COVERAGE — no features evaluated.")
else:
    passed = sv.features_summary_passed(result.features_summary)
    print(f"{result.profile_id} v{result.profile_version}: {'PASSED' if passed else 'FAILED'}")
    for feat_id, data in result.features_summary.items():
        if not data["passed"]:
            print(f"  {feat_id}: failing {data.get('failing requirements')}")
            print(f"    optional requirements: {data.get('optional requirements', [])}")

sv.destroy()
```

---

## Key concepts

### Profiles

A **profile** is a named, versioned set of feature and capability selectors. Foundations 2
feature and capability IDs use `<name>[.<runtime>].<version>`. Neutral IDs omit the runtime
(for example, `FET004_Multibody.0-2-0`); runtime variants retain it
(`FET004_Multibody.PhysX.2-0-4`). Earlier explicit `.OpenUSD.<version>` IDs remain readable
and normalize to the neutral spelling, with `OpenUSD` retained as the parsed runtime.
Profiles may select feature names, runtimes, and versions with
wildcards such as `FET004.*` and `FET004.PhysX.*`; feature and capability selectors may both be
optional. Required selectors must match the loaded catalog.

Profile selectors require an explicit version or version wildcard. A bare name or family
such as `FET004_Multibody` or `FET004` is invalid, including in optional entries.
Two-part selectors match neutral versions, with one explicit shorthand: `name.*`
matches every runtime and version. Three-part selectors specify both runtime and
version patterns. Capability selectors follow the same rules.

| Profile selector | Matches |
|---|---|
| `FET004_Multibody.*` | Every version and runtime of this feature name |
| `FET004_Multibody.0*` | Neutral versions beginning with `0` |
| `FET004_Multibody.*.0*` | Versions beginning with `0`, across every runtime |
| `FET004_Multibody.0-2-0` | Neutral version `0-2-0` |
| `FET004_Multibody.PhysX.*` | Every PhysX version |
| `FET004_Multibody.OpenUSD.0*` | Neutral versions beginning with `0` |
| `FET004.*.0*` | Versions beginning with `0` for every runtime and name in family FET004 |

Versions are opaque tokens; leading zeroes and wildcard matching are preserved.
Exact contract IDs and dependency references keep their existing meaning: an ID such as
`FET004_Multibody.0-2-0` identifies only the neutral contract outside a profile selector.
Duplicate contracts using both neutral spellings are rejected.

This selector policy intentionally rejects bare selectors and removes two-part runtime
shorthand. Existing tier profiles and their upstream resolver need to align: add `.*`
to bare names and runtime shorthand. `name.OpenUSD.*` is invalid in profiles and CLI
normalization: removing `OpenUSD` would produce `name.*` and silently expand selection
to every runtime. Version-specific neutral aliases such as `name.OpenUSD.0*` remain
valid. CLI feature prefixes are separate from profile selectors.

To compare both readers against every tier in a source checkout, set
`SIMREADY_FOUNDATIONS_CHECKOUT` to that checkout and run
`python -m pytest source/libraries/validate/tests/integration/test_foundations_catalog_compatibility.py`
in the Validate/Evaluate integration test environment. This checks registered IDs, profile
versions, dependency expansion, and optionality against the checkout's own resolver.
It reports differences when that checkout still uses an older selector policy.
Requirement registration is scaffolded for this catalog test; it does not qualify asset
validation rules or simulator execution.

A runtime Foundations 2 `FET` declares `runtime_tests`, `additional_requirements`, and
`adapters`. A testless `FET` is valid only as `source=true` provenance for at least one tested
derived FET; other static-only bundles use a `CAP`-prefixed capability. A feature may reference
exact capability IDs, and both feature and capability dependencies inherit optionality; any
required path wins. The validation registry uses an internal `0.0.0` SemVer sentinel for these
contracts, but public summaries expose only the complete dotted contract ID.

Profile data (rules, features, profile TOML) is loaded via `initialize()`. When running inside
a Kit environment, profiles are already registered and `initialize()` can be omitted.

### Validate one asset against multiple profiles

Profile targets are caller-supplied and evaluated independently. After initialization,
inspect `sv.get_available_profiles()` and set `requested_registered_profiles` to the
exact `(profile_id, profile_version)` pairs requested by the caller from that mapping.
Keep the requested order; each version is the complete registered version string.

```python
results = sv.validate_asset_against_profiles(
    "/assets/props/crate_01/crate_01.usd",
    [sv.ProfileTarget(pid, ver) for pid, ver in requested_registered_profiles],
    write_metadata=True,
)
```

Multi-profile metadata is stored under `SimReady_Metadata.validation.profiles`, keyed by
`<profile>@<version>`, so one result does not overwrite another.

### Legacy profile inference

If `profile_id` is omitted from `AssetValidationConfig`, the library first reads
`SimReady_Metadata.validation.profile` from the asset's `.simready/assets/<asset-key>/validation.json`
receipt, then falls back to the same metadata embedded in USD `customLayerData`.
This allows previously-stamped assets to be re-validated without specifying the profile.

### Stamping results into USD

Setting `write_metadata=True` writes the validation outcome to the wrapped
`.simready/assets/<asset-key>/validation.json` receipt while preserving unknown receipt keys. For writable
`.usd`, `.usda`, and `.usdc` assets, the same metadata is embedded in
`customLayerData["SimReady_Metadata"]["validation"]`. USDZ archives are read-only for this
operation: their bytes are preserved and only the receipt is written. Writes use atomic
same-directory replacements. Stamping applies to both passing and failing results.

### Runtime variant validation

For Foundations 2 physics features (PhysX, Newton, MuJoCo), the runtime is derived from the
middle segment of the feature ID; no separate `runtime` or `version` identity field is allowed.
Published Foundations 1 manifests with a separate `runtime` remain readable. When validating,
the library groups the profile's requirements by that runtime. Among the profile-referenced
runtime sets present on the default prim, it selects each participating set's neutral
option for the neutral base and activates only the target set for each runtime group — so runtime-specific
schemas (which compose only when the variant is on) are visible to their rules. Requirements
shared with the neutral base are checked once. Canonical `Enabled`/`Disabled` options are
resolved by name, regardless of the currently selected option. Custom options require
`SimReady_Metadata.Variants.Physics.<runtime>.activateOption` metadata and an unambiguous
neutral option; invalid configuration raises an error. Unreferenced variant sets retain their
incoming selections. Temporary selections are applied on
the stage's session layer and prior session opinions are restored after validation, including
on errors and cancellation. If cleanup is rejected, remaining owned cleanup is
attempted and failures are explicit: the original error/cancellation stays primary,
or a cleanup-only error is raised. Caller permissions are not overridden.
Adding a new physics engine is a data-only change (a new
dotted runtime segment, or legacy `runtime` value); no code change is required. See
[`docs/api.md`](docs/api.md#runtime-variant-validation) for details.

---

## Python API

### Initialization

```python
sv.initialize(
    rules_and_requirements_paths: list[Path],
    features_paths:               list[Path],
    profiles_paths:               list[Path],
) -> None

sv.destroy() -> None
```

#### From a project config file

```python
# Reads [validate] section from project_config.toml and calls initialize()
sv.initialize_from_config("/workspace/project_config.toml")
```

`project_config.toml` format:

```toml
[project_root]
setting = ".."   # optional offset from config file's directory

[validate]
requirements_paths = ["nv_core/tiers/simready_foundation_tier_core/simready/foundation/tier_core/rules_and_reqs"]
features_paths     = ["nv_core/tiers/simready_foundation_tier_core/simready/foundation/tier_core/capabilities", "nv_core/tiers/simready_foundation_tier_core/simready/foundation/tier_core/features"]
profiles_paths     = ["nv_core/tiers/simready_foundation_tier_core/simready/foundation/tier_core/profiles"]

[docs]
url = "https://nvidia.github.io/simready-foundation/latest/"
```

Omit `[validate]` entirely to load installed tier wheels instead (see
[Initialization](#initialization)). When the paths *are* given, they may point either at a
tier's package tree, as above, or at a plain spec folder with no owning Python package.

This source-checkout example resolves from the Foundation repository root and
requires the selected rules' schema dependencies. `rules_and_reqs` supplies Python
validators and requirement definitions; `capabilities` and `features` supply the
contract catalog. Explicit paths replace installed-tier discovery.

Selected checker execution ERRORs are unavailable evaluation, with or without
attached requirements and regardless of optionality, not measured asset failures.
`validate_stage` raises a contextual error after restoring caller state;
`validate_asset` logs the cause and returns `None`, and batch preserves that index.
The CLI exits nonzero; no new result is stamped or emitted for that member.
Historical report/receipt entries are not current execution evidence.

A selected rule's FAILURE without an attached requirement is retained and
attributed to that rule's selected requirements in the current runtime bucket.
Mandatory and optional requirements keep their own failure semantics; unrelated
requirements registered to the same rule are not selected or failed. Missing
rule provenance is unavailable evaluation rather than a passing measurement.

USD validation also refuses selected rules that have no USD assessment callback.
In particular, `CheckFormatDependency`-only rules require a registered non-USD
format handler and cannot assess a USD stage. The error identifies the profile,
runtime bucket, rule, and selected requirements; even an optional unavailable
assessment cannot produce a profile PASS or a new stamp. Mixed-domain rules that
also implement USD callbacks remain supported. Package definitions are a
separate input domain: use the package workflow's registered format handler;
passing a bare USD to a package-only profile does not validate its package.

### Validate a single asset

```python
sv.validate_asset(config: AssetValidationConfig) -> AssetValidationResult | None
```

Accepts `.usd`, `.usda`, `.usdc`, and `.usdz`. Returns `None` (with a distinct log
diagnostic) if the file is missing, unsupported, cannot be opened, has no usable
profile, or selected checker execution is unavailable.

### Validate multiple assets

```python
sv.validate_asset_list(
    configs:          list[AssetValidationConfig],
    report_file_path: str | None = None,          # merged JSON report
) -> list[AssetValidationResult | None]
```

### Configuration and result types

```python
@dataclass
class AssetValidationConfig:
    asset_path:      str       # path to .usd / .usda / .usdc / .usdz file
    profile_id:      str | None = None   # None → receipt first, then USD metadata
    profile_version: str | None = None   # None → any registered version
    write_metadata:  bool = False         # stamp results into USD (pass or fail)

@dataclass
class AssetValidationResult:
    asset_path:       str
    profile_id:       str
    profile_version:  str
    features_summary: dict[str, dict]   # feature_id → {version, passed, failing requirements}
    issues:           list              # completed FAILUREs tied to mandatory requirements
    soft_issues:      list              # completed nonblocking FAILUREs
```

`issues` and `soft_issues` together contain the completed evaluation's measured
failures. Optional-only failure can leave `issues=[]` and `soft_issues` nonempty
while the profile passes. A selected engine `ERROR` makes evaluation unavailable:
`validate_stage` raises and `validate_asset` logs the error and returns `None`.

### Batch validation with JSON report

```python
from pathlib import Path

configs = [
    sv.AssetValidationConfig(asset_path=str(p), profile_id=profile_id, profile_version=profile_version)
    for p in Path("/assets").rglob("*.usd")
]

results = sv.validate_asset_list(configs, report_file_path="/reports/validation.json")

n_passed = sum(
    1 for r in results
    if r and sv.features_summary_passed(r.features_summary)
)
print(f"{n_passed}/{len(configs)} passed")
for config, result in zip(configs, results):
    if result is None:
        print(f"UNAVAILABLE  {config.asset_path}")
    elif not result.features_summary:
        print(f"NO COVERAGE  {config.asset_path}")
    elif sv.features_summary_passed(result.features_summary):
        print(f"PASS  {config.asset_path}")
    else:
        print(f"FAIL  {config.asset_path}")
    if result is not None:
        for feature_id, entry in result.features_summary.items():
            if not entry["passed"]:
                print(feature_id, "blocking:", sv.is_blocking_failure(entry),
                      "failing requirements:", entry.get("failing requirements"),
                      "optional requirements:", entry.get("optional requirements"))
```

The JSON report updates each exact attempted asset/profile/version: a completed
result replaces its old record; `None` removes that target's old record. Unrequested
asset/profile history remains. Parent directories are created. Existing relative
keys resolve against the report directory, current request paths against cwd;
same basenames do not identify the same asset. Multi-profile publication follows
the same rule, and repeated list requests are processed in order.

Malformed/conflicting existing output or an unavailable inferred-profile request
whose current identity cannot be resolved against history fails publication before
writing, preserving the old bytes. Use an explicit target or a fresh destination;
the unchanged old file remains historical, not a successful current report.
The CLI includes missing requested members, even an all-missing list, and exits
nonzero without claiming publication success on an output error. No source stamps
are cleared and no global freshness/expiry guarantee is supplied. Check current
requested coverage and publication/source/build provenance before Evaluate use.

---

## CLI

The `simready-validate` command is included with the package.

```bash
# Validate a single asset
simready-validate \
  --profile "$PROFILE_ID" --version "$PROFILE_VERSION" \
  /assets/crate_01.usd

# Validate a list of assets and save a JSON report
simready-validate \
  --profile "$PROFILE_ID" --version "$PROFILE_VERSION" \
  --output /reports/results.json \
  --asset_list assets.txt

# Stamp results into the USD (pass or fail)
simready-validate ... --stamp-asset-validation /assets/crate_01.usd

# Print differences from each asset's last stamp
simready-validate --audit --asset_list assets.txt

# Load paths from a project config file
simready-validate \
  --project-config /workspace/project_config.toml \
  --profile "$PROFILE_ID" --version "$PROFILE_VERSION" \
  /assets/crate_01.usd
```

| Flag | Description |
|------|-------------|
| `ASSET_PATH` | Single `.usd` / `.usda` / `.usdc` / `.usdz` file to validate |
| `--asset_list FILE` | Text file, one asset path per line |
| `--profile ID` | Profile to validate against (omit for receipt-first inference) |
| `--version VER` | Profile version (requires `--profile`) |
| `--stamp-asset-validation` | Write the receipt and, except for USDZ, USD `customLayerData` |
| `--audit` | Print differences from each asset's last validation stamp |
| `--output JSON` | Publish current attempted identities while preserving unrequested history |
| `--project-config TOML` | Load spec paths from `project_config.toml` `[validate]` section |
| `--rules-path DIR` / `--features-path DIR` | Rules/features directories (repeatable; must be directories) |
| `--profiles-path DIR_OR_FILE` | Profiles directory or a single `.toml` file (repeatable) |
| `-v` / `--verbose` | Detailed mandatory and optional measured issues, including nonblocking optional issues on passing profiles |

Exit code: `0` = all passed, `1` = any failed or not found. With `--audit`, `0` = every
asset matches its last stamp.

---

## Metadata ownership

`simready.validate` owns only the `validation` sub-key of `SimReady_Metadata` in USD
`customLayerData` and in the wrapped receipt. It preserves `runtime_testing`, `asset_id`,
and all other unknown receipt or metadata keys.

```
customLayerData["SimReady_Metadata"]
├── asset_id        <- simready.create
├── validation      <- simready.validate
└── runtime_testing.tested_features   <- simready.test
```

---

## Tests

Run the standalone producer and the explicit cross-library handoff suite in
separate environments, as CI does:

```powershell
.\repo.bat test -s lib_validate lib_validate_evaluate_integration -c release
```

On Linux, use `./repo.sh` with the same arguments. Both suites are part of the
default test run. `lib_validate` uses only Validate's test requirements and
excludes `tests/integration`; it must not require Evaluate. The integration
suite combines the declared test requirements and exercises the current source
producer and Evaluate consumer, including stale-report invalidation, exact
asset identity and duplicate-key rejection. It does not install a Evaluate
wheel or add a production dependency or release-version pin.

For direct pytest runs, pass `--ignore=source/libraries/validate/tests/integration`
when selecting the standalone `source/libraries/validate/tests` tree; select the
integration directory explicitly in an environment provisioned with
`tests/requirements-integration.txt` to exercise the handoff checks.

## License

Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0

Validation results order both mandatory `issues` and optional `soft_issues` by
requirement code, qualified rule class, USD location identifier, then message.
Duplicate issues are retained. This order is independent of checker scheduling
and `PYTHONHASHSEED`; issue counts and validation verdicts are unchanged.
