Persistence, Export and Legacy Migration#
This page of the Technical Guide explains how the
Suite data stores, the native
export and the legacy container handling are built. Read it before you
change code under source/suite/. Concepts defines the
consumer vocabulary, such as query,
overlap, clash record,
frame and fetch-and-save.
The page covers internals only. Each consumer-visible contract has its own canonical page:
Topic |
Canonical page |
|---|---|
Choosing a store, the |
|
Fetch-and-save transaction rules, clash states and the approval comparison, custom stores |
|
SQLite store path, values, reads, schema versions, migration and the system SQLite library |
|
Directory store files, commits, locking and recovery |
|
The |
|
Export inputs, output styles and validation |
|
Fetch-and-save callbacks, preparation threads and SQLite bulk writes |
Data model and persistence#
The Suite data API keeps its state in an ovclash_suite_data_t handle. Each handle owns exactly
one store implementation, chosen by the factory that creates the handle:
C factory |
Python class |
Store implementation |
|---|---|---|
|
|
|
|
|
|
The code lives under source/suite/:
Path |
Contents |
|---|---|
|
The |
|
The fetch-and-save pipeline |
|
Reading, extracting and exporting |
|
|
|
The query record model and its settings JSON validation |
|
The private |
|
The SQLite store: connection, schema, migration, reads and writes |
|
The directory store and its JSON codec, |
The serializer interface#
SuiteSerializer is the private persistence contract. It has four groups of operations:
store lifecycle:
open,migrate,save,saveAs,begin,commit,rollbackandclose;record reads and writes for queries, clash records, frames and point-cloud settings;
typed cursors:
overlaps()andframes()return aSuiteRecordCursor<Record>;createBulkWriter(), which returns the writer that one fetch-and-save operation uses.
Rules for the interface:
The shared data API and the fetch code call only this interface. They contain no SQL and never check which store they hold. A new store therefore needs only a new implementation and a factory.
Neutral state, such as the last error and the compatibility flags, stays on
ovclash_suite_data_t. Store state belongs to the implementation. For SQLite that is the connection, the open transaction and the extracted legacy payload.tests/native/TestSuiteSerializerInterface.cppbuilds anovclash_suite_data_taround an in-memory test implementation ofSuiteSerializerand drives the ordinary Suite APIs through it. It is a test fixture, not a third store and not a public factory.
Query settings are stored as the caller’s JSON text and spliced unchanged into serialized records.
SuiteModelQuery.cpp therefore accepts only strict RFC 8259 text. For example, it rejects a
vertical tab or a form feed between tokens, which C isspace() would accept. It tracks nesting on
an explicit stack instead of recursing. Any nesting depth is therefore accepted or rejected without
overflowing the thread’s stack.
Bulk writers and cursors#
Fetch-and-save writes through a SuiteBulkWriter that lives as long as the fetch operation:
A built-in store creates the writer with
createBulkWriter(). A caller-suppliedovclash_suite_fetch_serializer_tis wrapped in aSuiteCallbackBulkWriter.callbacks()exposes every writer as the fetch-serializer C callback table. The fetch driver therefore treats built-in and custom destinations alike.reserveFrameBatch(count)may return aSuiteFramePreparationBatch: reusable slots, one per frame, reserved on the driving thread.The SQLite writer returns a batch whose
serial()is true. The driving thread encodes the whole batch without a per-frame allocation.The directory writer and custom callbacks return none. When the callback table has the optional
prepare_frameandrelease_framehooks, frames are prepared on the runtime’s worker threads. The directory writer has them.
savedFrameReader()serves the approval comparison of a clash with one saved frame. The SQLite writer keeps one statement for the whole fetch instead of opening a cursor per compared clash.A live fetch blocks writes and lifecycle calls on its data handle. The writer and its prepared statements are destroyed before that block is lifted.
Typed cursors own their backend state. A SQLite cursor owns its statement. A directory cursor owns a
snapshot of record identifiers. A public clash-record cursor (ovclash_suite_overlap_cursor_t) or
frame cursor also keeps its own record buffer, so its view survives other reads. Until it is
destroyed, it counts as an active cursor on its data handle, which blocks store lifecycle calls.
Python frame reads and model dictionaries#
Each frame cursor, fetch adapter and runtime operation resolves the optional NumPy dependency at
most once. _NumpyLookup belongs to that operation; a later operation can therefore pick up NumPy
that has since been installed or imported. Native matrix arrays are copied with a slice or
numpy.frombuffer(...).copy(), without arithmetic. Record-cursor and fetch-adapter frame reads initialize frames
without repeated per-field __setattr__ calls.
ClashInfo.serialize_to_dict() and ClashFrameInfo.serialize_to_dict() allocate a first output
buffer from a validated upper bound on counts, encoded strings and fixed JSON text. They retry when
the native C API reports that the buffer is too small. Exact built-in numeric arrays can be handed
to ctypes through array.array and from_buffer; other values keep the element-by-element
conversion path. The same conversion serves Python store writes.
SQLite inventory reads#
The indexed getters read one record by position:
Getter |
Order |
Python caller |
|---|---|---|
|
ascending |
|
|
ascending |
|
|
|
– |
Reading every index with LIMIT 1 OFFSET ? costs quadratic time in total. The SQLite store
therefore remembers one position per kind: the last index, its row id, the connection’s
PRAGMA data_version and, for clash
records, the query. Each call uses one of two statements:
-- OFFSET form
SELECT ... FROM clash_query ORDER BY id LIMIT 1 OFFSET ?;
-- Successor form: seek past the previous row
SELECT ... FROM clash_query WHERE id>? ORDER BY id LIMIT 1;
Below index 1024,
OFFSETis cheaper than the bookkeeping. The call keeps no position.While any cursor on the handle is open, the call uses
OFFSETand keeps no position.From index 1024 on, the call runs in a short read transaction, so the version check and the row come from one snapshot. If the caller already has a write transaction open, the call uses it and leaves it open.
A call for the next index with an unchanged version uses the successor form. Any other call uses
OFFSETand records a new position.Outputs are published only after the call succeeds. A failure or a missing row discards the position.
For example, fetch_all_queries() on a store with 5,000 queries runs 1,025 OFFSET reads and then
3,975 successor seeks. Index 1024 still uses OFFSET, because the calls before it record no
position.
data_version changes only when another connection commits. The store therefore discards all
positions itself (invalidateInventoryPositions()) before every write, transaction boundary,
bulk-writer savepoint and connection change on its own connection.
The same invalidation discards the cached per-state grouping that
ovclash_suite_data_get_overlap_state_count_at reads. Reading the count and then every index costs
one GROUP BY scan, and writes made between the calls stay visible. Python
get_overlaps_count_by_query_id_grouped_by_state() reads the grouping this way.
Sequential C readers should use a cursor, as the ovclash_suite_data_get_overlap_by_query_at
documentation in ovclash_suite.h recommends. The two
loops of this example read the same clash records in the same order. Put the functions in a C source
file of your own that links the ovclash CMake target, and pass an open data handle and the
identifier of one of its queries:
#include <ovclash_suite/ovclash_suite.h>
#include <stdio.h>
/* Indexed reads: after index 1024, each call seeks past the previous row. */
static void print_overlaps_by_index(const ovclash_suite_data_t* data, int64_t query_id)
{
uint32_t count = 0;
if (ovclash_suite_data_get_overlap_count_by_query(data, query_id, &count).status != OVCLASH_SUITE_STATUS_SUCCESS)
return;
for (uint32_t index = 0; index < count; ++index)
{
ovclash_suite_clash_info_record_view_t view;
if (ovclash_suite_data_get_overlap_by_query_at(data, query_id, index, &view).status !=
OVCLASH_SUITE_STATUS_SUCCESS)
break;
printf("%lld\n", (long long)view.identifier); /* valid until the next data call */
}
}
/* Cursor: one ordered statement for the whole range. */
static void print_overlaps_by_cursor(const ovclash_suite_data_t* data, int64_t query_id)
{
ovclash_suite_overlap_cursor_t* cursor = NULL;
if (ovclash_suite_data_get_overlaps_by_query(data, query_id, 0, 0, &cursor).status == OVCLASH_SUITE_STATUS_SUCCESS)
{
ovclash_suite_clash_info_record_view_t view;
uint32_t has_value = 0;
while (ovclash_suite_overlap_cursor_next(cursor, &view, &has_value).status == OVCLASH_SUITE_STATUS_SUCCESS &&
has_value)
printf("%lld\n", (long long)view.identifier);
}
ovclash_suite_overlap_cursor_destroy(cursor); /* accepts NULL */
}
The single clash-record calls (lookup by ID, insert and update) and the frame count reuse
prepared statements kept in SqliteCachedStatements:
A statement is prepared on first use.
Each use resets the statement and clears its bindings before returning. Between calls, none holds a read transaction or blocks
VACUUM.closeSqliteDatabase()finalizes them before it closes the connection. Otherwisesqlite3_close_v2would leave a zombie connection that keeps the file open.
These native tests in tests/native/TestSuiteStoreLifetime.cpp pin the behavior:
testInventoryEnumerationHasBoundedWork, testOverlapStateCountsReuseOneScan,
testOverlapPositionsFollowCursorOrder and testPerRecordOverlapCallsReuseStatements.
Directory storage structures#
Directory store owns the file layout, the recovery rules and the locking contract. This section covers the in-memory structures and the commit mechanics.
Records and indexes. The store keeps the metadata of every record in memory, in ordered maps keyed by identifier. Frame geometry stays on disk until a read asks for it. Derived indexes serve the ordered reads:
Index |
Holds |
Maintenance |
|---|---|---|
Frame groups |
|
Appended unsorted; sorted only before an ordered read |
Clash hash groups |
An ordered set of |
Kept ordered, because fetch alternates hash lookups and inserts |
ID vectors |
The identifiers of all queries, of all point-cloud settings, or of one query’s clashes |
Built on first use by paging and indexed reads |
State counts |
The per-state grouping of the query last asked for |
Built on request; discarded by every clash write |
The time-code sort key is computed from the binary64 bits, so caller rounding and denormal modes cannot change the order. As in SQLite, NaN sorts first, signed zeros are equal, and equal times fall back to identifier order.
When several clashes of a query share a hash, a hash lookup returns the one with the greatest identifier.
State counting scans the whole clash map in identifier order when the query holds more than a quarter of all clashes. A smaller query looks up its sorted identifiers instead.
A rollback or a failed mutation discards every derived index. The next read rebuilds it.
Undo keeps the original map nodes instead of copies. An in-memory rollback therefore allocates nothing and succeeds even after an allocation failure. Filesystem cleanup can still fail.
Open. Opening reads manifest.json, the query and point-cloud-settings records and every
clash.json. One recursive traversal of clashes/ lists the frame files. Each frame_index entry
is checked against that list, and no frame file is parsed.
On local NTFS, the store can check the root chain once after acquiring its lock and confirming
that the lock handle names the checked .ovclash.lock file. The open handle pins that chain against
rename, removal and junction replacement. Other filesystems retain repeated root-chain checks.
Record reads check the complete expected byte count and reject an incomplete read.
Writes and commit. Writes append record payloads to one stage file in
.ovclash-transaction/, recording each payload’s offset and length in memory. A clash header write
only validates the record and marks the clash dirty. Commit then runs these steps:
Stage each dirty clash header once, then
manifest.json.Copy every record that the commit replaces or deletes to a backup file. Flush the backups as one batch.
Write
journal.json, which names every target and its backup.Copy every staged record to its target and delete removed records. Flush the published records as one batch.
Write the
COMMITTEDmarker, then remove the transaction folder.
File in |
Written |
Purpose |
|---|---|---|
|
At the first staged write of a transaction |
Marks the folder as an ovclash transaction folder |
|
Opened once per transaction and appended at each staged write |
Record payloads, indexed by offset and length; never flushed |
|
Commit step 2 |
The previous content of a replaced or deleted record |
|
Commit step 3 |
The targets and backups that recovery restores |
|
Commit step 5 |
Marks a finished commit, so recovery keeps the new records |
journal.json is the file that recovery parses (readJournal() in
source/suite/serializers/directory/SuiteDirectoryStore.cpp). It holds one object with one
member, entries, and recovery validates every entry before it restores any record:
Field |
Type |
Required |
Default or values |
Description |
|---|---|---|---|---|
|
array of objects |
Yes |
One entry per record that the commit publishes or removes |
The targets of the commit |
|
string |
Yes |
|
The backup file in |
|
integer |
Yes |
|
1: the target existed before the commit, and recovery copies its backup back. 0: recovery removes the target. |
|
string |
Yes |
A record path relative to the store root, unique within the journal |
The target record |
Staged files are checked for a complete write but not flushed, because recovery never replays a staged file. Only backups, the journal and published records must be durable.
A flush batch runs on the calling thread plus up to 15 short-lived helper threads. It uses one thread per file, at most 16 threads and at most the hardware thread count. Concurrent flushes share the file system’s journal commits, so a batch costs far less than flushing the files one by one. The first failure is rethrown after all threads join.
If publication fails, the store copies the backups back, flushes them the same way and only then removes the journal. If that restoration fails too, the handle rejects writes until it is closed.
The transaction folder is checked for symbolic links, its
formatmarker and a leftoverCOMMITTEDmarker twice per transaction: at the first staged record and when commit starts. Only the lock-holding handle changes the folder in between.The first staged record retires a leftover
COMMITTEDmarker, which an interrupted cleanup of a published transaction left behind. A marker found when commit starts, after records were staged, came from another writer. Retiring the folder then would discard the shared stage file that the pending payloads point into, so the commit fails withInvalid directory transaction folderand the transaction rolls back. The published records stay unchanged.A fetch of single-frame clashes appends each frame, each changed header and the manifest to the same stage file. Publishing creates each target directory once for consecutive records.
Fetch reconciliation skips a clash that is already absent, and already resolved when asked to resolve it. A refetch therefore does not republish its header.
This Python example shows a pending write and its commit:
import os
import tempfile
from ovclash_suite import ClashDataSerializerDirectory, ClashQuery
root = os.path.join(tempfile.mkdtemp(), "run_01")
store = ClashDataSerializerDirectory()
try:
store.open(root)
store.insert_query(ClashQuery(query_name="example"), commit=False)
print("pending:", sorted(os.listdir(os.path.join(root, ".ovclash-transaction"))))
store.commit()
print("committed:", sorted(os.listdir(root)))
finally:
store.destroy()
Output:
pending: ['format', 'stage-1.json']
committed: ['.ovclash.lock', 'manifest.json', 'queries']
JSON codec. SuiteDirectoryJson is a small DOM built for long numeric arrays:
An empty object allocates no map, and a number node holds only its text.
Raw query-settings JSON and write-only numeric arrays reuse that text, with
SuiteDirectoryJson::rawSourceset.prepareDirectoryFrame()encodes a frame view straight to text segments on a worker thread. The driving thread inserts the identifiers when it writes the segments.Each frame encoding and each numeric array formats all its numbers under one
ScopedSerializationFloatingPointEnvironment. It installs the default floating-point environment and restores the caller’s flags, rounding and denormal modes on success and on failure.
JSON costs more than SQLite in parsing, memory and file count. Prefer SQLite when compact storage
or write throughput matters. python -m benchmarks.directory_serializer
(benchmarks/directory_serializer/) measures both stores on your machine;
benchmarks/directory_serializer/README.md describes the run.
Native test file under |
Pins, for example |
|---|---|
|
|
|
|
|
|
Legacy containers and file paths#
Legacy Containers describes the container
format and how open, migrate and save_as treat it. The implementation follows these rules:
Suite file helpers and
.clashDetectionpaths are UTF-8 on every platform, Windows included.A path with an embedded NUL character is rejected before anything is touched, because the operating system would act on the part before the NUL.
ovclash_suite_copy_fileandovclash_suite_delete_filefail.ovclash_suite_file_existsreports no file, as Pythonos.path.isfiledoes.A legacy export writes a temporary sibling of the target and renames it over the target. A failed export therefore leaves an existing target unchanged.
The temporary file is named .ovclash-<target path hash>-<process id>-<sequence>.ovclash_tmp, for
example:
.ovclash-15370238862302826112-4242-0.ovclash_tmp
The target path hash separates targets in one folder, even when hosts that share a volume reuse process IDs. The process ID and the per-process sequence separate concurrent exports.
The name does not repeat the target’s name, so it stays short when the target name is already at the file-name length limit.
The
.ovclash_tmpsuffix is not.clashDetection, so a crash cannot leave a file that looks like a legacy container.On failure, the export closes and deletes its temporary file. When it cannot create the file, the error names the operating-system reason.
Schema versions#
SQLite store: Schema versions lists the current table versions, the oldest versions that migrate and the compatibility behavior that consumers see. This section maps the code and owns the rules for changing the schema. The code lives here:
What |
Where |
|---|---|
The current versions, |
|
The migration steps and |
|
The schema DDL ( |
|
Open and migrate |
|
The named constants, such as |
|
Open runs these steps:
Compare each table’s
version_inforow withlatestSqliteTableVersion(). A store without version rows is compatible.If any table differs, record whether a migration path exists, set the error text and close the store. No path leads from a newer version to an older one, so there is no downgrade.
Otherwise run
createSqliteSchema(). In one transaction it runs all theCREATE ... IF NOT EXISTSDDL and adds aversion_inforow for each table that has none. It runs on every successful open and after every migration. Additive DDL therefore reaches older files without a version bump.
Migration runs all four tables in one BEGIN IMMEDIATE transaction, one registered step at a time,
and then runs createSqliteSchema(). These steps are registered:
Table |
From |
To |
Change |
|---|---|---|---|
|
3 |
4 |
Add |
|
4 |
5 |
Add the |
|
15 |
16 |
Add the six |
|
16 |
17 |
Add the |
|
17 |
18 |
Rename |
|
5 |
6 |
Add the six |
|
6 |
7 |
Rename |
|
no row |
1 |
Create the table and its two indexes |
|
1 |
2 |
Add |
A file with an older table version than these, such as clash_info 14, has no migration path.
Decide first whether a schema change needs a version bump:
Additive DDL, such as a new index or a new
CREATE TABLE IF NOT EXISTS, must not bump a version. Schema creation re-runs on every successful open, so it reaches older files without a migration. A bump would mark every existing file incompatible until its owner migrates it.A structural change, such as a column added, removed or retyped, must bump that table’s version and register a migration step. Without the bump, old files are read with the wrong shape. Without the step, they are rejected permanently.
The tables, per-table versions and value encodings are shared with the SQLite store of Kit’s clash detection extension, so a bump also ends interoperability with Kit files of the older version; it needs an explicit decision.
To change a table’s structure:
Before you begin, make sure that you can build and validate both backends, ovstage and OpenUSD, from your source checkout (Local Development).
Bump the table’s constant in
SuiteSqliteVersions.h.Add a
SqliteMigrationStepentry to thestepstable insqliteMigrationStep()(SuiteSqliteMigration.cpp).Change the table in
schemaSql, so that new stores get the new shape.Add tests of the old schema, the migrated schema, data preservation and failure behavior, with fixtures of the old and the new schema.
Update
EXPECTED_VERSIONSintests/sentinel/inspect_sqlite.py.Update
_VERSIONS,_COLUMNSand_TYPESinbenchmarks/kpi/benchmark_summary.py.Update the tests that assert the current versions, such as
tests/python_tests/test_suite_api_sqlite_serializer.pyandtests/python_tests/test_suite_api_store_migration.py.Set the table’s “Version” cell in SQLite store: Schema versions to the new version.
Set the table’s “Oldest version that migrates” cell there to the lowest
source_versionthat thestepstable registers for the table.Run
build_ovstage.* --release --validate.Run
build_openusd.* --release --validate.
A steps entry is a SqliteMigrationStep (SuiteSqliteMigration.cpp):
Field |
Type |
Required |
Default or values |
Description |
|---|---|---|---|---|
|
|
Yes |
|
The table that the step changes |
|
|
Yes |
The version the step starts from; |
The lowest value registered for a table is the oldest version that this build migrates; the consumer table shows |
|
|
Yes |
Greater than |
The version after the step |
|
|
Yes |
One or more SQL statements |
The statements that the migration transaction runs |
The change is complete when the version_info script of Schema versions
prints the new version for the table, and each validation run ends with
All validation checks passed! No bugs, only features.... A failed run marks the failing step in
its summary table; Validation output explains it.
For example, a hypothetical new clash_info column needs these two edits:
// SuiteSqliteVersions.h
constexpr int SQLITE_CLASH_INFO_VERSION = 19;
// SuiteSqliteMigration.cpp, a new entry in the steps table of sqliteMigrationStep()
{ "clash_info", 18, 19, "ALTER TABLE clash_info ADD COLUMN example_value REAL DEFAULT -1.0;" },
Python reads the versions from the library through the named constants. ClashInfo.VERSION and the
other class constants therefore need no edit. Several Python test fixtures parse schemaSql and the
constexpr int SQLITE_<TABLE>_VERSION = <n>; lines with regular expressions, so keep both in their
current form.
This Python example prints the versions that a new store records. It reads version_info, whose
columns schemaSql defines; createSqliteSchema() adds the row of a table that has none:
Field |
Type |
Required |
Default or values |
Description |
|---|---|---|---|---|
|
|
No |
Assigned by SQLite |
The row identifier |
|
|
Yes |
|
The record table that the row versions |
|
|
Yes |
The table’s |
The schema version of that table |
The script runs from any directory with the ovclash packages importable, because it creates its
store in a temporary directory:
import os
import sqlite3
import tempfile
from contextlib import closing
from ovclash_suite import ClashData, ClashQuery
path = os.path.join(tempfile.mkdtemp(), "versions.ovclashdb")
data = ClashData()
try:
data.open(path)
data.insert_query(ClashQuery(query_name="example"))
finally:
data.destroy()
with closing(sqlite3.connect(path)) as connection:
for table, version in connection.execute("SELECT table_name, version FROM version_info ORDER BY table_name"):
print(table, version)
Output:
clash_frame_info 7
clash_info 18
clash_query 5
point_cloud_settings 2
Export architecture#
The native library builds the JSON and HTML exports. C and Python callers share one implementation:
File |
Contents |
|---|---|
|
Input validation, the JSON and HTML document builders and both output styles |
|
JSON and HTML escaping |
|
Number text, 128-bit hash text and caller-buffer copies |
|
|
Columns and rows in the Export guide defines the inputs:
ExportColumnDef(order, name, alignment=False) in Python, and the column and row arrays of the C
ABI.
Columns are emitted in array order. Each column renders the row cell that its
orderselects;orderdoes not reorder the columns.The Python helpers check that every row holds exactly one value per column before they call the C ABI. A ragged row raises
ValueError.The Python helpers always use the owned
ovclash_suite_export_text_thandle. A large document is therefore built once in C++, not once for a size query and again for the copy.
This Python example shows the first two rules. It runs from any directory with the ovclash
packages importable:
from ovclash_suite import ExportColumnDef, export_to_json
columns = [ExportColumnDef(1, "Object B"), ExportColumnDef(0, "Object A")]
rows = [["/World/A", "/World/B"]]
print(export_to_json(columns, rows).decode("utf-8"))
try:
export_to_json(columns, [["/World/A"]])
except ValueError as error:
print(f"ValueError: {error}")
Output:
{
"columns": [
"Object B",
"Object A"
],
"rows": [
[
"/World/B",
"/World/A"
]
]
}
ValueError: Export row 0 contains 1 values; expected exactly 2