Shared repository tooling#

ovclash/tooling/ is a small package for the source checkout. The KPI performance benchmarks, the Sentinel correctness campaign, the validation task runner scripts/run_parallel.py, the Python tests and the CMake build scripts share it. The SDK archive and the wheel do not contain it. The scripts of the source-only viewer sample on ovRTX, NVIDIA’s RTX rendering runtime, use version.py too. They run from the project root, where Python puts the script directory on sys.path, so they need no extra step, and they build their version label from read_version().

Path

Provides

Used by

process_tree.py

Process supervision

KPI, Sentinel, scripts/run_parallel.py, Python tests

git.py

Git policy

KPI source identity, Sentinel fixture check

ci_context.py, ci_context.cmake, ci_providers/

CI context for Python and CMake

KPI, Sentinel, CMake scripts

version.py

Version identity

KPI, Sentinel, the ovRTX viewer scripts

console.py

Human console formatting

Sentinel

Rules for the whole package:

  • The Python modules use only the standard library.

  • The CMake configure step and the build scripts need this directory too. scripts/crossplatform_helpers.cmake and scripts/validation_receipt.cmake include ci_context.cmake.

  • Every Python file under tooling/ is part of the KPI measurement identity (measurement_digest() in benchmarks/kpi/execution.py). Editing any of them starts a new measurement source. KPI does not pool campaigns from before and after the edit; see KPI.

Imports#

Import tooling as a top-level package, with the ovclash project root on sys.path:

  • Each script entry point under scripts/ derives the project root from its own file and puts it on sys.path before it imports tooling. The script then works from any working directory, without PYTHONPATH and under isolated Python (-I).

  • python -m benchmarks.kpi adds no path. It imports tooling from the working directory, so run it from the project root.

A new entry point under scripts/ follows the same pattern:

import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
if str(PROJECT) not in sys.path:
    sys.path.insert(0, str(PROJECT))

from tooling.process_tree import ProcessCancelled, ProcessCleanupError, run_process

Always use the canonical module name, such as tooling.process_tree. A module loaded a second time under another name defines its own exception classes. except ProcessCleanupError then misses the errors of the other copy.

Process supervision#

process_tree.run_process() runs one noninteractive command and owns its whole process tree:

run_process(argv, *, timeout=None, check=False, capture_output=False, cancel=None, **kwargs)

It returns a subprocess.CompletedProcess only after every owned descendant has exited.

import subprocess
import sys

from tooling.process_tree import run_process

result = run_process([sys.executable, "-c", "print('hello')"], timeout=60, capture_output=True, text=True)
print(result.returncode, result.stdout.strip())

try:
    run_process([sys.executable, "-c", "import time; time.sleep(30)"], timeout=1)
except subprocess.TimeoutExpired:
    print("timed out")
0 hello
timed out

Arguments#

Argument

Rule

argv

A nonempty argv sequence. A string, bytes or an empty sequence raises ValueError.

timeout

None for no deadline, or a positive, finite int or float. Anything else raises ValueError. The deadline covers the command and the exit of its whole tree, so a command that exits while a descendant keeps running still times out.

check

True raises subprocess.CalledProcessError for a nonzero exit, after the tree has drained.

capture_output

True captures both streams. Combining it with stdout or stderr raises ValueError.

cancel

An optional threading.Event; see Cancellation. An object without is_set() raises TypeError.

Accepted keywords

env, cwd, stdout, stderr, text, encoding, errors, bufsize, universal_newlines, pass_fds, and shell=False.

Rejected keywords

shell=True, stdin, input, start_new_session, creationflags and any keyword that the Accepted keywords row does not name raise ValueError.

The caller supplies the deadline, environment, working directory and output streams. run_process passes the environment through unchanged. The command’s standard input is always the null device. Concurrent calls own independent trees, deadlines and cleanup.

How each platform owns the tree#

Platform

Mechanism

Windows

A launcher joins a Job Object before it starts the command, so even an immediate grandchild is in the job. Closing the job kills its remaining members, also when the calling process dies.

Linux

A dedicated subreaper process starts in a new session. It owns and reaps every descendant, including those in nested sessions, and drains its tree when the calling process dies. Signal handling and reaping stay in that process; the caller’s signal handlers do not change.

Other POSIX hosts

The command starts in a new process group. Descendants must stay in that group.

On Windows and Linux the supervisor runs process_tree.py itself under isolated Python (-I). Keep that file, including its private launcher entry points, runnable on its own with only the standard library.

Linux shared-memory cleanup#

The runtime of ovstage, the package through which ovclash reads USD, can leave two names of Carbonite, NVIDIA’s plugin and runtime framework, in /dev/shm behind, even after a normal exit: carb-RStringInternals-<PID> and sem.carb-RStringInternals-<PID>. The Linux supervisor cleans them up for each exited child:

  1. It holds the exited child’s PID with waitid(..., WNOWAIT).

  2. It removes the two names when its effective user owns them.

  3. Only then does it reap the child.

It never scans /dev/shm and never removes a name of a live or unrelated process. When a removal fails, the supervisor kills the rest of the tree, still cleans up and reaps every remaining child, and then run_process raises ProcessCleanupError. The error’s returncode attribute holds the command’s exit status. A child that an intermediate process reaps itself is outside this cleanup, so nested launchers call run_process too.

Timeouts, interruptions and cleanup#

On a timeout or an interruption, run_process terminates the owned tree, waits for it to drain and re-raises the original exception. A subprocess.TimeoutExpired then carries the command and the output collected up to the end of the drain.

The drain has its own deadline, CLEANUP_TIMEOUT_SECONDS (30 s), which starts after the failure. A call that times out, is interrupted or is cancelled can therefore take up to timeout plus 30 s. Size outer deadlines for that.

If the drain cannot be confirmed, run_process raises ProcessCleanupError, a subclass of RuntimeError. The caller then cannot accept output that may still change. A confirmed drain says nothing about whether the output is correct; each caller validates its own results.

Cancellation#

Python delivers Ctrl+C only to the main thread. To stop a call that runs on a worker thread, pass a threading.Event as cancel:

import sys
import threading

from tooling.process_tree import ProcessCancelled, run_process

stop = threading.Event()


def worker():
    try:
        run_process([sys.executable, "-c", "import time; time.sleep(60)"], timeout=120, cancel=stop)
    except ProcessCancelled:
        print("cancelled")


thread = threading.Thread(target=worker)
thread.start()
stop.set()  # for example, from the main thread's Ctrl+C handler
thread.join()
  • The call checks the event at least every CANCEL_POLL_SECONDS (0.1 s) while it waits.

  • Once the event is set, the call drains the tree as for an interruption and raises ProcessCancelled.

  • An event that is already set starts no process. On Linux, a cancellation, timeout or interruption before the supervisor confirms ownership also starts no command.

  • ProcessCancelled derives from BaseException, like KeyboardInterrupt. An except Exception handler therefore does not absorb a requested stop.

  • The deadline still raises subprocess.TimeoutExpired, not ProcessCancelled.

Tests#

After you change process_tree.py, run both of its test modules in tests/python_tests/:

  • test_process_tree.py covers the readiness helpers, the cancellable waits and real writer trees through timeouts, interrupts and cancellation.

  • test_process_tree_owners.py covers the platform ownership backends: Linux IPC cleanup and ownership receipts, Windows Job draining and Windows cleanup errors.

Before you begin: a run of the Python tests, such as --validate or the test_python_runtime target, has created the test interpreter in _build/deps/venv/python_tests; Test and validate describes those runs.

From ovclash/, on Linux:

_build/deps/venv/python_tests/bin/python -m unittest discover -s tests/python_tests -t tests/python_tests -p "test_process_tree*.py"

On Windows:

_build\deps\venv\python_tests\Scripts\python.exe -m unittest discover -s tests/python_tests -t tests/python_tests -p "test_process_tree*.py"

The run passes when unittest ends with an OK line and the command exits with code 0.

Both modules belong to the Sentinel checker group. --validate does not run that group unless OVCLASH_VALIDATE_EXTRA_TARGETS names test_sentinel_checkers. Run the group with Sentinel’s check-tests command or the test_sentinel_checkers target, as Checker tests describes. Sentinel’s own supervision tests are in test_sentinel_serialization_process_tree.py.

Git policy#

git.py keeps Git noninteractive. run_process applies no Git policy, so each caller applies it explicitly:

  • git_environment(env=None) returns a copy of env (default os.environ) with GIT_TERMINAL_PROMPT=0 and GCM_INTERACTIVE=never. Neither Git nor Git Credential Manager can then prompt. env itself is not modified.

  • GIT_TIMEOUT_SECONDS (120) is the deadline for each Git command.

from tooling.git import GIT_TIMEOUT_SECONDS, git_environment
from tooling.process_tree import run_process

head = run_process(
    ["git", "rev-parse", "HEAD"],
    env=git_environment(),
    timeout=GIT_TIMEOUT_SECONDS,
    capture_output=True,
    text=True,
)

The callers are KPI’s source identity (scripts/kpi_startup.py) and Sentinel’s optional fixture-membership check (scripts/sentinel_ci.py).

The Sentinel check trusts only the selected source root, through a private Git configuration:

  • It writes a safe.directory entry for that root, with forward slashes, into a temporary .gitconfig.

  • It sets GIT_CONFIG_GLOBAL to that file, HOME to its private directory and XDG_CONFIG_HOME inside that directory. Git versions that ignore a command-line safe.directory, or that predate GIT_CONFIG_GLOBAL, therefore read the same entry.

  • It drops inherited GIT_* variables and sets GIT_CONFIG_NOSYSTEM=1, so the system Git configuration does not apply.

It never changes the user’s Git configuration.

CI context#

ci_context.current(env=None) reads env (default os.environ) and returns a dict of private execution state. It holds no endpoint or credential. Do not serialize it: public evidence admits only separately validated IDs.

import os

from tooling import ci_context

context = {
    "CI_JOB_ID": "4242",
    "CI_PIPELINE_ID": "77",
    "CI_COMMIT_SHA": os.environ.get("CI_COMMIT_SHA", "<source-revision>"),
}
print(ci_context.current(context))
print(ci_context.current({"OVCLASH_CI_PROVIDER": "jenkins", "OVCLASH_CI_JOB_ID": "15"}))

The first call reads the revision from CI_COMMIT_SHA. When it is unset, the example uses <source-revision> as a placeholder, which the first line of this output shows.

{'is_ci': True, 'source_revision': '<source-revision>', 'job_id': 4242, 'pipeline_id': 77, 'project_id': None, 'job_timeout': '', 'job_started_at': ''}
{'is_ci': True, 'source_revision': None, 'job_id': 15, 'pipeline_id': None, 'project_id': None, 'job_timeout': '', 'job_started_at': ''}

current() builds the context in two steps:

  1. Declared or detected. Setting OVCLASH_CI_JOB_ID (even to an empty value) or OVCLASH_CI_PROVIDER declares a provider-neutral CI job. is_ci is then true, and provider detection is skipped. A set OVCLASH_CI_PROVIDER must be 1 to 63 lowercase letters, digits and hyphens that start with a letter; otherwise current() raises ValueError. Without a declaration, the GitLab adapter in ci_providers/ reads the CI_* variables. Only a nonblank CI_JOB_ID marks a CI job.

  2. Overrides. A set OVCLASH_CI_<FIELD> variable then replaces that one field.

Field

Override

GitLab source

Value

is_ci

Not overridable

Nonblank CI_JOB_ID

True or False

source_revision

OVCLASH_CI_SOURCE_REVISION

CI_COMMIT_SHA

String, or None

job_id

OVCLASH_CI_JOB_ID

CI_JOB_ID

Positive integer, or None

pipeline_id

OVCLASH_CI_PIPELINE_ID

CI_PIPELINE_ID

Positive integer, or None

project_id

OVCLASH_CI_PROJECT_ID

CI_PROJECT_ID

Positive integer, or None

job_timeout

OVCLASH_CI_JOB_TIMEOUT

CI_JOB_TIMEOUT

Seconds as a string, or ""

job_started_at

OVCLASH_CI_JOB_STARTED_AT

CI_JOB_STARTED_AT

ISO 8601 time with a UTC offset, or ""

An ID becomes None unless it is 1 to 20 ASCII digits with a positive value; surrounding whitespace is ignored. The string fields pass through unvalidated, and their consumers validate them. tests/python_tests/test_kpi_ci_context.py covers the Python side.

CMake#

CMake scripts call ovclash_ci_value(<NAME> <out>) from ci_context.cmake. A script in ovclash/scripts/, such as scripts/validation_receipt.cmake, includes it relative to its own directory:

include("${CMAKE_CURRENT_LIST_DIR}/../tooling/ci_context.cmake")
ovclash_ci_value(REF_NAME branch)
ovclash_ci_value(REF_PROTECTED protected)

The value comes from the first rule that applies:

  1. A defined OVCLASH_CI_<NAME> environment variable.

  2. An empty value, when OVCLASH_CI_PROVIDER or OVCLASH_CI_JOB_ID declares the context.

  3. The GitLab variable, read through ci_providers/provider.cmake and ci_providers/gitlab.cmake. An unset variable yields an empty value.

CMake does not check the provider name. Every value is a CMake string, and none is required: an unset source yields an empty value. The local version is the PEP 440 local version label (the +<label> suffix of the Python version-string standard).

Name

Type

Required

Default or values

Override

GitLab source

Use

SOURCE_REVISION

String

No

A commit ID, or empty

OVCLASH_CI_SOURCE_REVISION

CI_COMMIT_SHA

Commit of the PEP 440 local version

REF_NAME

String

No

A branch name, or empty

OVCLASH_CI_REF_NAME

CI_COMMIT_REF_NAME

Branch of the PEP 440 local version

REF_PROTECTED

String

No

true or false; empty or any other value records null

OVCLASH_CI_REF_PROTECTED

CI_COMMIT_REF_PROTECTED

Signing policy of the validation receipt

  • scripts/crossplatform_helpers.cmake reads REF_NAME and SOURCE_REVISION before it consults Git. It builds the PEP 440 local version of the wheel and the SDK archive from them.

  • scripts/validation_receipt.cmake records REF_PROTECTED as the receipt’s signing_policy.protected_ref: true, false, or null for any other value.

  • Python has no ref-name or ref-protection field.

  • Keep the SOURCE_REVISION mapping in gitlab.cmake in step with gitlab.py.

Run KPI in another CI system describes how KPI uses this context.

Version identity#

version.py reads ovclash/VERSION once, at import, without importing the ovclash package.

Function

Returns or does

read_version()

The version string, for example 0.2.0.

version_label()

ovclash <version>, the text that --version prints.

add_version_argument(parser)

Adds --version to an argparse parser and puts the label at the start of its description.

is_version_request(arguments, commands=())

Whether the arguments are exactly --version, or a listed subcommand path, such as "budget create", followed by --version.

KPI and Sentinel commands call is_version_request() before their other imports. --version then prints the label without loading the rest of the command:

import sys

from tooling.version import add_version_argument, is_version_request, version_label

if is_version_request(sys.argv[1:], commands=("budget create",)):
    print(version_label())
    raise SystemExit(0)

import argparse  # the command's other imports follow the early exit

parser = argparse.ArgumentParser(description="Example command.")
add_version_argument(parser)
$ python example.py budget create --version
ovclash <version>

Human console formatting#

console.py renders Sentinel’s human console output: run and checker status lines, help headings and the success footer. tests/sentinel/timing.py, scripts/sentinel_ci.py and scripts/run_sentinel.py call it. Console output in the Sentinel guide describes the line formats.

Color is used only when all of these hold:

  • The selected output stream is a terminal.

  • NO_COLOR is unset or empty, and TERM is not dumb.

  • On Windows, virtual terminal (VT) processing, the console mode that interprets ANSI escape sequences, can be enabled on that console. console.py enables it and keeps the console’s other mode flags.

Otherwise the output is plain, and render_status() strips any ANSI sequences the text already carries:

from tooling import console

line = "[ 3/12]  25% PASS   1.250s  test_native_engine"
print(repr(console.render_status(line, enabled=True)))
print(repr(console.render_status("\x1b[92mPASS\x1b[39m done", enabled=False)))
'[ 3/12]  25% \x1b[92mPASS\x1b[39m   1.250s  \x1b[38;2;183;143;255mtest_native_engine\x1b[39m'
'PASS done'

Only the foreground color changes:

Text

Color

The label of a check line or timing row, and the == <label> part of a phase line

Violet #B78FFF

Whole heading lines, such as Sentinel run started ..., the opening Results: ... line, Plan: ..., the SUMMARY and TOTAL lines of a timing table, Sentinel summary and Checker summary

Violet #B78FFF

Section headings of the test_sentinel help

Violet #B78FFF

OK, PASS, PASSED outside heading lines

Bright green

FAIL, FAILED, ERROR outside heading lines, and the word failed in a final failure line

Bright red

The complete success footer, including its heart

Bright green (ANSI 92), matching KPI success messages

A heading line is one that its caller prints as a heading, or one that starts with a prefix in _HEADINGS. Everything else stays plain:

  • the counter, percentage, duration and run time of check lines, timing rows and phase lines;

  • the words START, NOT_RUN, RUNNING and WARN;

  • lowercase words, such as failed in 0 failed.

Progress records, timing evidence and JSON are never styled. Styling plays no part in any verdict or timing measurement.

The CHECK, ROW and PHASE patterns in console.py mirror CHECK_PATTERN, ROW_PATTERN and PHASE_PATTERN in tests/sentinel/timing.py. tests/python_tests/test_sentinel_console.py keeps them in agreement, so change both together.

KPI does not use this module. It styles its console output with benchmarks/kpi/console_style.py, which uses the same violet, bright green and bright red. A change to console.py therefore does not change KPI’s console output. Like any tooling/ edit, it still starts a new KPI measurement source.