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 |
|---|---|---|
|
KPI, Sentinel, |
|
|
KPI source identity, Sentinel fixture check |
|
|
CI context for Python and CMake |
KPI, Sentinel, CMake scripts |
|
KPI, Sentinel, the ovRTX viewer scripts |
|
|
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.cmakeandscripts/validation_receipt.cmakeincludeci_context.cmake.Every Python file under
tooling/is part of the KPI measurement identity (measurement_digest()inbenchmarks/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 onsys.pathbefore it importstooling. The script then works from any working directory, withoutPYTHONPATHand under isolated Python (-I).python -m benchmarks.kpiadds no path. It importstoolingfrom 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 |
|---|---|
|
A nonempty argv sequence. A string, bytes or an empty sequence raises |
|
|
|
|
|
|
|
An optional |
Accepted keywords |
|
Rejected keywords |
|
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:
It holds the exited child’s PID with
waitid(..., WNOWAIT).It removes the two names when its effective user owns them.
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.
ProcessCancelledderives fromBaseException, likeKeyboardInterrupt. Anexcept Exceptionhandler therefore does not absorb a requested stop.The deadline still raises
subprocess.TimeoutExpired, notProcessCancelled.
Tests#
After you change process_tree.py, run both of its test modules in tests/python_tests/:
test_process_tree.pycovers the readiness helpers, the cancellable waits and real writer trees through timeouts, interrupts and cancellation.test_process_tree_owners.pycovers 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 ofenv(defaultos.environ) withGIT_TERMINAL_PROMPT=0andGCM_INTERACTIVE=never. Neither Git nor Git Credential Manager can then prompt.envitself 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.directoryentry for that root, with forward slashes, into a temporary.gitconfig.It sets
GIT_CONFIG_GLOBALto that file,HOMEto its private directory andXDG_CONFIG_HOMEinside that directory. Git versions that ignore a command-linesafe.directory, or that predateGIT_CONFIG_GLOBAL, therefore read the same entry.It drops inherited
GIT_*variables and setsGIT_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:
Declared or detected. Setting
OVCLASH_CI_JOB_ID(even to an empty value) orOVCLASH_CI_PROVIDERdeclares a provider-neutral CI job.is_ciis then true, and provider detection is skipped. A setOVCLASH_CI_PROVIDERmust be 1 to 63 lowercase letters, digits and hyphens that start with a letter; otherwisecurrent()raisesValueError. Without a declaration, the GitLab adapter inci_providers/reads theCI_*variables. Only a nonblankCI_JOB_IDmarks a CI job.Overrides. A set
OVCLASH_CI_<FIELD>variable then replaces that one field.
Field |
Override |
GitLab source |
Value |
|---|---|---|---|
|
Not overridable |
Nonblank |
|
|
|
|
String, or |
|
|
|
Positive integer, or |
|
|
|
Positive integer, or |
|
|
|
Positive integer, or |
|
|
|
Seconds as a string, or |
|
|
|
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:
A defined
OVCLASH_CI_<NAME>environment variable.An empty value, when
OVCLASH_CI_PROVIDERorOVCLASH_CI_JOB_IDdeclares the context.The GitLab variable, read through
ci_providers/provider.cmakeandci_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 |
|---|---|---|---|---|---|---|
|
String |
No |
A commit ID, or empty |
|
|
Commit of the PEP 440 local version |
|
String |
No |
A branch name, or empty |
|
|
Branch of the PEP 440 local version |
|
String |
No |
|
|
|
Signing policy of the validation receipt |
scripts/crossplatform_helpers.cmakereadsREF_NAMEandSOURCE_REVISIONbefore it consults Git. It builds the PEP 440 local version of the wheel and the SDK archive from them.scripts/validation_receipt.cmakerecordsREF_PROTECTEDas the receipt’ssigning_policy.protected_ref:true,false, ornullfor any other value.Python has no ref-name or ref-protection field.
Keep the
SOURCE_REVISIONmapping ingitlab.cmakein step withgitlab.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 |
|---|---|
|
The version string, for example |
|
|
|
Adds |
|
Whether the arguments are exactly |
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_COLORis unset or empty, andTERMis notdumb.On Windows, virtual terminal (VT) processing, the console mode that interprets ANSI escape sequences, can be enabled on that console.
console.pyenables 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 |
Violet |
Whole heading lines, such as |
Violet |
Section headings of the |
Violet |
|
Bright green |
|
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,RUNNINGandWARN;lowercase words, such as
failedin0 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.