Asynchronous Pipelines#

ovclash, the clash detection library for USD scenes, can run a query on a background worker. The calling thread stays free to draw a progress bar or service a UI event loop. The async surface is small, and it rests on one rule:

A context runs at most one asynchronous operation at a time. Finish or drain that operation before you read results or reuse its context.

Both public layers have the same shape:

  • the canonical C ABI in <ovclash/ovclash.h>, with its ovclash Python binding;

  • the Suite C ABI in <ovclash_suite/ovclash_suite.h>, with its ovclash_suite Python binding.

Each layer has one async call that the other lacks: only the canonical layer has ovclash_async_is_cancelled, and only the Suite layer has ovclash_suite_async_destroy. The asynchronous pipeline lists both.

The released packages use the ovstage backend, and this page describes it. The unpublished OpenUSD reference build differs in cancellation scope, progress values and status fidelity; the comments in <ovclash/ovclash.h> and <ovclash_suite/ovclash_suite.h> document each difference. References in the package lists these headers.

The synchronous pipeline first#

The async surface does not replace the pipeline model; it drives it. A query is a sequence of steps. You build that sequence before you run it, in either mode.

Canonical C

Suite C

What it does

ovclash_create_pipeline(context, uint32_t* out_step_count)

ovclash_suite_create_pipeline(runtime, uint32_t* out_step_count)

Builds the pipeline for the current settings, scope and times, and reports its step count.

ovclash_get_pipeline_step_data(context, ovclash_step_data_t* data, uint32_t index)

ovclash_suite_get_pipeline_step_data(runtime, uint32_t step_index, ovclash_suite_step_data_t* out_step_data)

Describes one planned step.

ovclash_run_pipeline_step(context, uint32_t index)

ovclash_suite_run_pipeline_step(runtime, uint32_t step_index)

Runs one step synchronously on the calling thread.

Step count. ovclash_create_pipeline derives the step count from startTime, endTime and timeCodesPerSecond, so set times, settings and scope first.

  • A valid context always yields at least 7 steps.

  • A static query (start time equal to end time) has 11 steps.

  • A dynamic query has 7 steps plus one step per sampled time.

The call does not check that a stage is open or a scope is set. Those failures surface later, from ovclash_run_pipeline_step or from the async run. ovclash_suite_create_pipeline also re-applies the scope set by ovclash_suite_set_scope.

Step order. Steps carry state. Run them in ascending order, 0 .. count-1.

  • Out-of-order execution is not diagnosed. Each step runs against whatever state exists.

  • The final step reports success without doing the work when earlier steps have not completed.

  • After the stage is replaced during a started pipeline, nonzero steps are rejected. Step 0, a new ovclash_create_pipeline or an async launch restarts the pipeline.

Step data. The step-data structs are value snapshots. They do not update as the run advances. The PipelineStepData of each Python package carries the same fields, in snake_case.

ovclash_step_data_t

ovclash_suite_step_data_t

Python PipelineStepData

Type

Required

Default or values

Meaning

name

name

name

ovclash_string_t, ovclash_suite_string_t; Python str or None

Yes

A step name

Step name. Canonical: a static, library-owned literal, valid for the process lifetime. Suite: borrowed from the runtime or async handle. Never free either.

stepIndex

step_index

step_index

uint32_t; Python int

Yes

0 to the step count minus 1

Zero-based index of this step.

nbSteps

nb_steps

nb_steps

uint32_t; Python int

Yes

7 or more for a valid context

Total number of steps.

progress

progress

progress

float

Yes

[0.0, 1.0]

Fraction of the pipeline.

stepProgress

–

step_progress (ovclash only)

float

Canonical layer only

[0.0, 1.0]

Fraction within the step.

finished

finished

finished

bool; Suite C uint32_t; Python bool

Yes

True for the last step index; ovclash_reset_step_data also sets it

True for the last step index, not for a completed run.

ovclash_get_pipeline_step_data returns the plan: progress = index / nbSteps, stepProgress = 0 and finished on the last index. Use the async snapshot call for live values. ovclash_reset_step_data sets finished to true, so finished is never an initialized-or-not test.

The asynchronous pipeline#

Canonical C

Suite C

What it does

ovclash_run_pipeline_async(context, ovclash_async_t** out_async)

ovclash_suite_run_pipeline_async(runtime, ovclash_suite_async_t** out_async)

Starts the prepared pipeline on a background worker and returns the async handle.

ovclash_is_pipeline_running(async, bool* out_running)

ovclash_suite_async_is_running(async_handle, uint32_t* out_running)

Polls whether the run is still active.

ovclash_get_pipeline_step_data_async(async, ovclash_step_data_t* data)

ovclash_suite_async_get_step_data(async_handle, ovclash_suite_step_data_t* out_step_data)

Snapshots the live step and progress.

ovclash_finish_pipeline(async)

ovclash_suite_async_finish(async_handle)

Blocks until the worker stops.

ovclash_cancel_pipeline(async)

ovclash_suite_async_cancel(async_handle)

Requests cancellation. Canonical C returns immediately. Suite C also waits for the worker to stop and consumes the run; the handle stays until ovclash_suite_async_destroy.

ovclash_async_is_cancelled(async, uint32_t* out_cancelled)

–

Reports whether cancellation was requested. Canonical layer only.

–

ovclash_suite_async_destroy(async_handle)

Frees the handle, finishing an unfinished run first. Suite layer only; accepts null.

The two layers differ in who frees the handle:

  • Canonical C. There is no ovclash_async_destroy. ovclash_finish_pipeline destroys the handle. Call it exactly once per handle, also after a cancel. Cancel neither joins the worker nor frees anything.

  • Suite C. ovclash_suite_async_finish or ovclash_suite_async_cancel consumes the run. After either, every other call on that handle returns OVCLASH_SUITE_STATUS_ERROR until ovclash_suite_async_destroy frees it. ovclash_suite_destroy_runtime does not cancel a live run. It blocks until the run completes, and the handle still needs ovclash_suite_async_destroy.

  • Python. Both AsyncPipeline classes pair these calls for you; see Python.

Launch rules.

  • ovclash_run_pipeline_async rejects a second launch while a handle is live.

  • A launch with a pipeline but no open stage succeeds, and ovclash_finish_pipeline then reports the missing stage.

  • The worker uses the launching thread’s floating-point controls as they were at launch: rounding, denormal handling and exception masks.

The live-handle guard. While a canonical handle is live, the owning context rejects almost every other entry point with “… is not allowed while an async pipeline handle is active”. The guard covers stage, settings and scope setters, pipeline creation and stepping, result, report, statistics and memory getters, and ovclash_reset_context. These calls stay legal:

  • the handle’s own calls: ovclash_is_pipeline_running, ovclash_get_pipeline_step_data_async, ovclash_async_is_cancelled, ovclash_cancel_pipeline and ovclash_finish_pipeline;

  • context-free calls, such as ovclash_get_version_string, ovclash_get_backend_info and the ovclash_reset_* struct initializers;

  • read-only getters that do not touch results: ovclash_get_last_error (which reads the rejection), ovclash_get_settings, ovclash_get_timeline_data and ovclash_ovstage_get_matrix_decomposition;

  • ovclash_release_overlap_report;

  • ovclash_release_context, which reclaims the live handle and can therefore block: it joins the worker.

Who lifts the guard:

  • On the canonical C ABI, only ovclash_finish_pipeline lifts it. Cancelling alone does not, although the rejection text ends with “finish or cancel the async pipeline first”.

  • ovclash_suite_async_cancel and both Python cancel() methods wait for the worker and consume the run, so they lift the guard.

  • The Suite C ABI and both Python packages apply the same guard to their own calls.

Three behaviors matter before you write the loop:

  • Starting without a pipeline is not an error. ovclash_run_pipeline_async without ovclash_create_pipeline succeeds, and the worker does no work.

  • is_running converges; a single reading proves nothing. Poll until it reports false, then finish the handle before you read results. A small fixture can complete before the first poll. It also reports false as soon as cancellation is requested, before the worker has stopped.

  • Do not derive completion from finished. It means “this is the last step index”, so it becomes true when the final step starts.

Progress values. progress is refined within a step from counted work. Neither progress nor stepProgress is a time estimate.

  • A poll returns a locked snapshot within [0.0, 1.0]. An operation that cannot be counted keeps its label and fraction until it finishes. An async step name can append the current operation to the phase name, for example Computing global mesh data... Reading transforms.

  • The Suite API forwards progress unclamped. Portable code clamps the value and treats a non-finite one as unknown, as the polling loop in ovclash.AsyncPipeline does.

Step timeline#

One complete asynchronous run on the canonical C ABI, in order. Each step is one call, except the polling loop of step 8:

  1. ovclash_create_context creates the context.

  2. ovclash_open_stage opens the stage.

  3. ovclash_set_settings applies the settings.

  4. ovclash_set_scope_paths sets the scope.

  5. ovclash_set_times sets the time range.

  6. ovclash_create_pipeline builds the pipeline and reports its step count, 7 or more.

  7. ovclash_run_pipeline_async starts the run and returns the async handle. The context guard closes.

  8. Poll ovclash_is_pipeline_running until it reports false.

  9. ovclash_finish_pipeline blocks until the worker stops, destroys the handle and opens the guard.

  10. ovclash_get_overlap_count reads the overlap count.

  11. ovclash_get_overlap_data reads the data of each overlap.

  12. ovclash_create_overlap_report_ex creates the overlap report of each record that you inspect.

  13. ovclash_get_query_stats reads the query statistics.

  14. ovclash_release_overlap_report releases each report.

  15. ovclash_release_context releases the context.

Inside the polling loop of step 8, ovclash_get_pipeline_step_data_async snapshots the step name, index and progress between polls, and ovclash_cancel_pipeline requests a stop when you want one.

Set the scope after ovclash_open_stage and ovclash_set_settings, because both clear it. ovclash_set_full_scene and ovclash_ovstage_attach_stage clear it too.

Step 9 is required, cancelled or not, and it must come before the result getters of steps 10 to 13:

  • It is the only call that joins the worker and frees the handle while it keeps the context.

  • ovclash_release_context also reclaims a live handle, but it destroys the context with it.

  • The result getters of steps 10 to 13 are exactly what the guard blocks.

ovclash_finish_pipeline returns the outcome of the run, not of the finishing:

  • It returns OVCLASH_STATUS_ERROR when the worker reported failure.

  • It returns OVCLASH_STATUS_ERROR when cancellation was requested before finish, even if the worker had already completed.

  • An uncancelled zero-work run succeeds.

  • Either way a valid handle is joined and freed, and the context is reusable.

  • A failed phase is reported as an error, and the context’s last error names the reason.

Steps 6 to 9 in C, for a context whose stage, settings and scope are already set. The function belongs in a C source file of your program; the C quickstart shows how to build one:

#include <ovclash/ovclash.h>
#include <stdio.h>

/* Runs the pipeline of a configured context on the worker and prints each new step.
 * Returns 1 for a successful, uncancelled run. */
static int run_async(ovclash_context_t* ctx)
{
    uint32_t step_count = 0;
    uint32_t last_step = UINT32_MAX;
    uint32_t cancelled = 0;
    bool running = true;
    ovclash_async_t* job = NULL;
    ovclash_result_t finished;

    if (ovclash_create_pipeline(ctx, &step_count).status != OVCLASH_STATUS_SUCCESS ||
        ovclash_run_pipeline_async(ctx, &job).status != OVCLASH_STATUS_SUCCESS)
    {
        return 0;
    }
    while (ovclash_is_pipeline_running(job, &running).status == OVCLASH_STATUS_SUCCESS && running)
    {
        ovclash_step_data_t step;
        if (ovclash_get_pipeline_step_data_async(job, &step).status == OVCLASH_STATUS_SUCCESS &&
            step.stepIndex != last_step && step.name.length > 0)
        {
            last_step = step.stepIndex;
            printf("[%u/%u] %.*s\n", (unsigned)step.stepIndex + 1, (unsigned)step.nbSteps, (int)step.name.length,
                   step.name.ptr);
        }
        /* A real loop sleeps or services its UI here. ovclash_cancel_pipeline(job) stops the run. */
    }
    ovclash_async_is_cancelled(job, &cancelled); /* read it before finish clears the flag */
    finished = ovclash_finish_pipeline(job); /* exactly once, cancelled or not: joins and frees job */
    job = NULL;
    return finished.status == OVCLASH_STATUS_SUCCESS && !cancelled;
}

On time_sampled.usda, the sample stage in samples/data/ of the SDK archive and of the installed ovclash package, with the ovstage backend it prints the steps that the polls observed, for example:

[1/11] Releasing previous data... Clearing retained results
[2/11] Finding meshes...
[3/11] Computing initial mesh data...
[6/11] Computing global mesh data... Reading transforms
[11/11] Processing results...

Which steps appear depends on timing: a step can start and end between two polls.

The same loop on the Suite C ABI. Finish, or cancel, consumes the run. Destroy frees the handle in every case:

#include <ovclash_suite/ovclash_suite.h>
#include <stdio.h>

/* Runs the pipeline of a configured Suite runtime on the worker and prints each new step.
 * Returns 1 for a successful run. */
static int run_suite_async(ovclash_suite_runtime_t* runtime)
{
    uint32_t step_count = 0;
    uint32_t last_step = UINT32_MAX;
    uint32_t running = 1;
    ovclash_suite_async_t* job = NULL;
    ovclash_suite_result_t finished;

    if (ovclash_suite_create_pipeline(runtime, &step_count).status != OVCLASH_SUITE_STATUS_SUCCESS ||
        ovclash_suite_run_pipeline_async(runtime, &job).status != OVCLASH_SUITE_STATUS_SUCCESS)
    {
        return 0;
    }
    while (ovclash_suite_async_is_running(job, &running).status == OVCLASH_SUITE_STATUS_SUCCESS && running)
    {
        ovclash_suite_step_data_t step;
        if (ovclash_suite_async_get_step_data(job, &step).status == OVCLASH_SUITE_STATUS_SUCCESS &&
            step.step_index != last_step && step.name.length > 0)
        {
            last_step = step.step_index; /* step.name is borrowed from the handle: print it now */
            printf("[%u/%u] %.*s\n", (unsigned)step.step_index + 1, (unsigned)step.nb_steps, (int)step.name.length,
                   step.name.ptr);
        }
        /* A real loop sleeps or services its UI here. ovclash_suite_async_cancel(job) stops the run. */
    }
    finished = ovclash_suite_async_finish(job); /* an error after a cancel: the run is consumed */
    ovclash_suite_async_destroy(job); /* required after finish or cancel */
    return finished.status == OVCLASH_SUITE_STATUS_SUCCESS;
}

Cancellation#

ovclash_cancel_pipeline requests a stop and returns immediately. Call ovclash_finish_pipeline afterwards.

  • Cancel may come from another thread while the run is active.

  • It must not run concurrently with, or after, the finish of that handle. It cannot interrupt a finish that is already blocked.

  • Finish clears the cancel flag.

On the Suite layer, an async handle and its runtime form one serialization domain: no call on the handle, cancel included, may overlap a call on its runtime.

The cancel flag belongs to the context. Cancelling one context does not affect another.

What a set flag does.

  • Later ovclash_run_pipeline_step calls on that context fail.

  • ovclash_finish_pipeline or ovclash_reset_context clears the flag.

  • When the broad phase finds more candidate pairs than the broad-phase limit (ovclash_set_broadphase_limit), the engine stops the run itself. That stop counts as cancellation, so finish then returns OVCLASH_STATUS_ERROR.

Reading the flag. ovclash_async_is_cancelled exists on the canonical layer only.

  • It stays legal while the handle is live, and it accepts a null handle.

  • It answers for the context, and reports 0 for a null handle.

  • Read it before finish, which clears the flag and consumes the handle.

A zero count is not proof of a clash-free scene. A cancelled query can return zero overlaps with a success status from the count getter. Check the cancellation state, the finish status and ovclash_is_out_of_memory. Cancellation requested after completion changes the finish status but does not erase the results.

In Python, is_cancelled() latches the request, so you can read it after the run is finished. The Python examples on this page open time_sampled.usda by a relative path, so run them from the directory that holds it: samples/data/ of the installed ovclash package for the wheel (see Quick start), or samples/data/ of the SDK archive.

from ovclash import ClashRuntime

with ClashRuntime() as runtime:
    runtime.open_stage("time_sampled.usda")
    with runtime.run_async() as pipeline:
        pipeline.cancel()  # requests the stop, then finishes the run
        cancelled = pipeline.is_cancelled()  # latched: stays True after the finish
    count = runtime.get_overlap_count()
    if cancelled:
        print(f"cancelled run: {count} overlaps is not a complete result")

Python#

Both Python packages expose an AsyncPipeline class. They are different types. Import from one package and stay in it; see Same names, different types.

ovclash.AsyncPipeline#

ClashRuntime.run_async() returns it.

Method

Behavior

step_data()

Live PipelineStepData snapshot, with the fields of the step-data table. After finish(), cancel() or close(), and while another thread’s finish() waits, it returns the last step observed. It raises RuntimeError when no step was ever read. A successful finish settles that step to finished at full progress. A failed or cancelled run keeps the last step observed.

is_running()

bool from ovclash_is_pipeline_running. False once finished or cancelled.

is_cancelled()

bool, latched in Python. It latches a cancel() request, or a native cancellation it read while the handle was live. It stays true after finish clears the native flag. Once the handle is released, it reports False for anything it did not latch, such as a broad-phase-limit stop. Read it before the handle is released, or call finish(), which raises for a cancelled run.

poll()

(running, step_data) in one call.

finish()

Blocks until the worker stops and frees the native handle. Raises RuntimeError when the run failed or cancellation was requested before finish. Later calls, and a call after cancel(), return without raising.

cancel()

Requests cancellation, then finishes the run, which lifts the runtime guard. Does not raise for the cancelled outcome. Raises RuntimeError when the native cancel request fails. No effect once finished.

close()

Finishes an unfinished run without raising for its outcome, so the native handle is not leaked. __exit__ and __del__ call it.

Notes:

  • ClashRuntime.run_async() builds the pipeline if none exists.

  • It first closes every open OverlapReport, because the worker rebuilds the arrays that their buffer views borrow.

  • The AsyncPipeline methods may be called from several threads. cancel() cannot interrupt a finish() already blocked on another thread. To cancel from a UI, poll and cancel on one thread, and call finish() there once the loop ends; see Threading and Ownership.

A polling loop, run from the stage’s directory as Cancellation describes:

import math
import time

from ovclash import ClashRuntime

with ClashRuntime() as runtime:
    runtime.open_stage("time_sampled.usda")
    with runtime.run_async() as pipeline:  # builds the pipeline when none exists
        percent = 0.0
        running = True
        while running:
            running, step = pipeline.poll()  # does not block
            if math.isfinite(step.progress):  # portable: treat a non-finite value as unknown
                percent = min(max(step.progress, 0.0), 1.0) * 100
            print(f"[{step.step_index + 1}/{step.nb_steps}] {step.name} {percent:.0f}%")
            if running:
                time.sleep(0.05)
        pipeline.finish()  # raises RuntimeError if the run failed or was cancelled
    print("overlaps:", runtime.get_overlap_count())

A run on the ovstage backend prints, for example:

[1/11] Releasing previous data... Clearing retained results 0%
[11/11] Processing results... Sorting reports 100%
overlaps: 7

ovclash_suite.AsyncPipeline#

ClashDetection.run_async_pipeline() returns it. run_async is an alias of that method.

Method

Behavior

step_data()

PipelineStepData (name, step_index, nb_steps, progress, finished). A finished or cancelled pipeline reports a cleared, completed step instead of raising.

is_running()

bool. A finished or cancelled pipeline reports False instead of raising.

poll()

(running, step_data). Both halves agree with is_running() and step_data().

finish()

Waits for the run, then destroys the native handle. Raises RuntimeError when the run failed. No effect once finished or cancelled.

cancel()

Requests cancellation, waits for the worker to stop and destroys the native handle.

close()

Destroys the native handle, finishing an unfinished run first. __exit__ and __del__ call it.

Notes:

  • The Suite class has no is_cancelled(), because ovclash_async_is_cancelled has no Suite counterpart.

  • ClashDetection also offers cookie-style helpers over the same object: get_async_pipeline_step_data(cookie), is_async_pipeline_running(cookie), finish_async_pipeline(cookie) and cancel_async_pipeline(cookie). The last two finish or cancel, then close.

The Suite loop, run from the stage’s directory as Cancellation describes:

import time

from ovclash_suite import ClashDetection

clash = ClashDetection()
try:
    clash.open_stage("time_sampled.usda")
    with clash.run_async_pipeline() as pipeline:  # builds the pipeline when none exists
        while pipeline.is_running():
            step = pipeline.step_data()
            print(f"[{step.step_index + 1}/{step.nb_steps}] {step.name}")
            time.sleep(0.05)
        pipeline.finish()  # raises RuntimeError if the run failed
    print("overlaps:", clash.get_nb_overlaps())
finally:
    clash.destroy()  # ClashDetection is not a context manager

Context managers and cleanup#

Both AsyncPipeline classes are context managers, and that is the recommended form. Leaving the with block releases the handle, even if the loop raised. ClashRuntime is a context manager too; ClashDetection is not.

  • Exceptional exit. On an exceptional exit, including KeyboardInterrupt, both AsyncPipeline classes and ClashRuntime request cancellation before they drain the active run.

  • Normal exit. A normal exit and an explicit close() or destroy() wait for completion.

  • Errors during cleanup. Cleanup still runs if cancellation fails. An exception raised in the block remains the primary error.

An exception, including an interrupt, can hide whether the native finish (canonical) or destroy (Suite) ran. The wrapper then retires the handle, instead of reusing a pointer that may already be freed.

  • That exception does not establish successful detection.

  • If cleanup remains uncertain, destroy the owning runtime to drain any worker it still owns.

  • On the canonical layer, ovclash_release_context also reclaims a live handle.

  • On the Suite layer, runtime destruction does not free the async handle itself. A handle retired before ovclash_suite_async_destroy ran stays allocated.

See Threading and Ownership.

Samples#

Samples describes both samples and their launchers.

  • The clash_api sample runs the canonical loop with --async, together with scoping, result reading and reports. clash_api_python.py uses ovclash, and ClashApi.cpp uses the canonical C ABI.

  • The clash_suite_api sample runs the Suite pipeline asynchronously by default. --async false runs it on the calling thread.

  • Both samples ship in samples/ of the SDK archive. Their Python versions also ship in samples/ of the wheel’s ovclash package.

Known rough edges#

  • No timeout. ovclash_finish_pipeline blocks until the worker stops, and nothing bounds it. A hung pipeline can only be abandoned with the process.

  • The outcome dies with the handle. Capture the finish status and the cancellation state when you get them. There is no way to ask afterwards: on the Suite layer, every later call on the consumed handle returns OVCLASH_SUITE_STATUS_ERROR.

  • Error text is context-wide. The worker writes the same last-error slot. A mid-run ovclash_get_last_error is safe, but it returns a nondeterministic message. Read it after finish, and treat it as diagnostic text, not as a per-operation error channel; see Threading and Ownership.

See also#