LLAM v3.0.1

Owned scopes and typed outcomes

Edit pageReport a problemLast modified: 03 December 2026Declared in <llam/scope.h>

!!! note "Available in LLAM 3.0.1" These APIs require headers and runtime with ABI 2.5 or newer. The 3.0.1 SDK provides ABI 2.7. Dynamic bindings must check the ABI minor and resolve the required symbols first.

On this page

Include <llam/scope.h>. A scope owns execution, cancellation and cleanup; a future owns interest in one outcome. Destroying a drained scope does not destroy its ready futures or values. Dropping a future never detaches work from its scope. The existing task/group/result APIs retain their contracts.

Initialize and describe values

llam_result_contract_initInitialize success and application-error descriptors to unit.
int llam_result_contract_init(llam_result_contract_t *out, size_t out_size);
llam_value_spec_initInitialize an owned-value specification to unit with default free cleanup.
int llam_value_spec_init(llam_value_spec_t *out, size_t out_size);
llam_scope_opts_initInitialize reserved scope options to zero.
int llam_scope_opts_init(llam_scope_opts_t *out, size_t out_size);
llam_typed_task_spec_initInitialize a task specification with unit results and no argument.
int llam_typed_task_spec_init(llam_typed_task_spec_t *out, size_t out_size);
llam_outcome_initInitialize an empty outcome record.
int llam_outcome_init(llam_outcome_t *out, size_t out_size);
llam_value_create_exAdopt initialized, aligned data and its cleanup context on success only.
int llam_value_create_ex(const llam_value_spec_t *spec,
                         size_t spec_size,
                         llam_value_t **out);

Adopt an initialized, aligned value. Failure leaves data and output untouched. Success transfers data/drop_context ownership; the value handle is move-only.

llam_value_copy_exCopy a trivially byte-copyable value into separately allocated aligned storage.
int llam_value_copy_ex(const llam_type_descriptor_t *type,
                       size_t type_size,
                       const void *data,
                       llam_value_t **out);

Copy a trivially byte-copyable representation into independently owned storage.

llam_value_data_exValidate the expected semantic type and borrow the owned storage.
int llam_value_data_ex(llam_value_t *value,
                       const llam_type_descriptor_t *expected,
                       size_t expected_size,
                       void **out);

Borrow storage while retaining exclusive ownership of the handle. Type failure leaves output untouched. Concurrent handle consumption invalidates the borrow.

llam_value_releaseConsume the value handle and run its cleanup exactly once.
int llam_value_release(llam_value_t *value);

Consume a value and invoke its cleanup once. Claimed values return EBUSY.

llam_type_descriptor_t has a fixed 32-byte layout: id_high, id_low, and size are 64-bit fields; alignment and reserved are 32-bit fields. IDs are stable semantic identities, never RTTI or process addresses. Both IDs zero mean unit, which requires size zero and alignment one. Alignment must be a nonzero power of two; reserved fields must be zero. Matching size alone is insufficient.

LLAM_TYPE_UNIT_INIT, LLAM_TYPE_U64_INIT, LLAM_TYPE_I64_INIT, LLAM_TYPE_U32_INIT, and LLAM_TYPE_I32_INIT provide interoperable native scalar descriptors. Application IDs must avoid the reserved LLAM_TYPE_SCALAR_ID_HIGH namespace. These are native representations, not portable serialized formats. The 64-byte llam_result_contract_t contains success and error descriptors.

llam_value_spec_t contains the descriptor, data, a drop callback and its context. A null callback selects free(data). The callback runs outside runtime locks, under a native guard. It must be nonblocking, thread-neutral, non-throwing and must not reenter LLAM. Keep its provider module loaded and context valid until every owned value using it is released, including values retained after runtime teardown. A byte copy does not clone referenced resources or invoke C++ constructors.

A value handle is move-only and runtime-neutral. A successful adoption transfers ownership; failure leaves the original allocation and output untouched. A data borrow is valid only while the caller owns the value: do not consume it concurrently. Owned arguments may contain pointers only when their pointees independently remain valid through full task retirement. This API does not make borrowed stack storage safe after an early return.

Spawn and collect

llam_runtime_scope_create_exCreate an open scope on an explicit runtime; null options select defaults.
int llam_runtime_scope_create_ex(llam_runtime_t *runtime,
                                 const llam_scope_opts_t *opts,
                                 size_t opts_size,
                                 llam_scope_t **out);

Consume a value and invoke its cleanup once. Claimed values return EBUSY.

llam_scope_spawn_exAdmit owned work, consuming its argument only on success and returning an independent future.
int llam_scope_spawn_ex(llam_scope_t *scope,
                        const llam_typed_task_spec_t *spec,
                        size_t spec_size,
                        llam_future_t **out);

Spawn owned work. External cancellation is ORed with the private scope token. Failure preserves argument and output. Closed admission returns EPIPE.

llam_task_set_outcome_exSet the current scoped task's candidate outcome once; consume a matching value only on success.
int llam_task_set_outcome_ex(const llam_outcome_t *outcome,
                             size_t outcome_size);

Set one candidate outcome on the current scoped task. Values are consumed only on success; a second set returns EBUSY. Public readiness follows full retirement.

llam_future_wait_untilWait without consuming; normal caller cancellation and request deadlines apply.
int llam_future_wait_until(llam_future_t *future, uint64_t deadline_ns);

Wait without consuming. Caller cancellation/deadline affects this wait only. Ready results win over an expired deadline. Host waits never drive a runtime.

llam_future_take_exNonblocking typed take; consume a ready future only after full type/output validation.
int llam_future_take_ex(llam_future_t *future,
                        const llam_result_contract_t *expected,
                        size_t expected_size,
                        llam_outcome_t *out,
                        size_t out_size);

Nonblocking single-consumer take. Expected types and the complete V1 output prefix are validated before ownership moves. EAGAIN means not ready. A take returning zero may yield APP_ERROR, CANCELLED or RUNTIME_ERROR, not only OK.

llam_future_releaseConsume result interest, preserving scope ownership of the execution.
int llam_future_release(llam_future_t *future);

Consume result interest; scope ownership of execution is retained.

A llam_typed_task_spec_t supplies an entry, an owned argument handle (or null), optional borrowed spawn options plus their size, and both result descriptors. The default runtime still requires a compiler-qualified entry. An explicit child token is ORed with the private scope token; scope cancellation never cancels that external token. Spawn racing with close either reserves ownership before close, or returns EPIPE with the argument and output unchanged. Admission/allocation failure also preserves the original argument handle.

The task receives the argument's data pointer and must not free it. It may call llam_task_set_outcome_ex once. A second call returns EBUSY; invalid type/kind leaves the candidate value owned by the caller. The setter permits OK, APP_ERROR, or CANCELLED; only the runtime produces RUNTIME_ERROR. A normally returning unit task implicitly succeeds. Missing non-unit output becomes RUNTIME_ERROR with EINVAL. A task returning without an explicit outcome while cancellation is observed becomes CANCELLED. An explicitly set outcome is retained on normal return. An interrupted execution that never returns cannot publish its candidate as a successful result.

Terminal kind Payload Meaning
LLAM_OUTCOME_OK Success type, or null for unit Task produced its success result.
LLAM_OUTCOME_APP_ERROR Error type, or null for unit Application-level failure; not an errno failure of take.
LLAM_OUTCOME_CANCELLED Null Task observed cancellation before a result.
LLAM_OUTCOME_RUNTIME_ERROR Null; runtime_error populated Execution could not produce a valid application outcome.

A successful take returns zero for all four terminal kinds. EAGAIN means not ready; EINVAL includes type/size mismatch; EBUSY includes conflicting public consumption. These failures preserve future and output. Stale handles return EINVAL. A full V1 llam_outcome_t output is mandatory because a partial copy could lose an owned pointer. The expected contract validates both types. Success transfers the payload and consumes the future. Release the payload with llam_value_release after use. task_id is diagnostic, not a joinable handle.

Readiness follows entry return, task-local/owned-argument cleanup, backend/helper retirement, native execution retirement, and task admission release. A ready future can be taken by a host after both scope and runtime are destroyed. Managed access from a peer runtime fails with EXDEV. Scoped children cannot be joined or detached using ordinary task APIs (EBUSY).

Cancel and drain

llam_scope_cancelSeal admission and request private scope cancellation; idempotent.
int llam_scope_cancel(llam_scope_t *scope);

Seal admission and request cancellation; idempotent and scope-local.

llam_scope_get_report_exCopy the compatible report prefix without waiting or sealing.
int llam_scope_get_report_ex(llam_scope_t *scope,
                             llam_scope_report_t *out,
                             size_t out_size);

Seal admission and request cancellation; idempotent and scope-local.

llam_scope_drain_untilSeal admission and wait for complete quiescence using a cleanup deadline.
int llam_scope_drain_until(llam_scope_t *scope,
                           uint64_t cleanup_deadline_ns,
                           llam_scope_report_t *out,
                           size_t out_size);

Seal admission and wait for complete retirement. This cleanup wait ignores caller cancellation and its inherited request budget, but preserves both for subsequent operations. Only cleanup_deadline_ns bounds this wait; zero never waits and UINT64_MAX is unbounded. A timeout retains every outstanding resource. Runtime failure/stop can interrupt incomplete drain. A host needs an active driver for pending work (EBUSY/NEEDS_RUNNER); a scope child cannot drain itself (EDEADLK). Only one drainer is admitted. Reports are written after validation, including on wait failure. This API does not support borrowed lexical stacks.

llam_scope_cancel_and_drain_untilSeal, cancel and drain under one public operation.
int llam_scope_cancel_and_drain_until(llam_scope_t *scope,
                                      uint64_t cleanup_deadline_ns,
                                      llam_scope_report_t *out,
                                      size_t out_size);

Seal admission and wait for complete retirement. This cleanup wait ignores caller cancellation and its inherited request budget, but preserves both for subsequent operations. Only cleanup_deadline_ns bounds this wait; zero never waits and UINT64_MAX is unbounded. A timeout retains every outstanding resource. Runtime failure/stop can interrupt incomplete drain. A host needs an active driver for pending work (EBUSY/NEEDS_RUNNER); a scope child cannot drain itself (EDEADLK). Only one drainer is admitted. Reports are written after validation, including on wait failure. This API does not support borrowed lexical stacks.

llam_scope_destroyConsume a drained scope with no concurrent public operation.
int llam_scope_destroy(llam_scope_t *scope);

Consume a drained scope with no concurrent public operation. Ready futures and taken values remain owned independently; their callbacks must remain loaded.

The state moves from OPEN to CLOSING on drain or cancel, then to DRAINED when no pending tasks or active spawns remain.

A drain shields only the calling task's application cancellation and inherited request budget for the duration of the cleanup wait. Both remain effective after it returns. The explicit cleanup_deadline_ns stays effective; runtime failure or shutdown can still interrupt an incomplete drain. Managed callers park, allowing peer tasks to progress even with one worker.

Deadlines use absolute llam_now_ns() units: zero never waits; UINT64_MAX is unbounded. Already quiescent scopes succeed immediately. ETIMEDOUT leaves all outstanding ownership intact and the scope sealed; retry drain later. A timeout never permits freeing memory still used by I/O, a native frame, or a blocking callback. Cancellation requests do not forcibly unwind arbitrary foreign code.

Host drain never drives the scheduler. Pending work without an active runner returns EBUSY and sets LLAM_SCOPE_REPORT_F_NEEDS_RUNNER in that call's report (unless its deadline was already expired). Only one drainer is admitted. A child cannot drain its own scope (EDEADLK, without sealing or cancellation side effects).

The 72-byte report includes state, flags, admitted/pending task counts, active spawns, four terminal-kind counts and the first runtime error. QUIESCENT means all admitted execution has retired, including cleanup; it does not release ready future results retained by callers. CANCEL_REQUESTED records scope cancellation. Reports can be requested on wait failure; validation failures do not transfer any ownership. Destroy before quiescence or during another operation returns EBUSY.

ABI sizes and typed host binding

Use LLAM_TYPE_DESCRIPTOR_CURRENT_SIZE, LLAM_RESULT_CONTRACT_CURRENT_SIZE, LLAM_VALUE_SPEC_CURRENT_SIZE, LLAM_SCOPE_OPTS_CURRENT_SIZE, LLAM_TYPED_TASK_SPEC_CURRENT_SIZE, LLAM_OUTCOME_CURRENT_SIZE, and LLAM_SCOPE_REPORT_CURRENT_SIZE for the corresponding size argument. Initializers and ownership-bearing inputs/outputs require their complete V1 prefix, preserve unknown output tails, and ignore unknown input tails. Reports copy the available prefix. Future versions may append tails without changing V1 ownership fields.

<llam/future.hpp> provides optional C++17 host types llam::owned_value<T>, llam::future<T,E>, and llam::outcome<T,E> (default error type llam::unit). They are move-only. Specialize llam::type_id<T> with stable high/low members for custom types. owned_value<T>::adopt consumes a std::unique_ptr<T> only on success and calls delete once; T's destructor must satisfy the callback rules. future::spawn moves an owned argument only on successful admission; take requires an empty outcome destination. Methods return C-style status and errno.

Use reset() for reportable release failures. Destruction or move-assignment that must release an invalid/concurrently accessed/wrong-owner handle terminates instead of silently leaking. Keep wrapper operations in an allowed owner or host context and externally synchronize access. The wrapper does not grant C++ task code managed qualification or translate C++ exceptions into outcomes.

The complete C ownership example checks creation, run, take, cancellation and teardown failures using an explicit compatibility runtime. The installed SDK regression compiles tests/fixtures/managed/scoped_tasks.c through llam-clang, links scoped_consumer.cpp as a native C++ host, and checks the default asynchronous runtime plus typed take after scope/runtime teardown.

↑↓ Navigate↵ Openesc CloseSearching the 3.0.1 docs