Suite Runtime and Fetch#
This page of the Technical Guide explains how the
Suite runtime wrapper and the
fetch-and-save engine work inside. Read it before you change
source/suite/SuiteRuntime.cpp, source/suite/SuiteFetch.cpp, a store’s bulk writer or the
Python serializer bridge. Concepts defines the consumer
vocabulary, such as overlap,
frame and custom store; the
Architecture glossary defines the implementation terms.
On this page a custom store is a destination that the caller implements, and its serializer is
the callback interface that implements it: the C table ovclash_suite_fetch_serializer_t or a
Python AbstractClashDataSerializer.
The caller contracts live on other pages. This page links to them and does not repeat them:
Topic |
Canonical page |
|---|---|
What the Suite ABI adds, report flags, single-overlap save |
|
Runtime and store leases, synchronous and asynchronous fetch rules |
|
Which failure keeps or rolls back pending writes |
Saving detection results; the C call sequence is in Fetch failures and pending writes |
Per-step work limits, async progress and cancellation |
|
Clash-state reconciliation |
|
The saved-data reader of a custom C store |
|
Custom stores and their transaction contract |
|
Threading settings that select preparation workers |
|
Bulk-writer interface of the stores |
Source map#
Path |
Role |
|---|---|
|
The Suite runtime wrapper and the report capture that fetch uses |
|
The fetch engine ( |
|
The private report bridge: |
|
The ovstage preparation plan for frozen reports |
|
Batching and slot compaction for OpenUSD report extraction |
|
The worker launcher used for preparation and extraction |
|
|
|
The directory fetch writer and its |
|
The |
|
|
|
|
|
|
Suite runtime wrapper#
SuiteRuntime.cpp bridges the Suite ABI to the canonical ABI, which
the ovstage and OpenUSD backends
implement:
It converts Suite settings to
ovclash_settings_t.It calls the canonical
ovclash_*functions on the runtime’sovclash_context_t.It converts runtime records to Suite views and model records.
Report flags. Fetch capture requests OVCLASH_SUITE_OVERLAP_REPORT_POINTS0 for a
point-vs-mesh pair and FACES0 | FACES1 | OUTLINE for every other pair. The code tests the
pair type with == against the point-cloud value, so an undefined type gets the mesh flags. Both
backends ignore flags that do not apply to the pair type.
Report ownership. The two backends hand reports to the Suite differently:
OpenUSD: the
ovclash_suite_overlap_report_ttakes ownership of the buffers that the engine allocated increateOverlapReportEx(). Their capacity can exceed the public view, so fetch never holds two OpenUSD reports at once.ovstage: fetch freezes the report first (see Full-detail report capture). The public report path borrows the context’s buffers and does not extend their lifetime; see Borrowed memory.
Unavailable reports. runOverlapReportExtraction() returns one of three results:
|
Cause |
What fetch does |
|---|---|---|
|
The report was built. |
Captures the frame. |
|
The engine returned no report. Only OpenUSD does this, for a pair whose prim stopped resolving. |
The Suite returns |
|
Cancellation, native out-of-memory, an invalid record or another failure. |
Fetch fails. |
runOverlapReportExtraction() checks cancellation and the native out-of-memory state before and
after extraction. The engine can report success after a geometry allocation failed and leave that
channel empty. The second check turns such an incomplete report into Error.
When fetch skips frames, it prints one line to stderr, and the stored num_records counts only the
saved frames:
Overlap 3: persisted 239 of 241 records; missing reports were skipped.
If every record of an overlap is unavailable, the fetch fails with “Runtime overlap did not produce
clash info; all records failed to report”. Python process_overlap() makes the same distinction
between an unavailable report and an error.
The fetch engine#
Three operations share one engine in SuiteFetch.cpp:
Operation |
Driven by |
Notes |
|---|---|---|
|
The caller: |
The bounded synchronous form. |
|
One |
Runs |
|
|
Saves one overlap. No approval comparison and no reconciliation. Commits only when asked. |
Begin#
begin does the unbounded setup work:
It validates the arguments:
Exactly one of
dataandserializeris non-null.toleranceanddepth_epsilonare finite, and no async detection or other fetch is live.A custom table sets every storage and transaction callback.
prepare_frameandrelease_frameare both set or both null.A saved-data reader comes with the
serializertable of a custom store and sets both read callbacks.
It takes the runtime and destination leases.
It creates the bulk writer:
createBulkWriter()for a built-in store, or aSuiteCallbackBulkWriteraround a custom table.It snapshots the runtime’s threading settings with
suitePreparationSettings(). Before the first successfulovclash_suite_set_run_settings, these are the context’s own engine defaults, which detection also used, not the zero struct thatovclash_suite_get_run_settingsreturns.It counts the overlaps and, when
include_duplicatesis set, the duplicates.It calls
visit_existingonce and stores every existing identifier of the query.
include_duplicates is independent of the runtime’s only_find_duplicates setting. Python passes
the query’s SETTING_DUP_MESHES.
One next call#
A next call visits result groups in order: normal overlaps first, then duplicates. It captures
frames into a batch and flushes the batch when it is full. These are the serializer callbacks for
the groups of one batch, in order:
find_overlap(query, hash) approval check; only with resolve_stale and a saved-data reader
read_overlap, read_frame approval comparison of an APPROVED clash (custom reader only;
built-in stores read directly)
prepare_frame optional; on preparation workers, once per captured frame
transaction(BEGIN) idempotent; opens the destination's pending transaction
transaction(BEGIN_OVERLAP) only for a history that is still being captured
find_overlap before a group's first write, unless the approval check looked it up
write_overlap, clear_frames once per group, before its first frame
append_frame every captured frame, in result order
find_overlap, write_overlap the final header of a streamed history
transaction(END_OVERLAP) releases the streamed history's savepoint
release_frame every prepared frame, on the driving thread
Reconciliation starts in the call that writes the last group and continues on later calls:
transaction(BEGIN)
mark_absent(id, resolve_stale) stored IDs the fetch did not write; 1,024 IDs scanned per call
transaction(COMMIT) after the last ID, unless cancellation was requested
BEGIN runs before COMMIT even for an empty result. A successful completion therefore also
commits writes that were pending on the destination before begin.
Fetch batch sizing#
These constants in source/suite/SuiteFetch.cpp bound each next call:
Constant |
Value |
What it bounds |
|---|---|---|
|
1,024 |
Result groups visited per call |
|
1,024 |
Runtime frame reports attempted per call, across approval comparison and capture; also the retained batch size |
|
8 MiB |
Report geometry payload per call and per retained batch |
|
1,024 |
Stored identifiers scanned per reconciliation call |
|
64 |
Frames frozen and prepared together for one approval comparison (ovstage only) |
How the limits apply:
A missing report counts toward the frame limit. Each duplicate counts as one frame.
The call stops after the report that reaches or crosses 8 MiB. That last report is indivisible and may overshoot.
An oversized report sits alone in its retained batch, not necessarily alone in the call.
OpenUSD measures a report’s payload as its face, point and outline element counts times 4 bytes. ovstage uses the bound that
freezeOverlapReport()computes, which includes both matrices.The limits bound work units, not elapsed time or process memory. Prepared data, metadata and internal report capacity are outside the payload count.
beginenumerates every existing identifier and is outside these bounds.
The 1,024-group limit matters for many single-frame overlaps. Fewer next calls mean fewer
preparation dispatches. That helps the std-thread path most, because it starts new threads for each
dispatch, while Carbonite reuses its pool. Larger limits trade progress
and cancellation granularity for less scheduling overhead. They do not change cancellation or
transaction semantics.
More workers are not automatically faster. For small reports, serial or Carbonite preparation
often beats many std threads, and SQLite insertion always has one writer. Measure preparation and
insertion separately on the target system before you change a limit or the
scheduler policy.
python -m benchmarks.fetch_batch (benchmarks/fetch_batch/) compares native builds on the
same completed detection results; benchmarks/fetch_batch/README.md lists its options.
HTML export does not use fetch batching; see
HTML export.
Streamed histories#
A group whose capture finishes before its first frame is written needs one header write and no savepoint. Otherwise its history streams:
On OpenUSD every multi-frame history streams, because fetch flushes the batch before it acquires each report.
On ovstage a history streams when it does not fit in the current batch or call.
A streamed history is written in these steps:
BEGIN_OVERLAPopens a savepoint.A first header write returns the stable identifier.
Each batch appends its frames under that identifier.
The final step looks the header up again, refreshes the editable fields, and writes the final aggregate header.
END_OVERLAPreleases the savepoint.
The refresh keeps annotations that a custom store assigns on insertion. The final step also runs when missing trailing reports leave the last batch empty. A serializer failure during the final lookup or header write requests a full rollback.
Preserved fields. When a stored clash record exists,
preserveEditableOverlapFields() keeps 12 fields: the identifier, priority, person in charge,
creation timestamp, comment, state and the six penetration-depth annotations. The fetch moves the
strings out of the looked-up record instead of copying them. Fresh runtime results supply every
other header field. The state is then updated as
Clash-state reconciliation on refetch describes.
The first frame of a group builds the group metadata, its paths and hash strings, through
ovclash_suite_create_clash_info() or the deferred ovstage variant
suiteCreateClashInfoDeferred(). Later frames use suiteCaptureRuntimeFrame() or
suiteCaptureRuntimeFrameDeferred(), which skip that work. The user name is read once per
operation, not per frame.
Progress and counts#
ovclash_suite_runtime_fetch_and_save_get_counts() reads written and total without doing any
work. written counts only fully written groups, so written == total can come before
reconciliation and commit.
The fractional progress of next is done / (total + 1), capped below 1.0 until commit:
doneadds the finished groups, the fraction of the active group’s frames, and the fraction of identifiers reconciled.While an
APPROVEDgroup is being compared, comparison counts for the first half of that group and capture for the second half.The
+ 1reserves room for reconciliation. Only a successful commit returns exactly 1.0.
The async operation publishes these values under a mutex after each step.
ovclash_suite_fetch_async_get_step_data() reports one of these step names:
|
Name |
|---|---|
0 |
|
1 |
|
2 |
|
any, while a cancel request is running |
|
This example fetches one run three times into a SQLite store. Run it from the ovclash/ directory
of a source checkout, with PYTHONPATH and OVCLASH_LIB set as
Running the module from a source checkout
shows:
"""Fetch one run three times and show counts, progress and state reconciliation."""
import tempfile
from contextlib import closing
from pathlib import Path
from ovclash_suite import ClashData, ClashDetection, ClashQuery, ClashState, SettingId
def save(clash, data, query):
"""Run one fetch-and-save and print its (written, total) counts and progress values."""
counts = []
fetch = clash.fetch_and_save_overlaps(None, data, query, progress_callback=lambda w, t: counts.append((w, t)))
with closing(fetch) as steps:
progress = list(steps)
states = [info.state.name for info in data.find_all_overlaps_by_query_id(query.identifier, False).values()]
print(f"counts={counts} progress={progress} states={states}")
query = ClashQuery(
query_name="Cube vs Plane",
object_a_path="/Root/Xform_Primitives/Cube",
object_b_path="/Root/Xform_Primitives/Plane",
clash_detect_settings={SettingId.SETTING_TOLERANCE.name: 0.0},
)
clash = ClashDetection()
data = ClashData()
try:
data.open(str(Path(tempfile.mkdtemp()) / "refetch.ovclashdb"))
data.insert_query(query)
clash.open_stage("tests/data/time_sampled.usda")
clash.set_settings(query.clash_detect_settings)
clash.set_scope_paths([query.object_a_path], [query.object_b_path])
clash.run_pipeline()
save(clash, data, query) # first detection: NEW
save(clash, data, query) # re-detected: ACTIVE
for info in data.find_all_overlaps_by_query_id(query.identifier, False).values():
info.state = ClashState.APPROVED
data.update_overlap(info, update_also_frame_info=False)
save(clash, data, query) # unchanged contents: stays APPROVED
finally:
data.destroy()
clash.destroy()
Output, the same on both backends:
counts=[(0, 1), (1, 1)] progress=[1.0] states=['NEW']
counts=[(0, 1), (1, 1)] progress=[1.0] states=['ACTIVE']
counts=[(0, 1), (1, 1)] progress=[1.0] states=['APPROVED']
In the default synchronous mode the progress callback runs once after begin and once after each
next call. Here one next call writes the only group, reconciles and commits.
Failure handling#
The public outcome of each failure is in Saving detection results. The engine implements it with two helpers:
Helper |
Called for |
What it does |
|---|---|---|
|
A serializer callback failure after |
Requests |
|
Every |
Requests |
Further rules:
nextmarks the operation failed before it starts work and clears the mark only on success. A failed operation cannot resume, even when an exception escaped.A
drivingflag rejectsnext,get_countsanddestroyfrom inside a running callback. The async operation rejectsfinish,cancelanddestroyfrom its own callbacks the same way.destroycloses the saved-data reader and aborts an open streamed history. It never commits. If closing the reader fails, it retries the close once, still aborts the history, and keeps the first error.Preparation workers cannot update the serializer’s error state. A failed preparation therefore reports “Serializer failed to prepare a frame” instead of asking
last_error, which could return an unrelated earlier storage error.Cleanup keeps the primary diagnostic.
PreserveSuiteLastErrorsaves the thread’s error text, andFetchDiagnosticSuppressionstops cleanup from querying the same serializer’slast_error.The serializer of a custom store must implement the transaction callbacks. The engine cannot repair a failed custom rollback.
Allocation failure does not hide errors or leak reports:
The C ABI guards borrow their operation names, so cleanup does not allocate.
A captured report is owned before hashes are formatted or paths are copied. An allocation failure then releases the native report.
SQLite savepoint and full rollback keep existing errors by swapping ownership (
PreserveRollbackErrors), so copying an error cannot block a rollback. SQLite error-message buffers are owned before diagnostic formatting can throw.
Clash-state reconciliation on refetch#
Clash states owns the rules. In short: with
resolve_stale nonzero, the clash record of a re-detected overlap becomes ACTIVE, an APPROVED
clash record with exactly unchanged detected contents stays APPROVED, and a clash record whose
overlap is absent becomes RESOLVED. The clash record of a new overlap starts NEW.
The comparison runs only with resolve_stale and a saved-data reader. Built-in stores and the
Python bridge always supply one. A plain C custom store without a reader cannot prove
unchanged contents, so the clash records of its re-detected overlaps become ACTIVE.
How one stored APPROVED group is compared:
prepareApprovalComparison()looks the hash up withfind_overlap. Only anAPPROVEDmatch continues.It reads the saved header and drops its review strings at once. Replacement takes the annotations from the separately owned initial lookup instead. A different query, hash, frame count or record count ends the comparison as changed.
The first runtime report’s header metadata is compared. A difference ends the comparison without reading any saved frame.
Frames are compared in order:
OpenUSD captures one report at a time and compares it.
ovstage freezes and prepares chunks of up to 64 frames, then compares them in order. When one chunk covers the whole history, capture reuses those prepared reports. A longer history is prepared again during capture: a bounded second preparation instead of retained memory.
A single-frame group in a built-in store skips the comparison pass.
flush()compares it after the batch has prepared the frame and before the batch is written.A custom saved-data reader always uses the comparison pass. Its calls for one overlap, from
read_overlaptoclose, never interleave with another overlap’s calls.
The aggregate header must also match.
Comparison and capture share the per-call frame and payload limits, so a long approved history yields between calls. A cancelled ovstage chunk is drained, discarded unprepared and never counts as a change.
Exact equality. equalDetectedValue() compares bit patterns instead of running floating-point
comparisons:
A NaN never matches. Positive and negative zero match.
Subnormals stay distinct from zero, even when the driving thread flushes denormals.
Arrays of 256 or more values compare with
std::equalinsideScopedSerializationFloatingPointEnvironment, which installs the default floating-point environment.Minimum distance and maximum local depth aggregate through
lessDetectedDouble()with the same bit rules.
Values compare at Suite ABI precision: binary64 for scalar metrics, times and matrices, binary32 for outlines and point sizes. Python keeps that precision in both directions:
python/ovclash/python/suite/_numeric.pycopies binary32 buffers from their source words while the borrowed buffer is valid. It repairs subnormals that ctypes promotion can flush. Long arrays locate candidates with byte-plane masks, so only actual subnormal words reach Python code.The saved-data reader converts stored values with
preserve_numeric=True.The Python
process_overlap()path compares its own snapshots with the same rules. It reads typed buffers, including the Gf typesGf.Matrix4fandGf.Matrix4d, directly.
Reading saved frames. Both reader callbacks use the identifier from the initial lookup, not the row identifier in the returned header:
Destination |
How saved frames are read |
|---|---|
SQLite, one frame |
|
SQLite, several frames |
One forward cursor per history, kept across |
Directory |
The store’s forward frame cursor |
Custom C or C++ |
|
Python custom store |
|
The default fetch_iter_saved_frames() issues one ranged CRUD read per frame. A SQL store turns
that into a quadratic scan over a long history, so SQL-backed stores should override it with a
forward cursor. The bridge holds one iterator and one frame. It closes the iterator before every
write, transaction and abandonment, and reopens at the next offset after an intervening write.
Existing identifiers. ExistingOverlapIdentifiers holds the identifiers from begin as a
sorted, deduplicated int64_t vector with one presence byte per identifier:
Lookups use binary search. Reconciliation scans in ascending order without building a second list.
No identifier value is reserved as a sentinel.
Repeated visits are idempotent. Identifiers created during the fetch need not be in the snapshot.
Do not replace the vector with a node-based hash set, which allocates once per identifier.
Legacy duplicate rows. A legacy store can hold several rows with the same query and
clash hash. The SQLite lookup then selects the highest row
identifier (ORDER BY id DESC LIMIT 1). That is the row the Python dictionary reader exposes,
because it reads in ascending order and later rows replace earlier ones. The other rows are
reconciled as absent and keep their history. Cursors still order ascending, and no unique-index migration is needed.
Threading#
Work |
Thread |
|---|---|
Runtime access, report capture and report release |
Driving thread |
SQLite encoding, statements and writes |
Driving thread |
Every storage, transaction and reader callback, and |
Driving thread |
Directory and custom-C |
Preparation workers |
ovstage face and outline preparation of frozen reports |
Preparation workers |
OpenUSD report extraction inside the engine |
Extraction workers |
The driving thread is the caller for the synchronous form and the operation’s worker for the async form. Every dispatch drains its workers before it returns or rethrows. Prepared values are released before their borrowed report buffers, and SQLite bindings are reset and cleared before those buffers can disappear.
Worker count. parallelWorkerCount() in source/ParallelFor.h selects the workers from the
snapshot settings:
single_threaded, or fewer than two items: no workers; the caller runs the loop.new_task_manager: Carbonite’s worker budget and reusable pool.otherwise:
std::threadworkers, at mostmin(max(nb_tasks, 1), hardware concurrency, items), withnb_taskscapped at 256 for fetch preparation.
The SQLite writer’s batch reports serial() as true, so SQLite preparation never dispatches
workers. Encoding two matrices and borrowing geometry does not pay for a dispatch. The Python
bridge registers no prepare_frame, so Python custom stores always prepare on the driving
thread.
The std-thread launcher. parallelFor() hands out indices from one shared counter, and the
caller takes part as a worker. It stops creating threads once every index is claimed, or once
cancellation or a failure is seen, and it joins every thread it started. Each worker inherits the
caller’s rounding and denormal modes. The first exception is rethrown on the caller after all
workers have joined.
OpenUSD extraction. forEachReportBatch() runs a report with fewer than 1,024 source pairs
serially. With std threads it starts at most one worker per 4,096 source pairs, because thread
start-up otherwise dominates small extractions. Workers fill predetermined slots with a validity
byte each. compactReportSlots() compacts them in source order after the workers join.
The async worker. The operation’s std::thread runs initialization, every step and writer
destruction, so SQLite transactions and ordered callbacks stay on one writer:
The worker inherits the floating-point control state of the launching thread.
Callers see only atomic reservation flags (
asyncFetchActive). A worker-only thread-local permit authorizes the worker’s own reads of the leased runtime and store.The terminal diagnostic is stored in a
SuiteSavedError, which falls back to a static message when copying fails.finishrepublishes it on the caller’s thread.The Python bridge uses
ovclash_suite_fetch_async_destroy_owned(), which nulls the caller’s pointer once the handle is consumed. Python can then tell an interruption before native destruction from one after it.Python keeps progress, modification and timing notifications on the polling thread. It rethrows a custom callback’s exception only after the worker has joined.
Concurrent stores. Independent data handles may open at the same time. The process-wide SQLite
API table is published through std::call_once after every required symbol has loaded.
Fetch containers. Each structure is chosen for its ownership and access pattern:
Structure |
Reason for its representation |
|---|---|
Contiguous captured-frame batch |
Pre-reserved capacity bounds growth; each worker writes only its own preparation slot. |
Individually owned overlap groups |
Addresses stay stable when the pointer vector grows, and a call allocates only the groups it captures. |
Prepared frame |
SQLite reuses fixed matrix-encoding slots on the driving thread. Directory workers own independent JSON text buffers. Reports stay live until ordered insertion and prepared-frame release finish. |
Outline slots plus validity bytes |
Disjoint output slots need no append lock; byte flags avoid packed-bit writes racing within one word. Ordered compaction runs after the join. |
Cached SQLite statements |
One driving thread owns statement reuse and borrowed bindings, so workers need no connection lock. |
Keep overlap groups individually owned. A contiguous, pre-reserved group vector slows large borrowed-report batches and reserves capacity for groups that a payload-limited call never captures. Destroy the captured-frame batch before the owned groups.
Serializers#
Callback acknowledgements#
ovclash_suite_serializer.h declares both
callback tables, ovclash_suite_fetch_serializer_t and ovclash_suite_fetch_saved_data_reader_t,
and documents every member: whether it is required, its thread and its contract.
C quickstart: Custom serializers shows how a
caller fills them. The Python hooks of a custom store, the fetch_* methods of
AbstractClashDataSerializer, are documented in the
Python API reference.
Every callback in ovclash_suite_fetch_serializer_t and ovclash_suite_fetch_saved_data_reader_t
returns void and receives an out_success that the engine sets to 0. The engine accepts only the
value 1. That rejects a missing write, any other value, and a Python exception raised before the
bridge’s try block. The check cannot undo side effects that a failing callback already
published.
This callback for a SQLite-backed custom store writes 1 only after every step succeeded. It
belongs in the C source file of that store, which links SQLite; set it as the clear_frames
member of the store’s ovclash_suite_fetch_serializer_t, whose user_data here is the store’s
sqlite3* connection:
#include <ovclash_suite/ovclash_suite_serializer.h>
#include <sqlite3.h>
static void clear_frames(void* user_data, int64_t identifier, uint32_t* out_success)
{
sqlite3* db = (sqlite3*)user_data;
sqlite3_stmt* statement = NULL;
if (sqlite3_prepare_v2(db, "DELETE FROM frames WHERE overlap_id = ?;", -1, &statement, NULL) == SQLITE_OK &&
sqlite3_bind_int64(statement, 1, identifier) == SQLITE_OK && sqlite3_step(statement) == SQLITE_DONE)
{
*out_success = 1u;
}
sqlite3_finalize(statement);
}
The serializer has header lookup and write, frame clear and append, existing-identifier
enumeration, absent marking, and the transaction and savepoint operations. The optional
prepare_frame and release_frame hooks let a native serializer encode frames on workers. A
preparation hook must not touch a connection or shared mutable state. It may return an allocated
output even on failure; the engine releases it after all workers join. Release order is
unspecified.
SQLite bulk writer#
SuiteSqliteBulkWriter is the built-in SQLite fetch writer. The fetch driver itself issues no SQL.
The writer reuses the SQL and the binding code of the ordinary data writes on the same connection.
Operation |
SQL or behavior |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Rules for the writer:
Statements are prepared once and cached for the whole operation. The fetch lease outlives them, so they are finalized before the store can be reopened or closed.
The writer validates and binds the borrowed overlap view directly. UTF-8, null-pointer and SQLite length checks still run at the callback boundary, and bindings clear before return.
Header identifier
-1means “insert”. An imported row whose key is-1is updated instead, but only when the preceding lookup found that exact query and clash hash.Frames are prepared into reusable
SuitePreparedFrameslots, reserved on the driving thread. Slots do not grow or get reused until preparation and the ordered writes finish.Always run the prepared
DELETE FROM clash_frame_infostatement, even for a header that is known to be fresh. DELETE triggers and stale cached statements report their errors when that statement is prepared.
Store lifecycle entry points reject live fetches and cursors before they touch the connection. The
close helper commits first and keeps the handle on commit or close failure. It then finalizes the
store’s statements and closes with checked sqlite3_close_v2, which completes when any remaining
internal statement is finalized.
The SQLite CRUD mutations (frame insertion, history replacement, overlap insertion, explicit-ID replacement and update) roll back before an exception propagates. A later commit or close therefore cannot publish a partial history or a failed header. Each mutation also clears an unrelated earlier handle error first, so that error cannot mask the new diagnostic.
Directory writer#
The directory writer supplies prepare_frame and release_frame:
Each worker formats one borrowed frame view directly into owned JSON text (
prepareDirectoryFrame()). It copies no geometry and builds no numeric JSON tree.The text is two segments around the frame’s identifier. The driving thread assigns the persistent identifier and writes the segments without joining them into another full-frame buffer. The result matches the ordinary record writer byte for byte.
Preparation never touches directory state, the filesystem or diagnostics.
Python serializer bridge#
_NativeFetchSerializerAdapter exposes a Python AbstractClashDataSerializer as a C callback
table and a saved-data reader. Native code still makes every scheduling, comparison and
reconciliation decision.
Entry points. The synchronous path calls
ovclash_suite_runtime_fetch_and_save_begin_with_reader()andnexton the calling thread.async_mode=Truelaunchesovclash_suite_runtime_fetch_and_save_async_with_reader()whenresolve_staleis set, andovclash_suite_runtime_fetch_and_save_async()otherwise.Transaction check. Fetching raises
NotImplementedErrorbefore any work whenfetch_transactionis still the base method. The check inspects the bound attribute, so a CRUD store can attach a working method or callable to an instance.Callback guard. Each callback sets the acknowledgement only after the Python method returns. The first exception is kept. An exception from a
ROLLBACK,ABORT_OVERLAP, readercloseorlast_errorcallback is a cleanup failure and does not replace the primary error.Identifiers. Every returned or visited identifier must implement the integer index protocol, fit signed int64 and differ from the unsaved sentinel
-1. Other negative values, includingINT64_MIN, stay valid. The C contract reserves no identifier.Header cache. When both
fetch_find_overlapandfetch_write_overlapare the base methods, the adapter loads one header snapshot per operation and looks hashes up in a dictionary. M existing headers and N results then cost O(M + N). A written key keeps its identifier in a small slotted marker. A later lookup of that key reads one header throughfind_all_overlaps_by_overlap_id(), so store normalization stays visible. A mismatched identifier, query or hash reloads the snapshot. The cache is cleared when the operation stops.Overrides keep live behavior. An overridden lookup or write hook disables the cache. An overridden
fetch_visit_existingstill controls reconciliation. Indexed overrides avoid loading the full query when a store holds many unrelated results.CRUD errors must raise. The default hooks cannot treat a return value such as 0 as failure, because 0 can be a valid identifier or a deleted-frame count.
Cleanup scope. Python fetch entry points create the native operation inside their cleanup scope. An interruption that arrives as
beginreturns still destroys the handle, and a cleanup error does not replace the interruption.
The omni.physxclashdetectioncore compatibility modules re-export these same Suite classes.
Numeric text and identifiers#
Native numeric text does not depend on the caller’s locale or floating-point environment:
Frame preparation rejects NaN and infinite matrix entries before insertion, because the reader accepts only finite values.
matrixToJsonBuffer()writes each matrix withstd::to_charsat 17 significant digits into a fixed buffer, with no allocation.matrixFromText()parses with_strtod_lon Windows orstrtod_lon Linux and an immutable C numeric locale. It never changes a process or thread locale.Each conversion runs inside
ScopedSerializationFloatingPointEnvironment. It installs the default floating-point environment and restores the caller’s complete environment, including exception flags, on every exit. Directed rounding, flush-to-zero and denormals-are-zero cannot change persisted or decoded values.Model JSON and run-settings JSON share that protection. Negative zero is written as
-0.0, because the integer token-0decodes as positive zero in Python. On Windows the formatter uses the classic-locale CRT conversion that MSVC streams use, which keeps the last digit identical to the MSVC Debug runtime. Elsewhere it usesstd::to_chars.Model JSON uses direct string appends under one floating-point guard per model record; a clash record and all of its frames share one guard. Integers use locale-independent
std::to_chars; matrices use bounded buffers, and numeric array text needs no JSON escape pass. Allocation failures propagate instead of silently truncating a number or document. The run-settings stream keeps the classic locale and stream exceptions.Each serialized model record, and each clash record with all of its frames, caches formatted finite numbers by their exact bit pattern. Repeated matrix and outline values reuse that text. Non-finite values never enter the cache, so a warm cache cannot bypass the formatter’s rejection. Native tests compare the output byte for byte with the former stream implementation, including edge values and randomized records.
Persistent 128-bit hashes are lowercase hexadecimal from bounded
std::to_chars.
This covers native conversions only. Python’s own JSON and ctypes conversions can depend on a floating-point environment that embedding code changed. Use Python’s normal round-to-nearest environment with gradual underflow for exact dictionary round trips. Numeric fidelity states the user-visible rules.
Signed identifiers:
The built-in SQLite writer keeps imported signed primary keys on refetch, including
INT64_MIN. Incremental fetch-and-save and single-overlap save both keep the existing identifier and annotations.ClashQueryvalidates its identifier before it builds a native view. An out-of-range value raisesOverflowError, so2**64 + 42cannot alias query 42.ClashQuery.deserialize_from_dict()returnsNonefor an invalid identifier.Both Python readers saturate positive offsets and limits at
INT64_MAXbefore ctypes, so2**63cannot wrap to a negative offset. The-1all-rows, zero-limit and negative-offset conventions are unchanged.The ovRTX clash sample app loads a lazy frame history by the stored signed identifier, including zero, negative values and an imported
-1.
Result order and determinism#
Workers fill predetermined slots, and the writer consumes them in source order.
Database clash-record cursors order by clash hash and row identifier. Frame cursors order by time and row identifier. Indexes serve header lookup, existing-identifier enumeration and both cursors without a temporary sort.
Identical inputs give identical result content and order. SQLite file bytes can still differ: timestamps, user metadata, fresh row identifiers, page layout and transaction history are not part of the contract. JSON and HTML exports with identical ordered columns, result values and export metadata are byte-identical.
Duplicate orientation on OpenUSD. The standalone engine applies the mesh-pair ordering
callback to duplicate pairs in both narrow-phase overloads. Scope enumeration or worker completion
order therefore cannot swap name0 and name1 and change the ordered clashHash. This does not
force object 0 into scope A; the scopes select membership.
The ordering uses the platform’s SdfPath::operator<. With the pinned OpenUSD dependency, non-ASCII
names can sort differently on x86-64 and AArch64. For example, the fixture
tests/data/mesh_mesh_unicode.usda orders Ḁ before Café on x86-64 and Café before Ḁ on
AArch64. The raw orientation and its ordered clashHash are stable within one platform and
runtime, but they are not cross-platform identities for such paths.
Reading a database keeps every stored duplicate hash as stored, including one that records the reversed orientation of a pair. A refetch then reports the canonical hash as a new result, and the normal new-result and stale-result rules reconcile the two. Loading never rewrites stored identities.
Fetch and persistence performance#
These rules keep the persist phase and full-detail report capture fast. Rerun the matching correctness and performance checks before you change one.
Persisting overlaps#
Saving a whole-timeline result can write millions of clash_frame_info rows. The persist phase is
bound by per-row formatting and allocation, not by SQLite:
SuitePreparedFrame::prepare()formats both matrices of a frame withmatrixToJsonBuffer().bindBorrowedText()inSuiteSqliteWrite.cppbinds that text without an SQLite copy.Do not reintroduce a
std::ostringstreamorstd::stringper formatted value on this path.Do not page through stored results with repeated
LIMIT 1 OFFSETqueries. The cost grows quadratically with the result count.
Database settings do not address that cost. Leave synchronous, journal_mode and the redundant
idx_clash_info_id index as they are; that index is a strict prefix of
idx_clash_frame_info_overlap_order. All writes share one transaction, because BEGIN is
idempotent and the fetch commits once. SQLite permits one writer, so the insert loop cannot be
parallelized.
Full-detail report capture and SQLite bulk writes#
In full-detail persistence, report capture (faces and outlines) and the SQLite apply dominate the
fetch. The final commit and save_as are negligible, so weakening durability saves little.
Outlines are the largest stored payload. Requested details are never reduced to save time.
The ovstage capture path freezes reports and prepares them on workers:
freezeOverlapReport()freezes an immutable report snapshot on the driving thread. The frozen input holds one reference to each cooked mesh and to the triangulated face-remap arrays, not to authored geometry. Outline floating-point controls are resolved at this point.prepareOverlapReports()plans one faces job per distinct uncached hit-stream payload and one outline job per uncached report. All slots reach their final size before workers start, and each slot has exactly one writer.A job with at least 16,384 hits is split into contiguous ranges of 8,192 hits, collected in parallel and merged in a second parallel pass. This keeps every worker busy when a batch holds only a few large reports.
Nothing reaches the output until both passes succeed. A worker failure or cancellation leaves caller outputs untouched.
Serialization-only detail belongs to PreparedOverlapReport and never enters the context’s public
lazy report caches, so existing public borrowed views stay valid. Allocation failure, cancellation,
scheduler budgets and floating-point controls keep their contracts. Workers drain before rollback,
buffer release or owner destruction.
The SQLite bulk writer raises a smaller connection page cache to 64 MiB
(PRAGMA main.cache_size=-65536) after BEGIN and keeps larger settings. Journal and synchronous
settings are untouched (SuiteSqliteBulkWriter::tuneWriteCache()). A small cache multiplies cache
misses and page writes during the bulk apply. The writer’s destructor restores the previous value,
so a finished incremental fetch keeps the larger cache until it is destroyed. Restoration is best
effort: if SQLite rejects the PRAGMA, the primary diagnostic survives and the caller can restore
the setting.
Fetch timing diagnostics#
OVCLASH_SOURCE_PERF=1 makes every fetch operation print one aggregate line to stderr when it is
destroyed, on either backend. Source diagnostics lists
the other markers that the same variable enables. Save the example from
Progress and counts as refetch_states.py and run it with the variable
set, from the same directory and with the same environment as that example.
Linux:
OVCLASH_SOURCE_PERF=1 python refetch_states.py
Windows (PowerShell):
$env:OVCLASH_SOURCE_PERF = "1"
python refetch_states.py
Remove-Item Env:OVCLASH_SOURCE_PERF
Each of its three fetches prints one line. The first one looks like this, with <seconds> in
place of each measured time:
[fetch-perf] query_id=1 complete=1 wall_s=<seconds> capture_s=<seconds> lookup_s=<seconds> prepare_s=<seconds> apply_s=<seconds> release_s=<seconds> commit_s=<seconds> capture_calls=1 acquired_reports=1 appended_frames=1 batches=1 commit_calls=1
FetchPerfCounters::publish() in source/suite/SuiteFetch.cpp prints every field on every line,
in this order:
Field |
Type |
Required |
Default or values |
Description |
|---|---|---|---|---|
|
integer |
Yes |
A signed 64-bit query identifier |
The query of the fetch |
|
integer |
Yes |
|
1 when the operation committed |
|
number |
Yes |
Seconds, with six decimals |
Time from operation construction to destruction |
|
number |
Yes |
Seconds, with six decimals |
Report capture and ovstage report preparation |
|
number |
Yes |
Seconds, with six decimals |
Approval lookups and saved-data reads |
|
number |
Yes |
Seconds, with six decimals |
Frame preparation, serial or on workers |
|
number |
Yes |
Seconds, with six decimals |
Ordered header and frame writes |
|
number |
Yes |
Seconds, with six decimals |
Report and prepared-frame release |
|
number |
Yes |
Seconds, with six decimals |
The final |
|
integer |
Yes |
Unsigned 64-bit counts |
Capture attempts and reports actually acquired |
|
integer |
Yes |
Unsigned 64-bit counts |
Frames written, flushed batches and commits |
Regression coverage#
The native tests are built by tests/native/CMakeLists.txt and run with the native suite; see
Testing internals. Several compile the Suite sources into uninstalled executables
with fake canonical-engine reports and executable-local allocators, so a test can inject an
allocation failure at each site.
Target |
Covers |
|---|---|
|
Failure, approval, async, built-in and custom fetch paths, built with ovstage-style borrowed and OpenUSD-style owned reports |
|
Every stored field across group, frame-count and payload batch boundaries |
|
Report-only failures stay fatal while overlap metadata is readable |
|
|
|
C ABI guards and report ownership under allocation failure |
|
Store lifecycle guards and fetch through the serializer interface |
|
Both schedulers of |
Python tests in tests/python_tests/ cover concurrent cold opens, custom stores, the callback
guard, compatibility imports, pagination boundaries and async operations, for example the
test_custom_fetch_*.py modules, test_async_fetch_operation.py and
test_native_fetch_operation.py.
The viewer tests also cover cancellation before the first and before a later
native fetch call.