Reading Attributes#

ovstage.Stage.read_attributes() reads attribute values for a query. It returns a read handle; fetch its groups of results and release each group after use.

Reading values#

By default, reads return CPU buffers. The experimental placement= argument can select a CUDA copy instead. A placed read with an availability event requires device synchronization after fetching a group and before using its payload; see Experimental Device Placement. NumPy column.array() is CPU-only.

First advance the watermark to cover the changes you need, and wait for that advance. See ovstage Overview for the read model.

Read → Fetch → Release#

This example writes values, advances the watermark, and reads them through a NumPy view in Python or a tensor pointer in C. It then releases the result group. Python releases the read handle on context-manager exit; the C example also releases it during cleanup.

# Write one value per prim, then advance the watermark before reading.
# wait() reports asynchronous failures; the context manager and finally
# block release the read and its result even if consuming the data fails.
stage.write_attribute(
    query, attr, ordinal=1, tensors=np.array([1.0, 2.0, 3.0], np.float32), is_array=False
).wait()
stage.advance_write_floor(ordinal=1).wait()

with stage.read_attributes(query, [attr], OrdinalRange.latest(1)) as read:
    read.wait()
    group = read.fetch_next()
    if group is None:
        raise SystemExit("read returned no group at ordinal 1")
    try:
        # column.array(i) is a zero-copy numpy view of tensor i (CPU).
        column = group.columns[0]
        print("read back ordinal", column.ordinal, column.array(0))  # -> [1. 2. 3.]
    finally:
        stage.release_group(group)
// Write one float per prim into the "temperature" column (UPSERT creates
// the prims on first write), advance the watermark to ordinal 1,
// then read the column back.
// Describe three contiguous CPU floats, one per prim in query order.
// The tensor references this array; keep it alive until the write completes.
float values[] = { 1.0f, 2.0f, 3.0f };
int64_t shape[] = { 3 };
int64_t strides[] = { 1 };
DLTensor tensor{};
tensor.data = values;
tensor.device = { kDLCPU, 0 };
tensor.ndim = 1;
tensor.dtype = { kDLFloat, 32, 1 }; // {code, bits, lanes}
tensor.shape = shape;
tensor.strides = strides;

// This is one scalar per prim, rather than a variable-length array per prim.
ovstage_write_data_t write{};
write.tensors = &tensor;
write.tensor_count = 1;
write.is_array = false;

// Submit the values at ordinal 1. UPSERT creates missing prims/attributes.
// waitOp checks both acceptance and completion before we proceed.
ovstage_enqueue_result_t enq =
    ovstage_write_attribute(stage, query, attrArg, /*ordinal*/ 1, write, OVSTAGE_PRIM_MODE_UPSERT);
waitOp(stage, enq, "write_attribute");

// Finish writes through ordinal 1 for all attributes. Once this completes,
// the values can be read and further writes at ordinals <= 1 are rejected.
ovstage_write_floor_desc_t writeFloor{};
writeFloor.ordinal = 1;
writeFloor.scope = OVSTAGE_SCOPE_ALL;
enq = ovstage_advance_write_floor(stage, &writeFloor);
waitOp(stage, enq, "advance_write_floor");

// Read the values at ordinal 1 (a snapshot: no start ordinal). A later change
// to this attribute would make this read fail with OUT_OF_RANGE; use
// OVSTAGE_ORDINAL_MAX as the end to read current values.
ovstage_ordinal_range_t range{};
range.end_ordinal = 1;
range.has_start_ordinal = false;
ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
enq = ovstage_read_attributes(stage, query, &attr, 1, range, &read);
waitOp(stage, enq, "read_attributes");

// Fetch the result data after the read completes. This uniform example
// returns one group; general readers fetch until END_OF_ITERATION.
size_t fetchedGroupCount = 0;
ovstage_read_group_t group{};
status = ovstage_fetch_read_next(stage, read, OVSTAGE_TIMEOUT_INFINITE, &group, 1, &fetchedGroupCount);
check(stage, status, "fetch_read_next");
if (group.column_count != 1 || group.columns[0].data.tensor_count != 1 || !group.columns[0].data.tensors[0].data)
{
    std::fprintf(stderr, "unexpected read layout\n");
    return EXIT_FAILURE;
}
// Borrow the returned floats while the group is alive. Releasing the group
// invalidates this pointer; copy the values first if they must live longer.
const ovstage_read_column_t& column = group.columns[0];
const float* out = static_cast<const float*>(column.data.tensors[0].data);
std::printf("read back ordinal %lld: %.1f %.1f %.1f\n", (long long)column.ordinal, out[0], out[1], out[2]);
ovstage_release_groups(stage, &group, 1); // the tensor data is only valid until the group is released

Read Groups and Columns#

A read group contains a shared set of logical prim rows and one or more attribute columns. In C, these are ovstage_read_group_t and ovstage_read_column_t; in Python, iterate ReadGroup.columns to get ReadColumn objects. Each column carries its attribute, ordinal, deletion state, array kind, semantic, payload, and metadata. Prim accessors and the release identity belong to the group.

If you are updating a 0.3 consumer, see Migrating read consumers from 0.3 for the renamed members and changed C fetch/release calls. For every read loop:

  • Iterate every fetched group and every column it contains, even when requesting only one attribute. Columns follow the requested attribute order after exact-token deduplication; omitted attributes mean a column’s position need not equal its position in the request. Use column.attribute to identify it. Groups have no ordering, disjointness, or stable-partition guarantee.

  • Resolve logical row i to a prim with the group’s mapping: in C, group.prims.index_map[i] when present, otherwise group.prims.offset + i; in Python, group.prim_index(i). These indices address group.prims.list / group.prim_list, not the entire query by assumption. Process only group.prims.count / group.prim_count rows.

  • Resolve the value for that same logical row independently for each column: in C, column.data.index_map[i] when present, otherwise i; in Python, column.data_row_index(i) when has_data_index_map is true, otherwise i. The value index selects a stacked fixed-size tensor row or a per-row array tensor. Never use a prim-list index as a value index or reuse another column’s mapping.

  • Check each column’s deletion state and presence before accessing payloads. An is_delete column is a tombstone with no tensors. An absent attribute is omitted; partial presence uses a column data mask or a separate group. If column.data.mask is present, only set bits identify present logical rows (Python exposes this mask through column.raw.data.mask). A present empty array, empty string, or zero is still a value. Do not manufacture defaults for missing columns or masked-out rows.

  • Keep the containing group alive while using columns, tensors, mappings, NumPy arrays, or DLPack views. Release every group after processing it, and copy anything that must outlive the release. Releasing the read handle does not release fetched groups. Python’s group context manager performs this release; it does not extend borrowed views beyond block exit.

Groups and Lifetime#

  1. Keep the read handle in a with block and call read.wait().

  2. Fetch all results with read.groups(), or call read.fetch_next() until it returns None. Do not assume one group contains the whole result.

  3. Release each group with its own with block or ovstage.Stage.release_group().

  4. Release the read handle after fetching its results. Context-manager exit does this for you.

  • ovstage_read_attributes enqueues the read and returns a read handle.

  • ovstage_fetch_read_next fills an output array of ovstage_read_group_t — each returned group carries one shared prim group and one or more attribute columns — until OVSTAGE_ERROR_END_OF_ITERATION.

  • Columns may have different masks, index maps, tensor buffers, devices, synchronization, metadata, ordinals, or deletion state. OVStage combines columns only when backend fragments already have exactly the same prim layout; it does not intersect, reorder, repartition, or copy data to align them. Single-column groups remain valid. See Read Groups and Columns for interpreting each column and its row mapping.

  • Release groups with ovstage_release_groups, then the read with ovstage_release_read. All columns and their borrowed views have the same lifetime as their containing group. A group’s pinned storage is an independent resource: releasing the read does not reclaim it, and an unreleased group keeps its outstanding-read coverage, so later writes to the same canonical attribute and prims fail with an “overlapping outstanding read” error reported at the write site. A public alias of that attribute shares the same coverage.

  • In Python, ReadGroup is a context manager that releases on block exit, including when the body raises. fetch_next() returns None at end of iteration, so bind it before entering the block (group = read.fetch_next() → if group is not None: → with group:), or iterate read.groups(), which yields only real groups. Dropping a group without releasing it triggers a finalizer that releases it and emits a ResourceWarning; treat that as a bug report rather than a strategy.

  • Python exposes columns through ReadGroup.columns. Each ReadColumn exposes payloads through array(), tensor(), and dlpack(). The semantic is an AttributeSemantic for values known to the installed bindings, or the raw integer for a newer native value so it can be preserved without reaching into the private ctypes structure.

  • wait() returns the read handle, so group = read.wait().fetch_next() chains inside the read’s with block. Do not chain on the temporary (stage.read_attributes(...).wait().fetch_next()): the Read is dropped unreleased and falls to the finalizer, and its fetched group is stranded with it. read.wait() is not redundant with fetch_next()’s own wait — it is what releases the read’s reserving op and surfaces a producer failure with its typed error.

  • A ReadColumn borrows its group through a weak reference. Keep the group alive while accessing the column: read.fetch_next().columns[0].array(0) can raise OvstageError because the temporary group has already been finalized. The same applies to a chained .dlpack(0) call.

  • column.array(i) borrows the group’s storage. A NumPy view already created from a live group does not keep that group alive and becomes invalid when it is released. For example, after group = read.fetch_next() and view = group.columns[0].array(0), calling stage.release_group(group) invalidates view. Copy out (np.array(view)) before release if the data must outlive the group. Later column access raises, but an existing view cannot be guarded.

  • A DLPack producer returned by column.dlpack(i) keeps the group alive while the producer exists. A consumer view does not: consuming the capsule destroys it, and the native deleter cannot retain the Python owner for the consumer’s lifetime. Keep the group or producer alive until the consumer is done, and do not explicitly release the group while its views are in use.

Batched Fetch and Release in C#

ovstage_fetch_read_next() accepts a caller-owned output array, its positive capacity, and a required output count. OVSTAGE_OK returns between one and capacity complete groups. Only the returned slots are valid. Timeout applies to the first group; fetch does not wait to fill the batch. A short batch is not completion: keep fetching until OVSTAGE_ERROR_END_OF_ITERATION. Timeout, completion, and other errors return a zero count. If an error occurs after some groups have been delivered, that call returns them with OVSTAGE_OK and the next fetch reports the error. A failure while delivering groups is terminal for the read, including OVSTAGE_ERROR_OUT_OF_MEMORY before any group is delivered: every later fetch returns the same error, never OVSTAGE_ERROR_END_OF_ITERATION. Release the read handle to reclaim undelivered groups. Timeouts and argument validation errors do not latch a group-delivery failure.

Each acquisition remains independently valid after another fetch or release of the read handle. Copying a descriptor does not acquire another reference. ovstage_release_groups() accepts groups from different reads or fetches on the same instance, in any order. Count zero succeeds even with a null array. Invalid, duplicate, or previously released IDs reject the entire batch without releasing anything. Finish all uses of borrowed views, including asynchronous GPU work, before releasing a group. The instance must outlive its groups. Concurrent fetches on one read handle are safe and return disjoint groups. A short batch or deferred error may be observed on another thread; serialize fetches when one consumer must observe every group and the error. Independent groups may be released from worker threads, without concurrently releasing the same acquisition.

This test reads four scalar attributes on two prims. It sums the values before releasing each batch and checks the completed result:

ovstage_read_group_t groups[3]{};
for (;;)
{
    size_t count = 0;
    const auto status = ovstage_fetch_read_next(stage_, read, OVSTAGE_TIMEOUT_INFINITE, groups, 3, &count);
    if (status == OVSTAGE_ERROR_END_OF_ITERATION)
    {
        EXPECT_EQ(count, 0u);
        break;
    }
    ASSERT_EQ(status, OVSTAGE_OK);
    ASSERT_GT(count, 0u);
    ASSERT_LE(count, 3u);
    for (size_t i = 0; i < count; ++i)
    {
        for (size_t c = 0; c < groups[i].column_count; ++c)
        {
            const auto& column = groups[i].columns[c];
            const auto& tensor = column.data.tensors[0];
            const auto* data =
                reinterpret_cast<const float*>(static_cast<const uint8_t*>(tensor.data) + tensor.byte_offset);
            for (size_t row = 0; row < groups[i].prims.count; ++row)
            {
                const size_t index = column.data.index_map ? column.data.index_map[row] : row;
                sum += data[index]; // Finish using borrowed values before release.
                ++totalValues;
            }
        }
    }
    totalGroups += count;
    ASSERT_EQ(ovstage_release_groups(stage_, groups, count), OVSTAGE_OK);
    // Even a short batch needs another fetch to observe completion.
}
ASSERT_TRUE(waitOp(stage_, ovstage_release_read(stage_, read), "release_read"));

Python’s read.fetch_next() and ovstage.Stage.release_group() remain single-group convenience methods.

Copying Results Before Release#

These snippets copy each selected heat value before releasing its group. The query selects /World/Writes/A, /World/Writes/B, and /World/Writes/C; the earlier write examples set their values to 300, 400, and 200, and advance the watermark to 15. paths is the stage’s PathDictionary (dict in C). The C helpers waitOp(), check(), and checkOvx() wait for operations and check stage or dictionary errors. The copies remain usable after cleanup:

import numpy as np

import ovstage
from ovstage import (AttributeSemantic, DLDataType, DLDataTypeCode, OrdinalRange, OvstageError,
                     PrimMode, WriteDesc, make_dltensor,
)

# Copy selected values before releasing each group; copies outlive the read.
heat = paths.intern_token("heat")
saved = []
with stage.read_attributes(query, [heat], OrdinalRange.latest(15)) as read:
    read.wait()
    for group in read.groups():
        with group:
            for column in group.columns:
                if column.is_delete:
                    continue
                rows = column.array(0)
                for i in range(group.prim_count):
                    row = column.data_row_index(i) if column.has_data_index_map else i
                    saved.append(float(rows[row]))
# Sorting is for display; read groups need not arrive in query order.
print("Copied heat values:", sorted(saved))
# Copied heat values: [200.0, 300.0, 400.0]
const ovx_string_t name = literal_to_ovx_string("heat");
ovx_token_t attribute = OVX_INVALID_TOKEN;
checkOvx(dict, path_dictionary_create_tokens_from_strings(dict, &name, 1, &attribute), "intern attribute");
ovstage_ordinal_range_t range{};
range.end_ordinal = 15;
ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
waitOp(stage, ovstage_read_attributes(stage, query, &attribute, 1, range, &read), "read attributes");
std::vector<float> saved;
for (;;)
{
    size_t fetchedGroupCount = 0;
    ovstage_read_group_t group{};
    const auto status =
        ovstage_fetch_read_next(stage, read, OVSTAGE_TIMEOUT_INFINITE, &group, 1, &fetchedGroupCount);
    if (status == OVSTAGE_ERROR_END_OF_ITERATION)
        break;
    check(stage, status, "fetch group");
    if (group.column_count != 1)
        fail("single-attribute read returned multiple columns");
    const ovstage_read_column_t& column = group.columns[0];
    const DLTensor& tensor = column.data.tensors[0];
    const auto* values = reinterpret_cast<const float*>(
        static_cast<const uint8_t*>(tensor.data) + tensor.byte_offset);
    for (uint32_t i = 0; i < group.prims.count; ++i)
    {
        const uint32_t row = column.data.index_map ? column.data.index_map[i] : i;
        saved.push_back(values[row]); // Copy the value before releasing its group.
    }
    check(stage, ovstage_release_groups(stage, &group, 1), "release group");
}
waitOp(stage, ovstage_release_read(stage, read), "release read");
// Copied values remain valid after both groups and the read are released.
std::sort(saved.begin(), saved.end());
std::printf("Copied heat values:");
for (float value : saved)
    std::printf(" %.1f", value);
std::printf("\n");
// Copied heat values: 200.0 300.0 400.0

Fixed-Size Result Shape#

A raw fixed-size read column has one scalar-lane tensor with a leading transported data-row axis. A point3f reads as (N, 3) and a matrix4d with MATRIX semantic as (N, 4, 4); both have dtype.lanes == 1. N is the transported data-row count and may differ from data.count (the logical prim count): it can be smaller when data.index_map shares rows, or larger when a query touches only part of a transported bucket. A convenience write shape is not stored; the trailing read dimensions derive from the stored component count and semantic. Python DLPack preserves them.

When column.has_data_index_map is true, use column.data_row_index(i) to find the row for each selected entry. See DLPack Tensor Exchange.

These snippets read the three-component velocity values written by the same example. They select the correct tensor row for each prim before accessing its components. Matrix views already preserve the trailing (4, 4) dimensions; C consumers can access the 16 components of each row:

velocity = paths.intern_token("velocity")
with stage.read_attributes(query, [velocity], OrdinalRange.latest(15)) as read:
    read.wait()
    for group in read.groups():
        with group:
            for column in group.columns:
                if column.is_delete:
                    continue
                # Raw and NumPy shapes are (N, 3), with scalar lanes.
                vectors = np.from_dlpack(column.dlpack(0))
                for i in range(group.prim_count):
                    row = column.data_row_index(i) if column.has_data_index_map else i
                    print("Velocity:", vectors[row].tolist())
                    # One of [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0].
const ovx_string_t name = literal_to_ovx_string("velocity");
ovx_token_t attribute = OVX_INVALID_TOKEN;
checkOvx(dict, path_dictionary_create_tokens_from_strings(dict, &name, 1, &attribute), "intern attribute");
ovstage_ordinal_range_t range{};
range.end_ordinal = 15;
ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
waitOp(stage, ovstage_read_attributes(stage, query, &attribute, 1, range, &read), "read attributes");

for (;;)
{
    size_t fetchedGroupCount = 0;
    ovstage_read_group_t group{};
    const auto status =
        ovstage_fetch_read_next(stage, read, OVSTAGE_TIMEOUT_INFINITE, &group, 1, &fetchedGroupCount);
    if (status == OVSTAGE_ERROR_END_OF_ITERATION)
        break;
    check(stage, status, "fetch group");
    if (group.column_count != 1)
        fail("single-attribute read returned multiple columns");
    const ovstage_read_column_t& column = group.columns[0];
    // Raw tensor shape is (N, 3), with scalar float32 lanes.
    const DLTensor& tensor = column.data.tensors[0];
    const auto* values = reinterpret_cast<const float*>(
        static_cast<const uint8_t*>(tensor.data) + tensor.byte_offset);
    for (uint32_t i = 0; i < group.prims.count; ++i)
    {
        const uint32_t row = column.data.index_map ? column.data.index_map[i] : i;
        const float* vector = values + row * 3;
        // Use vector[0..2] here, while the group still owns the buffer.
        (void)vector;
    }
    check(stage, ovstage_release_groups(stage, &group, 1), "release group");
}
waitOp(stage, ovstage_release_read(stage, read), "release read");

Reading Built-in Metadata#

The reserved attributes usd-path, usd-schemas, usd-prim-type, usd-ancestor-types, usd-parent, and usd-children use 64-bit identifiers. Resolve names and paths through the Path Dictionary. The Runtime Loop reads usd-prim-type after population.

usd-path, usd-parent, and usd-children are computed from current scene structure. Latest reads return them with the requested end ordinal on the result, but that ordinal does not select historical structure. usd-parent and usd-children have no per-write change records, so change-range reads return no groups for them. Latest reads of the three names do not require a watermark advance.

A change-range read of usd-path returns one group with a tombstone column (is_delete) for the query prims that were deleted whole in the range. Only the latest creation or delete of each prim in the range counts, so a prim that is deleted and then created again gives no tombstone. A prim created in the range gives no usd-path group; its other attributes show the change. Exception: this read needs a watermark. If the watermark of usd-path is less than the range end, the read fails with ErrorCode.WRITE_FLOOR_VIOLATION, also when no prim changed above it. The read cannot see a prim creation or delete that has not run yet, so only the watermark makes its result final. Scope.ALL, or Scope.INCLUDE with usd-path in its list, advances this watermark.

usd-children can span multiple groups; fetch them all. A prim without a value contributes no row: for example, the root has no parent and a leaf has no children. Writes, deletes, and maps of these three names or usd-active fail with ErrorCode.NOT_SUPPORTED. Reads and filters of usd-active also fail: live prims are always active. The name is retained in the API for now and may be removed.

These snippets query the direct children of /World/Group, read usd-path, and resolve the identifiers to strings. This is the separate Queries example, whose scene contains /World/Group/Left and /World/Group/Right. The Python tab includes its imports. The C helper resolvePath() resolves a path identifier through the dictionary:

import pathlib

import numpy as np

import ovstage
from ovstage import Filter, FilterOp, Predicate
from ovstage import OrdinalRange
from ovstage import ErrorCode, OvstageError, PopulationDomain, instancing, population

# Query the direct children, then read their current path identifiers.
children_filter = Filter([
    Predicate("usd-parent", FilterOp.IN, ["/World/Group"]),
])
path_attribute = paths.intern_token("usd-path")
matched_paths = []
with stage.query(filter=children_filter) as query:
    query.wait()
    with stage.read_attributes(query, [path_attribute], OrdinalRange.latest(2)) as read:
        read.wait()
        for group in read.groups():
            with group:  # Release every group after resolving its identifiers.
                for column in group.columns:
                    if column.is_delete:
                        continue
                    path_ids = column.array(0)
                    for i in range(group.prim_count):
                        row = column.data_row_index(i) if column.has_data_index_map else i
                        matched_paths.append(paths.path_to_string(ovstage.PrimPath(path_ids[row])))
print("Matched paths:", " ".join(sorted(matched_paths)))
# Matched paths: /World/Group/Left /World/Group/Right
// Query the direct children of /World/Group.
const ovx_string_t parent = literal_to_ovx_string("/World/Group");
ovstage_predicate_t predicate{};
predicate.attribute.string = literal_to_ovx_string("usd-parent");
predicate.op = OVSTAGE_FILTER_OP_IN;
predicate.values = &parent;
predicate.value_count = 1;
ovstage_filter_t filter{};
filter.predicates = &predicate;
filter.count = 1;
ovstage_query_handle_t query = OVSTAGE_INVALID_QUERY_HANDLE;
waitOp(stage, ovstage_query(stage, &filter, nullptr, 0, &query), "query paths");

// usd-path contains prim-path identifiers resolved through the stage dictionary.
const ovx_string_t name = literal_to_ovx_string("usd-path");
ovx_token_t pathAttribute = OVX_INVALID_TOKEN;
checkOvx(dict, path_dictionary_create_tokens_from_strings(dict, &name, 1, &pathAttribute),
         "intern usd-path");
ovstage_ordinal_range_t range{};
range.end_ordinal = 2; // No start ordinal: read current paths.
ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
waitOp(stage, ovstage_read_attributes(stage, query, &pathAttribute, 1, range, &read), "read paths");

std::vector<std::string> matchedPaths;
for (;;)
{
    size_t fetchedGroupCount = 0;
    ovstage_read_group_t group{};
    const ovstage_api_status_t fetched =
        ovstage_fetch_read_next(stage, read, OVSTAGE_TIMEOUT_INFINITE, &group, 1, &fetchedGroupCount);
    if (fetched == OVSTAGE_ERROR_END_OF_ITERATION)
        break;
    check(stage, fetched, "fetch_read_next");
    if (group.column_count != 1)
        fail("single-attribute read returned multiple columns");
    const ovstage_read_column_t& column = group.columns[0];

    const DLTensor& tensor = column.data.tensors[0];
    const auto* pathIds = reinterpret_cast<const uint64_t*>(
        static_cast<const uint8_t*>(tensor.data) + tensor.byte_offset);
    for (uint32_t i = 0; i < group.prims.count; ++i)
    {
        const uint32_t row = column.data.index_map ? column.data.index_map[i] : i;
        ovx_primpath_t path{ pathIds[row] };
        matchedPaths.push_back(resolvePath(dict, path));
    }
    check(stage, ovstage_release_groups(stage, &group, 1), "release_groups");
}
waitOp(stage, ovstage_release_read(stage, read), "release_read");
waitOp(stage, ovstage_release_query(stage, query), "release_query");

std::sort(matchedPaths.begin(), matchedPaths.end());
std::printf("Matched paths:");
for (const std::string& path : matchedPaths)
    std::printf(" %s", path.c_str());
std::printf("\n");
// Matched paths: /World/Group/Left /World/Group/Right

When to Use a Change-Range Read#

A latest read answers “what are the values now?”. A change-range read answers “what changed since I last looked?”. Use a range read when a consumer keeps its own copy of the scene and only needs to update what moved:

  • Renderers and sensors. Each frame, update only the prims whose transforms, materials, or other attributes changed since the previous frame, instead of re-reading the whole scene.

  • Consumers at a different rate. If physics advances the watermark four times per rendered frame, a consumer that runs once per frame reads the whole interval and gets every prim that changed in any of those steps, with its latest value.

  • Replication and export. Send only changed prims, and deletions, to another process, a network client, or a USD layer.

ovstage keeps no per-consumer state, so each consumer keeps a cursor: the last ordinal it has consumed.

  1. Start with a latest read of everything the consumer needs. Set the cursor to the watermark that read covered.

  2. On each update, read the range from cursor + 1 to the current watermark. Apply the returned values, and treat groups marked is_delete as deletions.

  3. Move the cursor to that watermark.

  4. If cursor + 1 is older than ovstage.Stage.get_oldest_preserved_ordinal(), the consumer has fallen behind the retained change records. Go back to step 1. See Retained Change Records.

Coordinate with producers so the bounded read completes before later writes replace its selected values. Otherwise, handle OUT_OF_RANGE by requesting a newer end or current state; see Read Ranges and Errors.

This catch-up, from the producer-consumer example, reads the range [last_seen + 1, floor] and returns the floor as the consumer’s new cursor:

def copy_group(paths, group):
    """Copy one fetched group into application-owned storage:
    (ordinal, is_delete, paths, values). prim_index(local) resolves the
    group's offset/index_map to a position in the group's OWN prim list (the
    query's pinned copy, in query order), so paths resolve through the
    dictionary. The value row honors data.index_map when present. Tombstone
    groups carry no tensors, so their values list is empty."""
    group_paths = paths.get_path_strings(group.prim_list)
    covered = [group_paths[group.prim_index(i)] for i in range(group.prim_count)]
    column = group.columns[0]
    values = []
    if not column.is_delete:
        data = column.array(0)
        for local in range(group.prim_count):
            row = column.data_row_index(local) if column.has_data_index_map else local
            values.append(float(data[row]))
    return (column.ordinal, column.is_delete, covered, values)


def read_delta_groups(stage, paths, query, temperature, begin, end):
    """Range-read [begin, end] over the query and return the result as-is,
    group by group. The EXPLICIT begin makes it a delta ("what changed since
    begin - 1"); an open begin would be a snapshot read. If a selected
    (attribute, path) changed again after end, the read raises OUT_OF_RANGE.
    Each group is copied and released at once: a borrowed group blocks every
    overlapping write for as long as it is held."""
    groups = []
    with stage.read_attributes(query, [temperature], OrdinalRange.between(begin, end)) as read:
        read.wait()
        for group in read.groups():
            groups.append(copy_group(paths, group))
            stage.release_group(group)
    return groups


def report_delta(groups, floor):
    """Example plumbing: report each copied group; S0..S3 = last path component."""
    changes = 0
    for ordinal, is_delete, group_paths, values in groups:
        names = [path.rsplit("/", 1)[-1] for path in group_paths]
        if is_delete:
            print(f"  tombstone group (ordinal {ordinal}): {', '.join(names)} deleted")
        else:
            cells = [f"{name} = {value:.1f}" for name, value in zip(names, values)]
            print(f"  value group (ordinal {ordinal}): {', '.join(cells)}")
        changes += len(group_paths)
    print(f"  delta batch: {changes} prim changes")
    print(f"consumer: last_seen -> {floor}")


def consume_deltas(stage, paths, query, temperature, last_seen) -> int:
    """One consumer catch-up: fetch the global floor; if it moved past
    last_seen, range-read the delta [last_seen + 1, floor] and report what
    changed."""
    floor = poll_write_floor(stage)
    if floor <= last_seen:
        return last_seen  # nothing sealed since the last catch-up

    print(f"consumer: floor {floor}, last_seen {last_seen} -> reading delta [{last_seen + 1}, {floor}]")
    groups = read_delta_groups(stage, paths, query, temperature, last_seen + 1, floor)
    report_delta(groups, floor)
    return floor  # the consumer's cursor: the next catch-up starts at floor + 1
/// Return the display name (S0..S3) for the local-th prim in a valid read group, using ex.dict to resolve its path.
/// Apply prims.index_map when present, otherwise prims.offset + local, and look up the path in the group's own list.
static std::string sensorName(const Example& ex, const ovstage_prim_group_t& prims, uint32_t local)
{
    const uint32_t listIndex = prims.index_map ? prims.index_map[local] : prims.offset + local;
    ovx_primpath_t pathId = OVX_INVALID_PRIMPATH;
    size_t fetched = 0;
    ovx_api_result_t ovxResult =
        path_dictionary_get_paths_from_path_list(ex.dict, prims.list, listIndex, 1, &pathId, &fetched);
    checkOvx(ex.dict, ovxResult, "get_paths_from_path_list");
    ovx_token_t tokenBuffer[16] = {};
    ovx_token_t* tokensPerPath[1] = { nullptr };
    size_t numTokens[1] = { 0 };
    size_t numProcessed = 0;
    ovxResult =
        path_dictionary_get_tokens_from_paths(ex.dict, &pathId, 1, tokenBuffer,
                                              sizeof(tokenBuffer) / sizeof(tokenBuffer[0]), tokensPerPath, numTokens,
                                              &numProcessed);
    checkOvx(ex.dict, ovxResult, "get_tokens_from_paths");
    if (numProcessed == 0 || numTokens[0] == 0 || !tokensPerPath[0])
    {
        fail("could not decompose a prim path into tokens");
    }
    ovx_string_t name{};
    ovxResult = path_dictionary_get_strings_from_tokens(ex.dict, &tokensPerPath[0][numTokens[0] - 1], 1, &name);
    checkOvx(ex.dict, ovxResult, "get_strings_from_tokens");
    return std::string(name.ptr ? name.ptr : "", name.length);
}

// What one fetched change group yields, as-is: the covered prims resolved to
// display names, plus current values for a successful value group. A tombstone
// group (is_delete = true, no tensors) carries no values -- the listed prims
// were deleted somewhere in the delta range.
struct DeltaGroup
{
    ovstage_ordinal_t ordinal = 0;
    bool isDelete = false;
    std::vector<std::string> names;
    std::vector<float> values; // one per covered prim; empty for a tombstone group
};

// Copy one fetched group into application-owned storage. The value row for
// the local-th prim honors data.index_map when present. Copying is what lets
// the caller release the group promptly: a borrowed group blocks every
// overlapping write for as long as it is held.
static bool copyGroup(const Example& ex, const ovstage_read_group_t& group, DeltaGroup* out)
{
    if (group.column_count != 1 || !group.columns)
    {
        std::fprintf(stderr, "single-attribute read returned an unexpected column layout\n");
        return false;
    }
    const ovstage_read_column_t& column = group.columns[0];
    out->ordinal = column.ordinal;
    out->isDelete = column.is_delete;
    out->names.clear();
    out->values.clear();
    for (uint32_t local = 0; local < group.prims.count; ++local)
        out->names.push_back(sensorName(ex, group.prims, local));
    if (column.is_delete)
        return true;
    if (column.data.tensor_count != 1 || !column.data.tensors[0].data)
    {
        std::fprintf(stderr, "unexpected read-group layout (want one tensor row per covered prim)\n");
        return false;
    }
    const float* cells = static_cast<const float*>(column.data.tensors[0].data);
    for (uint32_t local = 0; local < group.prims.count; ++local)
    {
        const uint32_t row = column.data.index_map ? column.data.index_map[local] : local;
        out->values.push_back(cells[row]);
    }
    return true;
}

// Range-read [startOrdinal, endOrdinal] over all four sensors and return the
// fetched groups, copied, in outGroups. The EXPLICIT-BEGIN range makes it a
// delta ("what changed since startOrdinal - 1"); an open begin would be a
// snapshot read. Each fetched group covers the prims that changed in the
// range for one attribute. If a selected (attribute, path) changed again after
// endOrdinal, the read returns OUT_OF_RANGE.
// Returns false on a failed op (already reported) so the caller decides the
// policy; the group and read handles are released either way.
static bool consumeDelta(const Example& ex, ovstage_ordinal_t startOrdinal, ovstage_ordinal_t endOrdinal,
                         std::vector<DeltaGroup>* outGroups)
{
    ovstage_ordinal_range_t delta{};
    delta.start_ordinal = startOrdinal; // explicit begin: only changes AT or AFTER startOrdinal
    delta.end_ordinal = endOrdinal;     // inclusive end of the selected changes
    delta.has_start_ordinal = true;

    ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
    ovstage_enqueue_result_t enq = ovstage_read_attributes(ex.stage, ex.allQuery, &ex.temperature, 1, delta, &read);
    if (!tryWaitOp(ex.stage, enq, "read_attributes"))
        return false;

    bool ok = true;
    for (;;)
    {
        size_t fetchedGroupCount = 0;
        ovstage_read_group_t group{};
        const ovstage_api_status_t fetch =
            ovstage_fetch_read_next(ex.stage, read, OVSTAGE_TIMEOUT_INFINITE, &group, 1, &fetchedGroupCount);
        if (fetch == OVSTAGE_ERROR_END_OF_ITERATION)
            break;
        ok = tryCheck(ex.stage, fetch, "fetch_read_next");
        if (!ok)
            break;

        DeltaGroup rows;
        ok = copyGroup(ex, group, &rows); // on failure, shut down like any failed op: the group is still released
        if (ok)
            outGroups->push_back(rows);
        const ovstage_api_status_t status = ovstage_release_groups(ex.stage, &group, 1);
        ok = tryCheck(ex.stage, status, "release_groups") && ok;
        if (!ok)
            break;
    }
    enq = ovstage_release_read(ex.stage, read);
    ok = tryWaitOp(ex.stage, enq, "release_read") && ok;
    return ok;
}

// Example plumbing: report the range a catch-up covered, each copied group
// (value or tombstone), and the batch size in prim changes.
static void reportDelta(const std::vector<DeltaGroup>& groups, ovstage_ordinal_t floor, ovstage_ordinal_t lastSeen)
{
    std::printf("consumer: floor %llu, last_seen %llu -> reading delta [%llu, %llu]\n", (unsigned long long)floor,
                (unsigned long long)lastSeen, (unsigned long long)(lastSeen + 1), (unsigned long long)floor);
    uint32_t changes = 0;
    for (const DeltaGroup& group : groups)
    {
        if (group.isDelete)
        {
            std::printf("  tombstone group (ordinal %lld):", (long long)group.ordinal);
            for (size_t i = 0; i < group.names.size(); ++i)
                std::printf(i ? ", %s" : " %s", group.names[i].c_str());
            std::printf(" deleted\n");
        }
        else
        {
            std::printf("  value group (ordinal %lld):", (long long)group.ordinal);
            for (size_t i = 0; i < group.names.size(); ++i)
                std::printf(i ? ", %s = %.1f" : " %s = %.1f", group.names[i].c_str(), group.values[i]);
            std::printf("\n");
        }
        changes += static_cast<uint32_t>(group.names.size());
    }
    std::printf("  delta batch: %u prim changes\n", changes);
    std::printf("consumer: last_seen -> %llu\n", (unsigned long long)floor);
}

// One consumer catch-up (the deterministic mode runs this): fetch the global
// floor; if it moved past last_seen, consume the delta [last_seen + 1, floor],
// report it and advance the cursor. False means an op failed and was already
// reported.
static bool consumerCatchUp(const Example& ex, ovstage_ordinal_t* lastSeen)
{
    ovstage_ordinal_t floor = 0;
    if (!fetchGlobalFloor(ex.stage, &floor))
        return false;
    if (floor <= *lastSeen)
        return true; // nothing sealed since the last catch-up

    std::vector<DeltaGroup> groups;
    if (!consumeDelta(ex, *lastSeen + 1, floor, &groups))
        return false;
    reportDelta(groups, floor, *lastSeen);

    *lastSeen = floor; // the consumer's cursor: the next catch-up starts at floor + 1
    return true;
}

Choose a latest read instead when the consumer has no copy to update, or when almost everything changes every step. A range read then returns the same data with extra bookkeeping. See also Choosing an API.

Read Ranges and Errors#

The checks below describe the underlying read failure; asynchronous wait/fetch can instead expose OP_FAILED with a diagnostic. See Error Handling and Diagnostics before branching on an error code.

The default history_latest implementation stores only current attribute values. A snapshot (OrdinalRange.latest(end) in Python) checks every queried path for each requested attribute. A change range [start, end] checks only queried (attribute, path) pairs changed within that range.

For each requested attribute, both forms apply these checks in order:

  1. A selected, unsealed change at or before end returns OVSTAGE_ERROR_WRITE_FLOOR_VIOLATION.

  2. A recorded change after end on a selected path returns OVSTAGE_ERROR_OUT_OF_RANGE, whether that later change is sealed or not.

Changes on unrelated paths do not affect these checks. For example, seal a write at 3, then overwrite it at 5. Reading that attribute with end 4 returns OUT_OF_RANGE. Sealing 5 does not restore the old value. Use a newer end or OVSTAGE_ORDINAL_MAX (ovstage.ORDINAL_MAX in Python) for current state. An end of OVSTAGE_ORDINAL_MAX skips the second check, but a selected unsealed change still returns WRITE_FLOOR_VIOLATION. Because a later change after the end makes a bounded read return OUT_OF_RANGE, a bounded read is not a replay point. A zero-initialized C range is a snapshot at ordinal 0, not a request for current values.

These rules describe an instance of history_latest, the default, and every unselected pair of an instance of history_selective. A selected pair retains its earlier sealed values; see Earlier Values of Selected Pairs.

While the end is above the attribute’s write floor, changes between the floor and the end can still be admitted and, once sealed, change what the same request returns. Once the end is at or below the floor, later writes, deletes and maps cannot change the recorded values that a successful read of the same request returns for paths the query still selects. This does not cover derived built-ins or query membership, which reflect current state, changes that ovstage_compute_hierarchy records at or below the floor, or history below the retention frontier.

A returned group’s ordinal is informational. It may be above or below the requested end and is not, by itself, proof of which state the payload represents.

These checks use recorded changes. Snapshot reads of values without change records, including derived built-ins, return current state. Queries select current paths, not the paths present at an earlier ordinal. Under FLOOR_ONLY admission, a write or delete above the applicable floors can be admitted at an older ordinal than an existing change to the same attribute and path; reads then return the most recently applied change. STRICTLY_INCREASING and the default NONDECREASING policy reject such older changes against retained history.

Before relying on an old snapshot or interval, query the retention frontier with ovstage_get_oldest_preserved_ordinal (Stage.get_oldest_preserved_ordinal() in Python). History below that frontier may have been discarded, so a successful read does not guarantee the requested earlier state. For example, after an attribute’s deletion history is discarded, a snapshot from before that deletion may return no row for the attribute instead of OUT_OF_RANGE.

In the write-options example, A and B last changed heat at ordinal 14, while C last changed at 12. These snippets select the inclusive interval [14, 14], so only A and B contribute values. The watermark is already 15, and no later writes have replaced those values:

# Only A and B changed heat at ordinal 14; C last changed at ordinal 12.
heat = paths.intern_token("heat")
changed = []
with stage.read_attributes(query, [heat], OrdinalRange.between(14, 14)) as read:
    read.wait()
    for group in read.groups():
        with group:
            for column in group.columns:
                if column.is_delete:
                    continue  # Deletions carry no value tensor.
                values = column.array(0)
                for i in range(group.prim_count):
                    row = column.data_row_index(i) if column.has_data_index_map else i
                    changed.append(float(values[row]))
print("Heat values changed at 14:", sorted(changed))
# Heat values changed at 14: [300.0, 400.0]
const ovx_string_t name = literal_to_ovx_string("heat");
ovx_token_t attribute = OVX_INVALID_TOKEN;
checkOvx(dict, path_dictionary_create_tokens_from_strings(dict, &name, 1, &attribute), "intern attribute");
ovstage_ordinal_range_t range{};
// A and B changed at 14; C last changed at 12.
range.has_start_ordinal = true;
range.start_ordinal = 14;
range.end_ordinal = 14;
ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
waitOp(stage, ovstage_read_attributes(stage, query, &attribute, 1, range, &read), "read attributes");
std::vector<float> saved;
for (;;)
{
    size_t fetchedGroupCount = 0;
    ovstage_read_group_t group{};
    const auto status =
        ovstage_fetch_read_next(stage, read, OVSTAGE_TIMEOUT_INFINITE, &group, 1, &fetchedGroupCount);
    if (status == OVSTAGE_ERROR_END_OF_ITERATION)
        break;
    check(stage, status, "fetch group");
    if (group.column_count != 1)
        fail("single-attribute read returned multiple columns");
    const ovstage_read_column_t& column = group.columns[0];
    if (column.is_delete)
    {
        // Deletions carry no value tensor; still release their group.
        check(stage, ovstage_release_groups(stage, &group, 1), "release deletion group");
        continue;
    }
    const DLTensor& tensor = column.data.tensors[0];
    const auto* values = reinterpret_cast<const float*>(
        static_cast<const uint8_t*>(tensor.data) + tensor.byte_offset);
    for (uint32_t i = 0; i < group.prims.count; ++i)
    {
        const uint32_t row = column.data.index_map ? column.data.index_map[i] : i;
        saved.push_back(values[row]); // Copy the value before releasing its group.
    }
    check(stage, ovstage_release_groups(stage, &group, 1), "release group");
}
waitOp(stage, ovstage_release_read(stage, read), "release read");
std::sort(saved.begin(), saved.end());
std::printf("Heat values changed at 14:");
for (float value : saved)
    std::printf(" %.1f", value);
std::printf("\n");
// Heat values changed at 14: 300.0 400.0

Retained Change Records#

Before relying on an old interval, call ovstage.Stage.get_oldest_preserved_ordinal(), wait for the returned ordinal query, fetch its value, and release the query. Records of which attributes changed on which prims are exact at or above that value. Older records may have been combined or discarded; do not assume a fixed retention depth.

This boundary describes change records, not stored versions of values. A value can be unavailable even when its change record is retained.

These snippets check whether an interval starting at ordinal 14 is within the retained change records. They release the ordinal query after fetching its result; the check does not guarantee that the interval’s values still exist:

# Query the boundary before relying on exact membership of an old interval.
with stage.get_oldest_preserved_ordinal() as ordinal_query:
    ordinal_query.wait()
    oldest = ordinal_query.fetch()
requested_start = 14
if requested_start < oldest:
    raise RuntimeError("Change records for this interval are no longer exact")
# A subsequent range read can still fail if a newer write replaced its values.
// Query the boundary before relying on exact membership of an old interval.
ovstage_ordinal_query_handle_t ordinalQuery{};
waitOp(stage, ovstage_get_oldest_preserved_ordinal(stage, &ordinalQuery), "query oldest ordinal");
ovstage_ordinal_t oldest = 0;
check(stage, ovstage_fetch_ordinal(stage, ordinalQuery, OVSTAGE_TIMEOUT_INFINITE, &oldest), "fetch ordinal");
waitOp(stage, ovstage_release_ordinal_query(stage, ordinalQuery), "release ordinal query");
const ovstage_ordinal_t requestedStart = 14;
if (requestedStart < oldest)
{
    fail("Change records for this interval are no longer exact");
}
// A subsequent range read can still fail if a newer write replaced its values.

Earlier Values of Selected Pairs#

An instance of history_latest, the default, keeps history off. It stores the latest committed value of every cell, and the checks above apply to every read. An instance of history_selective turns history on for the (prim, attribute) pairs that the application selects with ovstage_enable_history() (Python ovstage.Stage.enable_history()). A selected pair retains its earlier sealed values, up to the process setting OVSTAGE_CONFIG_RETENTION_WINDOW (default 4). It answers a snapshot at a finite end with the value sealed at or before that end, and it answers a change range from the retained history. Every other pair keeps the rules above. The instance does not serve the experimental device placement extension.

Warning

History support is experimental. The history_selective implementation, the ovstage.history.v1 selection extension of ovstage_history.h and the OVSTAGE_CONFIG_RETENTION_WINDOW setting can change between releases without a deprecation period. The library does not guarantee source compatibility, ABI or semantics. Isolate their use behind an application adapter. Check availability at run time.

The history_selective implementation is available as a preview of the planned direction for history support, intended for early evaluation and feedback. It may be less stable at runtime and offer lower performance than the default history_latest implementation. Validate stability and performance with your application’s workloads before adopting it.

The sequence of a selective history is:

  1. Create the instance with the implementation name history_selective (ovstage_instance_desc_t.implementation, Python StageConfig(implementation="history_selective")).

  2. Write and seal the first values. A selection copies the sealed values of its pairs as the retained baseline, so seal before you select.

  3. Select the pairs with ovstage_enable_history() on a quiescent instance: no pending stage or renderer work, and no live reads, groups or maps. A completed query gives the prims, and the attribute list gives the attributes. Later matches of the same filter are not selected.

  4. Write and seal later ordinals. Every write of a selected pair is recorded at its own ordinal, and a floor advance waits for those records.

  5. Read a selected pair at an earlier ordinal with a snapshot at that end or with a change range. A latest read is unchanged.

  6. Stop the retention with ovstage_disable_history(). The call discards the retained history of the pairs and keeps their live values.

Two failures need a retry. If the baseline copy of a selection fails, every mutation and publication of the instance is refused until the identical selection is retried with success, or until the instance is destroyed. A failed copy activates no partial selection. If a floor advance reports that a record did not land, the history floor stays behind. A historical read of a selected pair is then refused with WRITE_FLOOR_VIOLATION until a floor advance succeeds. Retry the floor advance with the whole-stage scope. ovstage_history.h states both contracts in full.

These snippets run the sequence against the produced package and wheel:

import ovstage

# Select the implementation "history_selective": history is on for the
# pairs that enable_history selects. The selection is per stage: a stage
# of "history_latest", the default, in the same process keeps history off.
config = ovstage.StageConfig(implementation="history_selective")
with ovstage.Stage("history.selected", config=config) as stage:
    paths = ovstage.PathDictionary(stage)
    temperature = paths.intern_token("temperature")
    with paths.create_path_list_from_strings(["/World/A"]) as plist:
        query = stage.query_from_path_list(plist)

        # Write and seal the first value, then select the exact pair.
        # The sealed value becomes the retained baseline.
        stage.write_attribute(query, temperature, 1, np.asarray([1.0], dtype=np.float32), is_array=False).wait()
        stage.advance_write_floor(1, ovstage.Scope.ALL).wait()
        stage.enable_history(query, [temperature])

        # A later sealed write keeps the earlier value readable for this pair.
        stage.write_attribute(query, temperature, 2, np.asarray([2.0], dtype=np.float32), is_array=False).wait()
        stage.advance_write_floor(2, ovstage.Scope.ALL).wait()
        first = _read_one(stage, query, temperature, ovstage.OrdinalRange.between(1, 1))
        latest = _read_one(stage, query, temperature, ovstage.OrdinalRange.latest(2))

        # Disabling discards the retained history and keeps the live value.
        stage.disable_history(query, [temperature])
        query.release().wait()
// Select the implementation "history_selective" in the descriptor of the
// instance: history is on for the pairs that ovstage_enable_history
// selects. The selection is per instance: an instance of "history_latest",
// the default, in the same process keeps history off.
ovstage_instance_desc_t desc{};
desc.name = "test.ovstage.history.selected";
desc.implementation = "history_selective";
ovstage_instance_t* stage = nullptr;
ASSERT_EQ(ovstage_create_instance(&desc, &stage), OVSTAGE_OK);
path_dictionary_instance_t* dict = ovstage_get_path_dictionary(stage);

const ovx_string_t path = str("/World/A");
ovx_primpath_list_t list = OVX_INVALID_PRIMPATH_LIST;
ASSERT_EQ(path_dictionary_create_path_list_from_strings(dict, &path, 1, &list).status, OVX_API_SUCCESS);
ovstage_query_handle_t query = OVSTAGE_INVALID_QUERY_HANDLE;
ASSERT_EQ(ovstage_query_from_path_list(stage, list, &query), OVSTAGE_OK);
const ovx_string_t attrName = str("temperature");
ovx_token_t attr = OVX_INVALID_TOKEN;
ASSERT_EQ(path_dictionary_create_tokens_from_strings(dict, &attrName, 1, &attr).status, OVX_API_SUCCESS);

// Write and seal the first value, then select the exact (prim, attribute)
// pair. The sealed value becomes the retained baseline.
writeOne(stage, query, attr, 1.0f, /*ordinal*/ 1);
sealAll(stage, 1);
ovx_token_or_string_t selection{ attr, {} };
ASSERT_EQ(ovstage_enable_history(stage, query, &selection, 1), OVSTAGE_OK);

// A later sealed write keeps the earlier value readable for this pair.
writeOne(stage, query, attr, 2.0f, /*ordinal*/ 2);
sealAll(stage, 2);
ASSERT_TRUE(readOne(stage, query, attr, fixed(1), &firstValue));
ASSERT_TRUE(readOne(stage, query, attr, latest(2), &latestValue));

// Disabling discards the retained history and keeps the live value.
ASSERT_EQ(ovstage_disable_history(stage, query, &selection, 1), OVSTAGE_OK);

waitOp(stage, ovstage_release_query(stage, query), "release_query");
path_dictionary_release_path_list_reference(dict, list);
ASSERT_EQ(ovstage_destroy_instance(stage), OVSTAGE_OK);

Selecting Attributes with Patterns#

An entry of the attribute list can also be a selector pattern:

  • * selects every attribute that the read can return.

  • A prefix followed by *, such as primvars:*, selects every attribute whose name starts with the prefix.

A pattern has exactly one *, as its last character. The match is case sensitive and uses the full name. Other forms that contain *, such as *mass or a*b, fail with ErrorCode.INVALID_ARGUMENT. Each read finds the matching names again, so a read includes attributes that were written after the query was made.

# "primvars:*" selects every attribute whose name starts with "primvars:".
# A latest read returns the current value of each matched attribute.
read = stage.read_attributes(query, [paths.intern_token("primvars:*")], OrdinalRange.latest(2))
read.wait()
matched = {}  # attribute name -> {prim path: value}
for group in read.groups():
    with group:
        # A group may carry several columns over the same prim rows.
        group_paths = paths.get_paths(group.prim_list)
        for column in group.columns:
            # Keep every group's rows, keyed by column name and prim path.
            name = paths.token_to_string(column.attribute)
            rows = matched.setdefault(name, {})
            values = column.array(0)  # Copy values before releasing the group.
            for local in range(group.prim_count):
                path = paths.path_to_string(group_paths[group.prim_index(local)])
                row = column.data_row_index(local) if column.has_data_index_map else local
                rows[path] = float(values[row])
read.release().wait()
// "primvars:*" selects every attribute whose name starts with "primvars:".
// A latest read returns the current value of each matched attribute.
const ovx_token_t selector = intern("primvars:*");
ovstage_ordinal_range_t range{};
range.end_ordinal = 1;
ovstage_read_handle_t read = OVSTAGE_INVALID_READ_HANDLE;
ASSERT_TRUE(waitOp(stage_, ovstage_read_attributes(stage_, query_, &selector, 1, range, &read), "read"));

std::vector<std::string> matched;
size_t fetchedBatchCount = 0;
ovstage_read_group_t group{};
ovstage_api_status_t status;
while ((status = ovstage_fetch_read_next(stage_, read, OVSTAGE_TIMEOUT_INFINITE,
    &group, 1, &fetchedBatchCount)) == OVSTAGE_OK)
{
    // Each group can hold several columns over the same prim rows.
    for (size_t i = 0; i < group.column_count; ++i)
        matched.push_back(name(group.columns[i].attribute));
    ovstage_release_groups(stage_, &group, 1);
}
// END_OF_ITERATION is the normal end. Any other status is an error.
EXPECT_EQ(status, OVSTAGE_ERROR_END_OF_ITERATION);
waitOp(stage_, ovstage_release_read(stage_, read), "release_read");

Rules for the result:

  • Explicit attribute names enter the selection first, in caller order after exact-token deduplication. Repeated explicit names do not add columns again.

  • Then come the names that the patterns add, sorted by name. A pattern does not add a name that the selection already has, so overlapping patterns give each name one time.

  • Names that start with _ or usd- are hidden, except usd-path. A pattern selects a hidden name only when the prefix of the pattern starts with the same namespace. Thus *, u*, and usd* do not select usd-schemas, but usd-* and usd-s* do. * does not select _name, but _* does. The rule applies to the start of the name only. A hidden name in the list of attribute names is read as usual.

  • A pattern that matches usd-path selects it. In a latest read it gives the prims. In a change-range read it gives the tombstones of prims deleted whole in the range.

  • A latest read with usd-* also selects usd-parent, usd-children, usd-prim-type, usd-schemas, and usd-ancestor-types. Each gives groups only for the prims that have a value, and usd-children groups are ragged arrays.

  • A change-range read with usd-* selects usd-prim-type, usd-schemas, and usd-ancestor-types when they changed in the range, as any recorded attribute. It never selects usd-parent or usd-children. Patterns never match usd-active.

  • A pattern that matches no name gives zero groups. An empty attribute list, or a query with no prims, also gives zero groups.

Which names a pattern finds:

  • A latest read finds the names that the query prims have now. It also finds a name that was deleted above its watermark. That delete is not sealed, so the read fails with WRITE_FLOOR_VIOLATION until the watermark of the name reaches the delete.

  • A latest read with an end below OVSTAGE_ORDINAL_MAX also finds a name that changed, or was deleted, after the end. The read then fails with OUT_OF_RANGE, as for a name in the list. Thus the read does not leave out a name that the prims had at the end.

  • A change-range read finds the names that changed, or were deleted, on the query prims in the range.

Each name that a pattern finds gets the same checks as a name in the list. A change-range read with a pattern also has two more checks:

Check

Error

Why, and what to do

The stage-wide watermark is at or above the range end.

WRITE_FLOOR_VIOLATION

A pattern can match a name that no prim has yet. That name has no watermark of its own, so only the stage-wide watermark seals it. Thus the read fails while the stage-wide watermark is below the range end, also when every known name has a higher watermark. Before the read, advance the watermark to the range end with Scope.ALL.

The range start is at or above ovstage.Stage.get_oldest_preserved_ordinal().

OUT_OF_RANGE

Records of deleted attributes below that value can be gone, so the pattern could miss a deleted name. Read from a later start.

Warning

Do not use ovstage.Stage.get_attribute_write_floor() with no attribute to check the stage-wide watermark. After a Scope.INCLUDE or Scope.EXCLUDE advance, it can report a higher value than the stage-wide watermark.

A latest read with a pattern does not check the stage-wide watermark. The two checks apply also when the query has no prims. When the list has names and patterns, the checks apply to the whole read.

An outstanding write or delete on the query prims to a matching name fails the read with ErrorCode.OP_FAILED. This is the same as for an attribute name. The rule includes a write that adds a new name.

Note

Because * is a selector, an attribute name that contains * is reserved for read selection. Writes, maps, deletes, query filters and attribute lists, ovstage.Stage.get_attribute_write_floor(), and the attribute lists of Scope.INCLUDE and Scope.EXCLUDE watermark advances reject such a name with ErrorCode.INVALID_ARGUMENT. Scope.ALL does not use its attribute list, so it does not check it.

For the current limits of patterns, see Limitations and Current Behavior.

Further Reading#

See Device Placement (Experimental) for the experimental GPU-to-GPU workflow, extension access, event ordering, and buffer lifetimes.