Threading and Ownership#

ovclash is a handle-based C library with Python bindings over it. A handle is an opaque pointer to an object that the library creates, such as a context. Two rules shape everything on this page:

  • The caller serializes calls on a handle. A handle has no internal lock.

  • Most returned pointers and string views are borrowed. They point into storage that the library still owns.

This page states the threading and lifetime rules for the canonical ABI, the C ABI of the canonical API in <ovclash/ovclash.h>; the Suite ABI, the C ABI of the Suite API in <ovclash_suite/*.h>; and the two Python packages, ovclash and ovclash_suite. The headers ship in the SDK archive, and the per-function notes in them are authoritative.

The released packages use the ovstage backend, and this page describes it. The unpublished reference build, which reads USD through OpenUSD instead, has stricter limits in places; the per-function notes in the headers document each difference.

Rules at a glance#

Rule

Details

Drive one context or runtime from one thread at a time, or serialize the calls.

What a context owns

Independent contexts may be created and used concurrently.

What a context owns

Inputs are copied during the call. Handles returned through an out parameter belong to the caller; release each with its matching destroy or release call.

Ownership rules for the Suite models

Release every overlap report before the next step or run, and before you reset or release the context.

Borrowed memory

Copy borrowed strings, such as name0, name1 and error text, to keep them.

Borrowed memory, Error text lifetime

Call ovclash_finish_pipeline exactly once per async handle, also after a cancel.

Asynchronous Pipelines

Destroy Suite fetch operations and cursors before you change their runtime or store.

Suite fetch and cursor lifetime

Do not index results by position across runs.

Threading controls and result order

What a context owns#

The canonical ABI’s root object is ovclash_context_t*. ovclash_create_context() creates it, and ovclash_release_context() destroys it. A context owns:

  • the stage opened with ovclash_open_stage(). An attached stage, a borrowed ovstage Stage, stays caller-owned; see Attached ovstage Stages.

  • the settings and the scope paths

  • the pipeline and its step plan

  • the results: overlaps, duplicate records and the prim-path strings inside them

  • the async handle, while one is live

  • the last-error text

Releasing the context invalidates every borrowed view, async handle and result that belongs to it. Static strings stay valid for the process lifetime, for example step names and the text of ovclash_get_result_string(). Release your overlap reports before the context; see Borrowed memory.

One thread per context#

A context is not thread-safe. Drive one context from one thread at a time, or serialize the calls. Most entry points in the header carry the note “Threading: serialize all calls on one context.”

A function that allows a call from another thread says so in its own documentation. While an async pipeline is active, these calls may run on another thread:

  • ovclash_is_pipeline_running()

  • ovclash_get_pipeline_step_data_async()

  • ovclash_async_is_cancelled()

  • ovclash_cancel_pipeline()

None of them may overlap or follow ovclash_finish_pipeline() on the same handle. A cancel therefore cannot interrupt a finish that already blocks on another thread: cancel first, then finish.

Independent contexts may be created and used concurrently. Each context has its own cancellation flag, out-of-memory flag and error text. The implementation still keeps some process-global state, such as the stage and path registries, so do not assume a cross-context isolation that the headers do not document.

One async pipeline per context#

A context runs at most one async pipeline at a time. While a handle is live, the context rejects a second ovclash_run_pipeline_async() and almost every other entry point. Asynchronous Pipelines gives the handle lifecycle and lists the calls that stay legal, and Cancel a run after a deadline shows the cancel-then-finish sequence in C.

Suite handles#

The Suite ABI has the same shape, with its own handles:

Handle

What it holds

ovclash_suite_runtime_t

The stage, settings, scope, pipeline and results

ovclash_suite_async_t

A run started by ovclash_suite_run_pipeline_async()

ovclash_suite_overlap_report_t

A report over the runtime’s results

ovclash_suite_fetch_and_save_t, ovclash_suite_fetch_async_t

A fetch-and-save operation; see Suite fetch and cursor lifetime

ovclash_suite_data_t

A SQLite or JSON-directory store, with its ovclash_suite_overlap_cursor_t and ovclash_suite_frame_cursor_t cursors

The four model handles

See Ownership rules for the Suite models

ovclash_suite_export_text_t

Generated JSON or HTML text, valid until destroyed

The rules for these handles:

  • Serialize calls on one handle.

  • A runtime and its async handle share one serialization domain. The async calls update the runtime’s active-run guard and error text. No call on the async handle may overlap a call on its runtime, including ovclash_suite_get_last_error() and ovclash_suite_destroy_runtime(). Poll progress from another thread only while no call on the runtime is in flight.

  • The async handle may outlive its runtime. After the runtime is destroyed, every call on the async handle except ovclash_suite_async_destroy() fails.

  • Independent runtime handles may be used concurrently, like independent contexts.

  • Independent data and model handles may be used from different threads. Data handles remain subject to SQLite and filesystem locking for the same store path.

  • A directory store permits one open handle per root directory. For a deferred missing directory, ownership begins at the first write.

Suite fetch and cursor lifetime#

ovclash_suite_runtime_fetch_and_save_begin() reserves its runtime until ovclash_suite_runtime_fetch_and_save_destroy(). With a built-in store, the SQLite or directory store that its own serializer implements, it also reserves the data handle. The reservation stays after completion or failure. It is not a lock: it does not make concurrent calls on those handles safe. Serialize caller access.

Live dependent handle

Rejected owner operations

Still available

Synchronous fetch on a runtime

Destroy/reset, stage/settings/scope changes, pipeline creation/execution and depth computation

Read-only result access

Synchronous fetch on a built-in store

Public writes, commit, deferred-file-creation changes, open/save/save-as/migrate/close/destroy

Reads, including opening read cursors

Async fetch

Owner reads from any thread other than the fetch’s own worker; owner mutations and lifecycle calls from every thread, the worker included; both until fetch destruction

The fetch handle’s running/progress/count/error snapshots; owner error getters return the caller’s rejection text

Frame or overlap cursor

Store open/save/save-as/migrate/close/destroy, even for an empty or exhausted cursor

Reads and ordinary writes/commit, unless a fetch also reserves the store

  • A rejected owner operation returns an error and leaves the owner usable. Destroy the dependent handle before you retry.

  • Fetch and cursor guards do not extend the lifetime of separately created report handles.

  • A custom serializer must keep its user_data, destination and connection alive and stable until fetch destruction. Native code cannot guard an external store.

Synchronous fetch#

Drive a synchronous fetch with ovclash_suite_runtime_fetch_and_save_next() until it reports completion, then destroy it, whatever the outcome. This function belongs in a C source file of your program; call it after a completed run of runtime, with data an open built-in store that holds the query query_id:

#include <ovclash_suite/ovclash_suite.h>

static ovclash_suite_result_t save_results(ovclash_suite_runtime_t* runtime,
                                           ovclash_suite_data_t* data,
                                           int64_t query_id,
                                           double tolerance,
                                           double depth_epsilon)
{
    ovclash_suite_fetch_and_save_t* fetch = NULL;
    ovclash_suite_result_t result = ovclash_suite_runtime_fetch_and_save_begin(
        runtime, data, NULL /* built-in serializer */, query_id, tolerance, depth_epsilon,
        0 /* include_duplicates */, 1 /* resolve_stale */, &fetch);
    uint32_t complete = 0;
    while (result.status == OVCLASH_SUITE_STATUS_SUCCESS && !complete)
    {
        double progress = 0.0;
        result = ovclash_suite_runtime_fetch_and_save_next(fetch, &progress, &complete);
    }
    ovclash_suite_runtime_fetch_and_save_destroy(fetch); /* accepts NULL; never destroy twice */
    fetch = NULL;
    return result;
}
  • ovclash_suite_runtime_fetch_and_save_begin_with_reader() follows the same rules. Its custom reader runs on the thread that drives the fetch. Each reader output needs to stay valid only until the next reader callback. Drive and destroy the fetch on a thread that the reader’s resources allow.

  • Destroying a fetch consumes it even when overlap cleanup fails. Never destroy the same pointer twice.

  • An ovclash_suite_runtime_fetch_and_save_next() or destroy call from inside a running callback is rejected and does not consume the fetch.

  • A failed fetch cannot resume. Destroy it.

Saving detection results lists which failures keep partial work pending.

Asynchronous fetch#

ovclash_suite_runtime_fetch_and_save_async() runs initialization, sequential writes and cleanup on one background worker, so custom callbacks run there.

  • Only prepare_frame can also run on scheduler workers. Those workers cannot read the reserved owners.

  • Launch fails while the built-in destination has live cursors.

  • ovclash_suite_fetch_async_finish() and ovclash_suite_fetch_async_cancel() join the worker but keep the owners reserved. Only destruction releases them.

  • Polls may overlap one finish or cancel call. Serialize the control calls with each other.

  • Destruction must not overlap any other call on the handle. It must not come from the operation’s own callbacks.

  • A custom reader’s optional close callback runs on the worker before the terminal state is published. It also runs after cancellation and on destruction.

  • ovclash_suite_fetch_async_destroy_owned(&fetch) sets the caller’s pointer to null once destruction consumes the handle. A caller interrupted during return handling can then tell whether to retry.

Cancellation can race successful completion. It does not undo an already committed result.

Python fetch operations#

  • ClashDetection.run_async_fetch_and_save() returns AsyncFetchAndSave, a context manager.

  • ClashDetection.fetch_and_save_overlaps() returns a lazy generator. Argument checks, the native launch and the settings snapshot happen on its first iteration.

  • The generator holds its leases until it is exhausted or closed. That includes the time after the final 1.0 progress value, which reports the commit.

  • Close fetch operations and iterators explicitly, before their runtime and store. Garbage collection does not release them promptly.

  • A finalizer whose cleanup fails keeps the operation and its owners alive until AsyncFetchAndSave.close() or ClashDetection.destroy() recovers it. Without such a call, for example when no caller still holds the runtime, they stay alive for the process lifetime.

  • close() raises when cleanup fails. A close that was rejected or interrupted before native destruction keeps the operation for a retry. Once native destruction has consumed the handle, a later close() does not repeat it.

Use contextlib.closing when a loop can stop early:

from contextlib import closing

# clash, data and query already describe a completed detection run and an open store.
with closing(clash.fetch_and_save_overlaps(None, data, query, async_mode=True)) as progress:
    for fraction in progress:
        print(fraction)
        # An early break still closes the native operation on leaving this block.

Borrowed memory#

An overlap report is a view, not a copy.

A buffer view that outlives its report is a use-after-free.

ovclash_create_overlap_report() and ovclash_create_overlap_report_ex() fill a caller-provided ovclash_overlap_report_t, whose fields Overlap reports lists. Its four array pointers are borrowed; the caller never owns them: collidingFaces0, collidingFaces1, collidingSegments and collidingPoints0. They alias result storage that the context owns.

Call ovclash_release_overlap_report() for every successful create. On ovstage the release only clears the struct, but the header contract requires it on every backend, so code that skips it is not portable. Never hold a report across another pipeline step or run: a sampled step can replace result buffers within the same run. Release reports before:

  • the next pipeline step or run

  • ovclash_release_memory()

  • ovclash_reset_context()

  • ovclash_release_context()

ovclash_release_overlap_report() resets the struct to the ovclash_reset_overlap_report() state. A second release with a live context is therefore harmless. A zero-initialized or reset empty report is also safe to release. Otherwise, pass only a struct that a create call filled in and that has not been edited since. This function, for a C source file of your program, reads one report after a completed run of ctx:

#include <stdio.h>

#include <ovclash/ovclash.h>

/* Prints the colliding faces of the first mesh of overlap `index`. */
static void print_faces0(ovclash_context_t* ctx, uint32_t index)
{
    ovclash_overlap_report_t report;
    ovclash_reset_overlap_report(&report);
    if (ovclash_create_overlap_report_ex(ctx, &report, index, 0,
                                         OVCLASH_OVERLAP_REPORT_FLAG_FACES0, NULL, NULL).status
        == OVCLASH_STATUS_SUCCESS)
    {
        for (uint32_t i = 0; i < report.nbCollidingFaces0; ++i)
            printf("%u\n", report.collidingFaces0[i]); /* read or copy while the report is live */
        ovclash_release_overlap_report(ctx, &report);
    }
}

Borrowed names#

The path strings borrow too. ovclash_overlap_data_t::name0 and name1, and the same fields of ovclash_duplicate_mesh_data_t, point at backend-owned storage. Never free them.

  • The four calls that Borrowed memory lists invalidate them.

  • Every call that retires the selected-object table, the list of meshes and point clouds that the last selection chose, invalidates them as well, such as an ovclash_open_stage() call that gets past argument validation. The notes on ovclash_get_overlap_data() and ovclash_get_duplicated_meshes_data() in <ovclash/ovclash.h> list those calls.

Copy the bytes to keep a name. These two functions belong in a C source file of your program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <ovclash/ovclash.h>

/* Returns a null-terminated copy of a borrowed name; free it with free(). */
char* copy_name(ovclash_string_t name)
{
    char* copy = malloc(name.length + 1);
    if (copy)
    {
        if (name.length != 0)
            memcpy(copy, name.ptr, name.length);
        copy[name.length] = '\0';
    }
    return copy;
}

/* Prints the first prim path of overlap `index` from a copy of the borrowed name. */
static void print_name0(ovclash_context_t* ctx, uint32_t index)
{
    ovclash_overlap_data_t data;
    ovclash_reset_overlap_data(&data);
    if (ovclash_get_overlap_data(ctx, &data, index, 0).status == OVCLASH_STATUS_SUCCESS)
    {
        char* name0 = copy_name(data.name0); /* stays valid after the next run */
        if (name0)
            printf("%s\n", name0);
        free(name0);
    }
}

The DLPack path#

ovclash_overlap_report_get_dltensor() describes one report array as a DLPack tensor, without copying. ovclash_dltensor_view_t, in <ovclash/ovclash.h>, is a transparent struct. It holds a DLTensor plus inline shape and strides storage, so the view is stack-allocatable and there is nothing to free. The call writes every field:

Field

Type

Required

Default or values

Description

tensor

DLTensor

Yes

ndim 1, or 2 for the outline; device kDLCPU, 0; byte_offset 0; dtype as the buffer table gives, with lanes 1

The DLPack tensor. tensor.data aliases the report array, or is NULL for an empty one. tensor.shape and tensor.strides point into the two arrays of this struct.

shape

int64_t[2]

Yes

[n], or [n, 6] for the outline

The storage of tensor.shape.

strides

int64_t[2]

Yes

In elements, row-major: [1], or [6, 1] for the outline

The storage of tensor.strides.

This function, for a C source file of your program, reads a report that a create call filled with OVCLASH_OVERLAP_REPORT_FLAG_FACES0:

#include <ovclash/ovclash.h>

/* Returns the number of colliding faces of the first mesh, or -1 on failure. */
static int64_t faces0_count(const ovclash_overlap_report_t* report)
{
    ovclash_dltensor_view_t view;
    if (ovclash_overlap_report_get_dltensor(report, OVCLASH_REPORT_BUFFER_FACES0, &view).status !=
        OVCLASH_STATUS_SUCCESS)
        return -1;
    /* Pass &view.tensor to a consumer that does not keep it beyond the report. */
    return view.tensor.shape[0];
}

Buffer

Report array

Element type

Shape

OVCLASH_REPORT_BUFFER_FACES0

collidingFaces0

uint32

[n]

OVCLASH_REPORT_BUFFER_FACES1

collidingFaces1

uint32

[n]

OVCLASH_REPORT_BUFFER_OUTLINE

collidingSegments

float32

[n, 6], one row per segment

OVCLASH_REPORT_BUFFER_POINTS0

collidingPoints0

uint32

[n]

Four rules apply:

  • tensor.data aliases the matching pointer inside the report. The tensor is valid only while the report is. It dangles after ovclash_release_overlap_report().

  • It carries no deleter. Do not hand it to a consumer that expects to own a DLManagedTensor.

  • The device is always kDLCPU, device_id 0.

  • Copying the ovclash_dltensor_view_t struct invalidates tensor.shape and tensor.strides, which still point into the original. Fill a new view rather than memcpy a filled one.

An array that was not requested through the report flags has count 0. That is reported as success with a zero-length tensor and tensor.data == NULL, not as an error.

In the ovclash Python package, the same memory is exposed as BufferView. It is an explicit-lifetime view, valid only until its OverlapReport is released.

  • It implements the array-interchange protocol: __dlpack__, and __dlpack_device__, which returns (1, 0), that is kDLCPU. numpy.from_dlpack(view) and torch.from_dlpack(view) therefore consume report buffers without a copy. The export goes through NumPy, so NumPy must be installed.

  • .numpy() and .warp() are zero-copy too. They need NumPy and Warp respectively.

  • .tolist() copies, and needs neither.

  • Every BufferView accessor first checks that the owning report is still open. It raises RuntimeError("closed overlap report buffer view") if it is not. That guard covers use after close(). It cannot cover a DLPack capsule, NumPy array or Warp array that you already exported and kept past the report. Consume those before the report is released, or copy out of them.

import numpy as np

from ovclash import OverlapReportFlag

# runtime is an ovclash.ClashRuntime after a completed run.
with runtime.get_overlap_report(0, flags=OverlapReportFlag.FACES0) as report:
    faces = np.from_dlpack(report.faces0).copy()  # zero-copy view, then an owned copy
    view = report.faces0
print(faces.dtype, faces.shape)  # the copy outlives the report
len(view)  # raises RuntimeError: closed overlap report buffer view

Suite reports#

The Suite Python facade copies on purpose. ClashDetection.get_overlap_report2(), which get_overlap_report() also uses, copies each buffer into an ArrayView, a small container of ovclash_suite that holds the values in a tuple and converts them to a list, NumPy or Warp array. It releases the native report before it returns, so nothing it returns is borrowed.

The Suite C ABI borrows:

  • ovclash_suite_get_overlap_report_view() fills an ovclash_suite_overlap_report_view_t with pointers into the report’s arrays. Those arrays borrow the runtime’s result storage.

  • A Suite report does not keep its runtime alive, and the view does not extend the report’s lifetime. Destroying the report invalidates the view. Invalidating the runtime’s results can invalidate it earlier.

  • Keep the runtime alive until the report is destroyed. Destroy the report before the next pipeline step or run, a reset, any other call that invalidates the runtime’s results, or runtime destruction.

  • The strings of the clash-info view from ovclash_suite_create_clash_info() belong to the runtime instead. They stay valid until the next ovclash_suite_create_clash_info(), ovclash_suite_runtime_save_overlap_to_data() or fetch-and-save capture on that runtime, or until the runtime is destroyed.

ovclash_suite_overlap_report_view_t, in <ovclash_suite/ovclash_suite_types.h>, holds borrowed buffer pointers and copied counts, point size and transforms. The flags of ovclash_suite_create_overlap_report() select the buffers; faces and outlines exist for mesh-vs-mesh pairs only.

Field

Type

Required

Default or values

Description

nb_colliding_faces0, colliding_faces0

uint32_t, const uint32_t*

With OVCLASH_SUITE_OVERLAP_REPORT_FACES0

Face indices of the USD mesh; the pointer may be null only when the count is 0

The colliding faces of the first prim. Borrowed.

nb_colliding_faces1, colliding_faces1

uint32_t, const uint32_t*

With OVCLASH_SUITE_OVERLAP_REPORT_FACES1

Face indices of the USD mesh; the pointer may be null only when the count is 0

The colliding faces of the second prim. Borrowed.

nb_colliding_segments, colliding_segments_xyzxyz

uint32_t, const float*

With OVCLASH_SUITE_OVERLAP_REPORT_OUTLINE

nb_colliding_segments * 6 floats in xyzxyz order; the pointer may be null only when the count is 0

The intersection outline, one segment per six floats, from touching or interpenetrating triangle pairs only. The count is in segments, not floats. Borrowed.

nb_colliding_points0, colliding_points0

uint32_t, const uint32_t*

With OVCLASH_SUITE_OVERLAP_REPORT_POINTS0

Point indices of the USD point cloud; the pointer may be null only when the count is 0

The clashing points of a point-vs-mesh overlap. Borrowed.

point_size0

float

With OVCLASH_SUITE_OVERLAP_REPORT_POINTS0

A point width

The source point size that the point-cloud report used.

matrix0, matrix1

double[16]

Yes

A row-major 4x4 matrix

The local-to-world transforms of the two prims, copied into the view.

Error text lifetime#

There are four error channels, and their lifetimes differ.

Accessor

Scope

Valid until

ovclash_get_last_error(context)

Per context

The view is a thread-local copy, invalidated by the next ovclash_get_last_error() on the same thread

ovclash_suite_get_last_error(runtime) / ovclash_suite_data_get_last_error(data)

Per handle, with a thread-local fallback

Handle-owned text: the next call that records or clears that handle’s error, or the handle’s destruction. Fallback text: the next Suite API call on the same thread

ovclash_suite_get_thread_last_error()

Per thread

The next Suite API call on the same thread

ovclash_suite_fetch_async_get_last_error(async, &error)

Per async fetch operation

The destruction of that handle. Empty while the worker runs

The Suite handle getters return the thread-local fallback in three cases: for a null handle, for a handle with no recorded error, and while an active async fetch rejects access. Copy the text before another Suite call if it must outlive that call. The Python wrappers return copies.

ovclash_get_last_error() has these properties:

  • It is declared only when OVCLASH_STANDALONE is defined. The installed CMake package and ovclash.pc define it for every SDK archive consumer; The OVCLASH_STANDALONE macro describes it.

  • It is the only diagnostic channel of the canonical ABI, and it has no thread-local fallback. The context-free entry points never record anything there: ovclash_sdf_path_to_int, ovclash_get_backend_info, ovclash_get_result_string, ovclash_get_version, ovclash_get_version_string, ovclash_overlap_report_get_dltensor and the ovclash_reset_* helpers.

  • ovclash_get_timeline_data records only when it is rejected inside an owner-operation callback with a non-null context.

  • A null context yields an empty { NULL, 0 } view.

The text is sticky across most successful calls. Calls that clear it include ovclash_open_stage(), ovclash_get_prim_matrix(), ovclash_get_stage_timeline_data() and ovclash_set_scope_paths(). The start of a run (step 0, or the async worker starting) and the optional ovstage attach and detach calls clear it too. A message can therefore outlive the call that produced it. Read it immediately after a call returned OVCLASH_STATUS_ERROR. Never treat a non-empty string as “the last call failed”.

Both canonical and Suite accessors return spans, not owned C strings. ovclash_string_t (a typedef of the producer-owned ovx_string_t) and ovclash_suite_string_t are both { const char* ptr; size_t length; }; Strings gives the type and rule of each field. Treat the length as authoritative. Write non-empty spans with fwrite(ptr, 1, length, stream), and copy the bytes to keep them. An empty view may carry a null ptr. This function, for a C source file of your program, prints the last error of a context:

#include <stdio.h>

#include <ovclash/ovclash.h>

static void print_last_error(const ovclash_context_t* ctx)
{
    ovclash_string_t err = ovclash_get_last_error(ctx);
    if (err.length != 0) {
        fwrite(err.ptr, 1, err.length, stderr);
        fputc('\n', stderr);
    }
}

The async pipeline worker writes the same context error string while a run is active. A mid-run read is safe, but it returns a nondeterministic message. Read it after ovclash_finish_pipeline().

Releasing a context is not instant#

ovclash_release_context() never cancels an active async pipeline; it waits for it. If a handle is still outstanding, the call blocks until the pipeline completes and joins the worker thread. Release therefore never races a running pipeline, but it can block for the remaining pipeline time.

ovclash_suite_destroy_runtime() behaves the same way for a run started by ovclash_suite_run_pipeline_async(). It blocks until the run completes and discards its results. The async handle stays caller-owned. Release it with ovclash_suite_async_destroy() afterwards.

To shut down early on the canonical ABI, while an async handle from ovclash_run_pipeline_async() is live:

  1. Call ovclash_cancel_pipeline().

  2. Call ovclash_finish_pipeline() exactly once. After a cancel it returns OVCLASH_STATUS_ERROR, which reports the cancelled run, and the worker has stopped.

  3. Release your overlap reports.

  4. Release the context with ovclash_release_context().

On the Suite ABI, while an async handle from ovclash_suite_run_pipeline_async() is live:

  1. Call ovclash_suite_async_cancel(). It blocks until the worker stops, so no separate finish call follows.

  2. Destroy your overlap reports.

  3. Destroy the async handle with ovclash_suite_async_destroy().

  4. Destroy the runtime with ovclash_suite_destroy_runtime().

Cancellation is cooperative. Finish, cancel and release have no timeout and may still block. When the last call returns, no worker of the run is left.

Attached ovstage Stages#

An ovstage context can borrow a live, caller-owned ovstage Stage instead of opening a file: ovclash_ovstage_attach_stage() in C, ovclash_suite_attach_ovstage() on the Suite API, and attach_ovstage() in both Python packages. The attachment changes who owns what:

  • The Stage and the optional evaluate_time callback stay caller-owned. They must outlive the attachment and every operation that uses it.

  • The binding and its optional composition are copied. The caller may free the composition and its strings once the attach call returns.

  • Detaching, resetting the context, an open-stage call that passes argument validation, a replacement attachment and releasing the context end the attachment. None of them destroys the Stage. ovclash_release_memory() keeps the attachment.

  • The owner excludes rendering, source edits, time changes and destruction while clash operations use the Stage, and serializes external use of a Stage that several contexts share.

  • Owner work on the Stage, such as creation, population and destruction, runs through the process-wide owner-operation gate. A clash call from inside an owner operation is rejected.

  • An attachment with a composition evaluates finite times in private ovstage populations that the context owns. The context creates them under the gate at the first finite-time read, and destroys them when the attachment ends and at ovclash_release_memory(). An owner thread that holds the gate must therefore never wait for a clash call. The Stage’s committed_ordinal must stay retained until the attachment ends. Each replay reopens the composition’s root by its string, so the root file and every file that the root or a layer references must stay unchanged on disk until then, and a relative root resolves against the process working directory at each replay.

Using ovclash with an ovstage Stage gives the binding descriptor, the gate and reentry rules, the callback rules, engine-evaluated time and a complete example.

On the canonical ABI, an attachment does not restore full-scene traversal that a non-empty scope cleared; see Zero overlaps, or a scoped run traverses the whole stage.

Python-side lifetimes#

The ovclash package makes all three lifetimes explicit.

  • OverlapReport is a context manager. Leaving the with block calls close(), which calls ovclash_release_overlap_report(). The runtime keeps a reference to every open report, so dropping yours does not close one; __del__ is only a fallback. close() retires the report and its BufferViews even if the release raises. It does not retry the release.

  • AsyncPipeline is a context manager.

    • finish() waits for completion and raises if the run failed.

    • cancel() requests a stop, then finishes the run and blocks until the worker exits.

    • close() finishes a run that was never finished, without raising for its outcome.

    • The methods may be called from several threads, but cancel() cannot interrupt a finish() that already blocks on another thread. To cancel from a UI, poll and cancel on one thread, and call finish() there once the loop ends. See Asynchronous Pipelines.

  • ClashRuntime exposes destroy(), with close() as an alias. destroy() is idempotent. It closes an active async pipeline, closes every registered report, then calls ovclash_release_context(). Explicit destroy() is the primary lifetime contract; the runtime also supports with.

The AsyncPipeline and ClashRuntime context managers request cancellation when the with block raises. A normal exit and explicit cleanup wait for completion. Asynchronous Pipelines describes that exceptional cleanup.

This standalone script needs the ovclash package installed, as Python Quickstart shows. Replace scene.usda with the path of your stage file, and run the script with that Python:

from ovclash import ClashRuntime, OverlapReportFlag

runtime = ClashRuntime()
try:
    runtime.open_stage("scene.usda")
    runtime.run_pipeline()
    faces = {}
    for index in range(runtime.get_overlap_count()):
        with runtime.get_overlap_report(index, flags=OverlapReportFlag.FACES0) as report:
            faces[index] = report.faces0.tolist()  # copy before the block ends
finally:
    runtime.destroy()

report.faces0.numpy() avoids the copy, but needs NumPy and stays valid only inside the block. Call .copy() on it to keep the data.

The runtime keeps a registry of open reports. It closes them wherever the native buffers would be invalidated anyway. These methods close every open report first:

  • reset(), open_stage(), attach_ovstage() and detach_ovstage()

  • set_run_settings(), set_scope() and set_ovstage_dynamic_matrix_cache()

  • set_ovstage_matrix_decomposition(), when it changes the mode

  • create_pipeline(), run_pipeline_step() and run_async()

  • destroy()

A stale BufferView then raises a clean RuntimeError instead of crashing. A report you were still reading is gone after any of those calls.

Exceptions during construction and cleanup#

If an exception interrupts construction or async launch, the wrappers of both packages attempt native cleanup and re-raise the original exception. Launch cleanup can block for the remaining pipeline time.

If an exception interrupts cleanup itself, the wrapper retires the handle instead of retrying, because native code may already have freed it. This has consequences:

  • An exception does not prove that native cleanup completed.

  • A handle retired after an interrupted call can leave native resources allocated.

  • An explicit failure status from a native destroy keeps the handle, so destroy() can be retried.

  • A failure while closing a dependent pipeline or report leaves the parent alive.

The Suite package#

In ovclash_suite:

  • ClashDetection.destroy() (alias close()) closes an active async pipeline, which waits for the run. Then it destroys the native runtime.

  • ClashData.destroy() closes the store. A built-in store attempts to commit pending writes first. Then it drops its serializer reference. It destroys the native handle only for the default serializer that it created itself.

  • A live fetch iterator, AsyncFetchAndSave or saved-frame iterator from fetch_iter_saved_frames() rejects the matching runtime or store lifecycle changes. Close it first.

  • ClashDetection is not a context manager. Its AsyncPipeline and AsyncFetchAndSave operations are:

    • The Suite AsyncPipeline cancels and drains when its block raises, and waits on a normal exit.

    • AsyncFetchAndSave cancels and drains unfinished persistence on every exit.

    • Both keep an exception raised in the block as the primary error.

Ownership rules for the Suite models#

The Suite model API (<ovclash_suite/ovclash_suite_models.h> in the SDK archive) covers the ClashQuery, ClashInfo, ClashFrameInfo and PointCloudSettings objects. The caller owns every handle returned through an out parameter, and destroys it with the matching destroy function. The two directions are deliberately asymmetric:

Direction

Function shape

Semantics

In

ovclash_suite_<model>_create_from_view(view, &handle)

Copies. The created handle copies the string and array views inside view. The caller may free its own buffers as soon as the call returns.

Out

ovclash_suite_<model>_get_view(handle, &view)

Borrows. The handle backs the returned view, which is valid only until that handle is mutated or destroyed. A frame view that ovclash_suite_clash_info_get_frame_info() synthesizes lasts only until the next frame read on that handle.

The same split applies across the Suite:

  • Inputs are copied during the call, including views passed to insert, update and replace functions.

  • Getters return borrowed views.

  • The non-cursor data-handle getters (query, overlap, frame and point-cloud-settings views) reuse per-kind scratch storage. The next getter of the same kind therefore invalidates the previous view, even without a store mutation. Copy the view before another such read, any data-handle mutation, close or destroy.

  • A cursor view lasts until that cursor’s next advance or destruction.

  • An input span’s ptr may be null only when its length (or a counted array’s count) is zero.

The serializer buffer rule#

A Suite function that writes text, such as a model serializer (..._serialize_json and the others), ovclash_suite_run_settings_to_query_settings_json() or an export into a caller buffer, takes an explicit buffer size in bytes. It reports the required UTF-8 byte count through out_required_size:

  • out_buffer == NULL with out_buffer_size == 0 is the size query. It writes the required byte count to out_required_size. The count excludes the trailing null.

  • A non-null buffer too small for those bytes plus the null returns OVCLASH_SUITE_STATUS_ERROR. It still writes out_required_size, and it never returns a truncated text. A model serializer also leaves the buffer unchanged.

So size, allocate one more byte, then fill. This function, for a C source file of your program, serializes a ClashQuery model handle:

#include <stdlib.h>

#include <ovclash_suite/ovclash_suite.h>

/* Returns the JSON text of query as a null-terminated string to free() with, or NULL. */
static char* query_json(const ovclash_suite_query_t* query)
{
    size_t required = 0;
    ovclash_suite_result_t result = ovclash_suite_query_serialize_json(query, NULL, 0, &required);
    if (result.status != OVCLASH_SUITE_STATUS_SUCCESS)
        return NULL;
    char* buffer = malloc(required + 1);
    if (buffer)
    {
        result = ovclash_suite_query_serialize_json(query, buffer, required + 1, &required);
        if (result.status != OVCLASH_SUITE_STATUS_SUCCESS)
        {
            free(buffer);
            buffer = NULL;
        }
    }
    return buffer; /* on success, required bytes plus a trailing null */
}

Failure detail is in ovclash_suite_get_thread_last_error(), valid until the next Suite API call on that thread.

The model serializers also follow these numeric rules:

  • They reject NaN and infinity in both forms, without writing partial JSON, and leave both outputs unchanged.

  • They write finite numbers with round-trip precision, and negative zero as -0.0.

  • They use the classic numeric locale and the default floating-point environment, whatever the caller’s settings, and restore the caller’s environment afterwards.

  • Serialization never mutates the model.

Threading controls and result order#

ovclash_set_single_threaded(), ovclash_set_new_task_manager() and ovclash_set_nb_tasks() select the scheduler and the worker budget. Settings gives their defaults and effects, and Performance says when to change them.

Four threading facts matter to callers:

  • Internal parallelism never relaxes the caller’s rules. Application calls on one context must still be serialized.

  • Background work can hold the ovstage owner-operation gate. Some phases of a run populate the stage on a helper thread under that process-wide gate, so stage loading and owner operations on other threads can wait for it. Direct queries such as ovclash_get_prim_matrix() wait for running background reads before they read the source.

  • Async runs snapshot floating-point controls. An async launch snapshots the calling thread’s rounding, denormal and exception-mask controls. The background run and its workers use that snapshot, even if the caller changes its controls while waiting. Launch and finish preserve the caller’s own controls.

  • Suite fetch-and-save serializes its writes. Serializer writes and report acquisition run in order on the thread that drives the fetch. Report release and built-in SQLite frame encoding stay on that thread. Directory frame preparation, face and outline report preparation and the custom-serializer prepare_frame callback can run on worker threads. Every started worker drains before its prepared buffers are published, or released after a failure or cancellation.

None of the three controls changes which pairs overlap or what is reported about them. Every part of the result that Overlap index order is not contractual lists stays identical across every combination, and a difference is a defect. On ovstage the controls do not change the order in which ovclash_get_overlap_data() returns groups either, but that order is still not part of the contract; key overlaps as Key overlaps by prim pair shows.