> This page is for version 5.1 (Latest) (default).
> For other versions, use one of these documentation indexes:
> - 5.1 (Latest) (default): https://docs.nvidia.com/holoscan/sdk-user-guide/5-1-latest/llms.txt
> - ltsb-2.0: https://docs.nvidia.com/holoscan/sdk-user-guide/ltsb-2-0/llms.txt
> - 5.0: https://docs.nvidia.com/holoscan/sdk-user-guide/5-0/llms.txt
> - 4.6: https://docs.nvidia.com/holoscan/sdk-user-guide/4-6/llms.txt
> - 4.5: https://docs.nvidia.com/holoscan/sdk-user-guide/4-5/llms.txt
> - 4.4: https://docs.nvidia.com/holoscan/sdk-user-guide/4-4/llms.txt
> - 4.3: https://docs.nvidia.com/holoscan/sdk-user-guide/4-3/llms.txt
> - Archives: https://docs.nvidia.com/holoscan/sdk-user-guide/archives/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/holoscan/sdk-user-guide/llms.txt.

> **You will learn**
>
> * Split one input job into bounded synchronous compute turns.
> * Keep an owned image when publication is blocked and resume on capacity.
> * End a finite source and let accepted inputs and outputs drain naturally.

An acquisition can finish receiving input before its reconstruction finishes producing
images. Cooperative continuation lets one input start a job that emits 100 images over
several compute turns. Later inputs stay queued until that job completes.

| Application need                                    | Mechanism                                                     |
| --------------------------------------------------- | ------------------------------------------------------------- |
| Finish reconstruction after acquisition input ends  | One input owns a job across continuation turns.               |
| Publish more images than the output queue holds     | Retain an owning image and resume when capacity is available. |
| Restart after accepted reconstruction work finishes | Explicitly request a bounded drain before lifecycle restart.  |

This is an advanced, opt-in `holoscan.core` capability (C++ namespace `holoscan`,
Python convenience exports under `holoscan`). Ordinary operators still receive, compute,
emit, and return. They do not need continuation actions or explicit source EOS.
Continuation uses synchronous callbacks; each return gives Runtime an opportunity to
schedule other ready work.

Call `try_emit` only during an active `compute()` callback whose contract declares
`allow_continuation()`. Calling it from an ordinary operator callback returns
`ErrorCode::kInvalidArgument` in C++ and raises `holoscan.errors.InvalidArgumentError`
in Python, with `RUNTIME_CONTINUATION_NOT_ACTIVE`, the operator and output identities,
and a remedy. This is an invocation error, not a blocked attempt: no payload is accepted.
Use ordinary `emit` when continuation is not needed. Error text is best effort if
diagnostic allocation fails; the typed error remains available.

The operator-test harness's controlled-clock mode requires `OnClock`, which cannot
declare continuation. Its observed outputs reject `try_emit` with `kNotSupported`
and `RUNTIME_TRY_EMIT_UNSUPPORTED`; use ordinary `emit` in that mode. This restriction
is specific to controlled-clock observation. Ordinary fixture runs use the normal
Runtime continuation contract.

> **Note**
>
> Cooperative continuation, `try_emit`/`EmitAttempt`, and the restart-admission extension
> are **Prototype** APIs. Existing lifecycle control remains **Beta**. Prototype APIs may change
> in upcoming releases. The examples use one process
> with bounded, lossless direct routes. Separate partitions do not mean separate processes.
> Native authoring extensions must be rebuilt against this Core version: cooperative
> payload registration uses the versioned `AuthoringRegistryV6` ABI. Earlier
> unversioned, V2, V3, V4, and V5 registry symbols deliberately fail at link/load rather than
> reading incompatible payload rows.
> This registry fence is not a general binary-compatibility guarantee: `RegisteredPayloadType`
> and `OutputBindingOps<T>` also grew, and `LifecycleTransactionState` adds `kWaitingForDrain`,
> `kWithdrawn`, and `kDrainExpired` (update exhaustive switches). Rebuild all native authoring
> extensions against matching installed headers and Core; do not mix old inline tables or
> foreign payload descriptors with the new library.

## Run the two examples

The complete sources are `examples/cooperative_continuation/cpp/cooperative_continuation.cpp`
and `examples/cooperative_continuation/python/cooperative_continuation.py`. Both provide
`counter` and `images` modes, optionally with `--split` for a partition per operator.
The Python application uses NumPy and native Python operator bindings; it does not launch
a C++ executable or create a retry thread.

From the SDK source root, with the SDK Python package available:

```bash
python3 examples/cooperative_continuation/python/cooperative_continuation.py counter
python3 examples/cooperative_continuation/python/cooperative_continuation.py counter --split
python3 examples/cooperative_continuation/python/cooperative_continuation.py images
python3 examples/cooperative_continuation/python/cooperative_continuation.py images --split
```

Run the built C++ `cooperative_continuation` executable with the same arguments.
Both implementations wait up to five seconds for natural completion, join the session,
and verify completed termination with no diagnostics. Their timeout cleanup stops a
failed run; stopping is not their successful completion mechanism.

| Scenario       | Queue and payload                                          | Assertion                                                                         |
| -------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------- |
| Counter parity | 100-slot scalar route, enough for the entire finite stream | Exactly `0..99`, one startup seed and 99 continuation callbacks                   |
| Reconstruction | Two queued input records; depth-one host Tensor output     | All 100 images from the first job precede the second job's image, then EOS drains |

The counter deliberately isolates scheduling parity from backpressure. The image example
may need more callbacks than outputs because a blocked publication requires another turn.
Natural scheduling may also avoid rejection entirely; a successful example run does not
by itself prove that the blocked branch executed.

## One seed starts a finite counter

`Contract.allow_continuation()` enables the action protocol. A zero-input operator uses
`OnNotified` and explicitly requests `seed_on_run_start()`. No application notification
post is needed for that seed. This is the counter's actual contract:

```python
def contract(self):
    return (
        hs.Contract()
        .trigger(hs.OnNotified(self.ready))
        .allow_continuation()
        .seed_on_run_start()
    )
```

The following method is from the complete Python counter; setup declares `ready` and
`out`, and the graph gives `out` 100 queue slots:

```python
def compute(self, context):
    if context.activation_reason() is hs.WorkActivationReason.RUN_START_SEED:
        self.next_value = 0
    turns.append((context.tag(), context.origin_tag(), context.activation_reason()))
    # The 100-slot route holds the entire finite stream, so this example
    # measures the exact turn count independently of capacity retries.
    self.out.emit(self.next_value)
    self.next_value += 1
    if self.next_value < 100:
        context.request_continuation()
    else:
        context.request_source_end_of_stream()
```

Runtime seeds once after successful startup of each new RunSession. Failed startup
does not dispatch a seed, and lifecycle restart does not reseed. Initialize finite
source state on the seed, as above, rather than resetting it every time `start()` runs.
The example asserts 100 distinct activation tags and the same `origin_tag()` for all
turns. `WorkActivationReason.RUN_START_SEED` identifies the first turn;
`WorkActivationReason.CONTINUATION` identifies the remaining 99. The C++ enum members
are `WorkActivationReason::kRunStartSeed` and `WorkActivationReason::kContinuation`.

## A real input owns a multi-image job

The reconstruction graph is `EndOfInputRecords → Reconstruct → ImageSink`. The source
publishes counts `100` and `1` as real input records, then requests source EOS. Each
count represents a finished acquisition whose reconstruction still has images to produce.
These application end-of-input records are data; Runtime EOS is a separate ordered event.

`Reconstruct` uses `OnEach(self.inp)` and `allow_continuation()`. Only an `INPUT`
activation receives a new input and initializes the job. Continuations use the saved
job state without selecting another input. The bounded input queue holds the next record
while the first job is active. The source can finish while reconstruction is still working.

The complete example creates each image with
`hs.Tensor.as_tensor(np.full((8, 8), value, dtype=np.uint32))`. This is an owning Tensor
whose DLPack ownership keeps the NumPy allocation alive. The value encodes job and image
index; the sink checks the shape, dtype, and every pixel of all 101 outputs.

This is the publication portion of `Reconstruct.compute()`:

```python
if self.pending is None:
    # DLPack ownership keeps the NumPy allocation alive after this expression.
    self.pending = hs.Tensor.as_tensor(
        np.full((8, 8), self.job * 1000 + self.index, dtype=np.uint32)
    )
attempt = self.images.try_emit(self.pending)
if attempt.blocked:
    wait_token = attempt.wait_token
    assert wait_token is not None, "blocked publication has no wait token"
    blocked_attempts.append((self.job, self.index))
    context.request_continuation_when_writable(wait_token)
    return  # Keep the same owned Tensor and index for the next turn.
assert attempt.accepted
self.pending = None
self.index += 1
if self.index < self.count:
    context.request_continuation()
# No action completes this job. Upstream EOS still drains the queued job.
```

The C++ example constructs a `Tensor` from a `DLManagedTensorContext` whose
`memory_reference` owns the pixel vector. `std::optional<Tensor> pending_` retains that
allocation across turns. Its corresponding publication block is:

```cpp
if (!pending_)
  pending_.emplace(make_owned_image(job_ * 1000U + index_));
auto attempt = images.try_emit(*pending_);
if (!attempt)
  return make_unexpected(attempt.error());
if (attempt->blocked()) {
  const auto wait_token = attempt->wait_token();
  if (!wait_token)
    return make_unexpected(
        Error{ErrorCode::kProtocolError, "blocked publication has no wait token"});
  ++evidence_->capacity_waits;
  // Keep the same owned Tensor and index. This token belongs to this rejection.
  return context.request_continuation_when_writable(*wait_token);
}
pending_.reset();
++index_;
if (index_ < count_)
  return context.request_continuation();
return {};  // Completes this job; upstream EOS must still drain the queued job.
```

These snippets omit their enclosing class declarations; the files above contain all
declarations, graph construction, bounds, error handling, and completion assertions.

## Publication outcomes and ownership

| Outcome  | What to do                                                                                                                                    |
| -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Accepted | Release the pending owner and advance the job; request another turn if work remains.                                                          |
| Blocked  | No recipient accepted the value. Keep it, register the returned capacity token in this callback, and return.                                  |
| Error    | Propagate the typed error. Unsupported routes, allocation failure, and partial or uncertain publication are not retryable capacity rejection. |

Python `EmitAttempt` exposes `accepted`, `blocked`, and `wait_token`; accepted results
have no wait token. C++ `Output<T>::try_emit(const T&)` returns
`expected<EmitAttempt, Error>` with `accepted()`, `blocked()`, and `wait_token()`.
An attempt is not a boolean success shortcut.

The initial Tensor route accepts an owning Tensor on a supported fanout-one direct
output. CUDA and CUDA-managed Tensors must already carry a valid readiness contract;
`try_emit()` does not modify shared readiness metadata or perform implicit DLPack/loan
conversion. Missing readiness is a typed error before reservation or sequence/accounting
changes, never a blocked capacity result. Existing `emit()` behavior is unchanged.

The token identifies the rejected publication's capacity condition; it does not own
the image. Register it with `request_continuation_when_writable()` during its creating
callback. Runtime rechecks capacity during registration, so a release before registration
is not lost. A wake hint alone does not establish usable capacity.

> **Warning**
>
> Do not spin on `try_emit()`, request an immediate continuation after a blocked result,
> or save its token to register during a later callback. Keep the owning payload, not
> an ExecutionContext, selected-input facade, or callback-scoped loan. Shared Tensor
> ownership does not permit rewriting pixels while receivers still use them.

The example prints its observed capacity-wait count. Separate deterministic checks in
`tests/runtime/test_run_session_capacity.cpp` and
`python/tests/core/test_native_continuation_capacity.py` hold downstream capacity to
force rejection and verify the subsequent wake. Those checks supply forced-rejection
evidence that a naturally scheduled example cannot guarantee.

## Work completion, source EOS, and whole-run completion

With no scheduling action and no unresolved blocked publication, successful return
completes the current work item. `complete_work_item()` is an optional explicit form.
That allows the next queued input to start; it does not declare an input stream finished.

Runtime records blocked attempts even if the result is ignored. Returning without the
matching capacity registration, using a stale token, or substituting immediate
continuation/completion is misuse. At most one distinct action may be selected per
callback. Repeating an identical action coalesces. Actions commit only after successful
retirement; a failing callback does not commit an earlier continuation request.

> **Warning**
>
> The blocked-output guard cannot inspect unsent private application state. If image 0
> was accepted and the callback forgets to request a turn for images 1–99, there is no
> blocked obligation to diagnose. Successful return can complete that job. Exact output
> assertions are necessary to catch this application error.

`request_source_end_of_stream()` is explicit and applies to an opted-in zero-input
source. It seals new notification admission, settles already accepted requests and
outputs, and orders downstream EOS after data. The action also completes its current
work item; do not combine it with `complete_work_item()`. An inputful reconstruction
operator inherits upstream EOS and drains its current and queued jobs rather than
calling source EOS itself.

Source EOS does not stop unrelated sources. It is different from the whole-run
`request_completion()` operation, which the examples never call. Completing the
reconstruction job means its images were accepted; natural run completion also waits
for downstream processing and ordered EOS to settle.

## Fresh turns preserve original causality

`activation_reason()` identifies initial admission versus continuation. Each turn has
a fresh `tag()` and retains its original `origin_tag()`. Input capture time and freshness
evidence remain those of the original selection; a new tag does not make old input fresh.

With a 10 ms `max_start_delay` on comparable clocks, an input captured at 0 ms and
executed at 4 ms satisfies its initial capture-based check. A continuation runnable at
5 ms and executed at 8 ms has 3 ms runnable delay. If the next turn waits for capacity
until 150 ms and executes at 154 ms, its delay is 4 ms. Executing at 172 ms instead
exceeds the 10 ms obligation. Initial capacity waiting is not scheduler delay.

The first authoritative eligibility fixes the deadline for that pending turn. Losing
capacity and re-parking before dispatch does not reset the 150 ms reference. The suppressed
scheduling candidate retires; a later freeze reserves a fresh Tag and clamps its TagTime after
previous candidates while preserving the work origin and first-eligibility reference. A callback
that actually executes and then blocks creates a different future turn with a new
first-eligibility reference. Neither rule limits the duration of the entire image job.

## Restart policy and supported routes

Restart defaults to `LifecycleRestartAdmission.REJECT_IF_BUSY`: live continuation
obligations cause busy rejection, including the requesting callback's own live work.
A compute-side self request does not bypass this check: it returns
`LIFECYCLE_RESTART_WORK_BUSY` with the affected owner. Existing `request_restart()` calls
keep fail-fast behavior; ordinary requests outside continuation-affected closures are unchanged.
Use `request_restart_with_admission()` to select `DRAIN_THEN_RESTART` explicitly.
`LifecycleRestartAdmissionOptions` keeps the existing restart options in `restart`,
the policy in `admission`, and the timeout in `drain_timeout`. Python expresses the
timeout in seconds; C++ uses `std::chrono::nanoseconds`. Draining requires a finite,
strictly positive, representable duration. `REJECT_IF_BUSY` requires a zero timeout. Python
validates both constructor combinations; mutated Python options and C++ aggregates are checked
again at submission before any receipt or fence. An accepted compute-side `DRAIN_THEN_RESTART`
request enters only after the requesting callback retires and all accepted continuation work
finishes; it does not discard the current job. Successful requests and blocked `try_emit` results
allocate no diagnostic text. Rejections may allocate bounded contextual text and retain their
error code if diagnostic storage is exhausted.

This helper is from `python/tests/core/test_native_continuation_restart.py`:

```python
def admission_options(*, timeout=5.0, stage=hs.lifecycle.LifecycleStage.START):
    return hs.lifecycle.LifecycleRestartAdmissionOptions(
        restart=hs.lifecycle.LifecycleRestartOptions(from_stage=stage),
        admission=hs.lifecycle.LifecycleRestartAdmission.DRAIN_THEN_RESTART,
        drain_timeout=timeout,
    )
```

The graph must grant `graph.lifecycle().allow_external_restart(target)`, and the
session must have lifecycle transaction capacity. Obtain a control handle with
`session.lifecycle_control(policy)`, then call
`control.request_restart_with_admission(target, admission_options())`. The returned
receipt records admission, not completed restart. An active ExecutionContext also
provides self-target and authorized explicit-target overloads. Its contribution can
be withdrawn by the submitting operator in the same lifecycle epoch during a live
callback. Do not retain that callback-scoped context for later use. Keep external
submissions and their withdrawals on a session control handle.

Drain admission establishes a finite boundary around the affected operators' accepted
work. For the supported `source → image producer → terminal sink` route, an active
image job, queued image inputs, and an already admitted upstream source job can finish
under the old generation. Their continuations and downstream consumers remain runnable.
New jobs at the immediate upstream source wait outside that boundary. Notification
posts may still be accepted within that source's ordinary finite capacity; acceptance
does not mean the new job has started. Once restart publishes, those jobs can enter the
new generation. A later submission cannot silently extend the accepted prefix.

This support is limited to provable local, bounded, lossless, fanout-one direct routes
in one process, with a terminal downstream consumer and a zero-input immediate upstream
source for an inputful target. Same and separate partitions are supported. Arbitrary
feedback, transported routes, and broader dependency graphs are not implied by this
example. Unsupported drain routes reject before admission changes.

Queued drain excludes a restarted or affected operator, or its immediate upstream
source, that owns RuntimePool Tensor or TensorSchema allocations. An unpublished pool
loan can remain live after its callback; this release rejects that route with
`RUNTIME_QUEUED_RESTART_TENSOR_POOL_UNSUPPORTED` before installing a cut or issuing a
receipt. Owning pass-through host Tensor routes remain supported, and pools outside
the affected boundary do not cause rejection. Ordinary restart keeps its existing
pool lifetime rules.

`control.inspect_restart(receipt)` returns a `LifecycleRestartAdmissionView`.
Its `receipt_view` contains the existing receipt state and transaction lineage;
`effective_deadline_ns` is an optional, opaque same-process steady-clock coordinate.
It is not a wall-clock timestamp, and no Python clock epoch is implied.
`WAITING_FOR_DRAIN` means the prefix is still settling, before lifecycle restart entry.
Successful restart ultimately reports `PUBLISHED` through the existing receipt view.

Exact duplicate requests receive separate receipts but share one execution, accepted
prefix, and immutable deadline. A second submission at 4 seconds cannot extend an
original five-second deadline to 9 seconds. Equivalence includes lifecycle epoch,
profile, scope, restart effect, drain policy, and the requested drain timeout; an incompatible request rejects
instead of changing the queued restart or creating an automatic successor.

Call `control.withdraw_restart(receipt)` to withdraw that handle authority's own
contribution before restart entry. Copies delegate the same authority; independently
minted or restricted handles cannot withdraw it. One withdrawal reports `WITHDRAWN`
for that receipt while other contributors remain active. The last withdrawal releases
the admission restriction. Runs without queued-drain withdrawal support retain
`kNotSupported`; existing availability checks take precedence over receipt checks.
Once withdrawal support is available, an ordinary restart receipt is rejected with
`kInvalidArgument` (`InvalidArgumentError` in Python). A receipt with the current plan
and run identity whose remaining identity fields are unknown or tampered is rejected
with `kNotFound` (`NotFoundError` in Python); a receipt
from another plan or run retains `kCrossSessionOperatorRef`. These classifications
apply to withdrawal; inspection and waiting keep their existing receipt-error contract.
Repeating withdrawal with the same authority for a contribution that already terminated
before restart entry succeeds without changing its terminal disposition. Identity,
authority, availability, and already-entered checks still apply. Passive inspection does
not drive expiry; an observed past deadline does not by itself mean the returned state
has advanced to `DRAIN_EXPIRED`.
Dropping a handle does not withdraw. Finite drain expiry
reports `DRAIN_EXPIRED`, releases the restriction, and prevents late restart entry;
the old generation can continue. A passive `await_terminal()` timeout only ends the
caller's wait. Withdrawal and expiry do not undo an entered restart or preempt a
callback or GPU operation.

Queued restart does not freeze all Parameters at request time. Independently admissible
`NextCompute` updates remain available; a plain restart pins the current published
Parameters at lifecycle callback entry. Duplicate identity therefore does not include
a complete request-time Parameter snapshot. An update requiring an overlapping lifecycle
transaction rejects: it cannot merge into, override, or defer a hidden restart behind
the queued request. A work item that needs application state fixed across continuation
turns must retain that state itself.

Lifecycle restart never repeats the run-start seed. It also cannot reopen committed
source EOS: a conflicting drain request rejects before restart entry, and withdrawal
or expiry does not undo the seal. The finite examples above deliberately finish through
EOS rather than exercising restart. The public restart tests illustrate the separate
admission protocol; their presence alone is not a qualification claim.

The example routes are fanout-one, lossless, bounded direct routes in one process.
Cooperative publication is not a general fallback for transported/interprocess routes,
forced HoloMQ routes, lossy delivery, or unsupported fanout. Tensor allocation failure
is not output-queue backpressure. CUDA-graph captured members cannot use this callback
action protocol. Ordinary non-continuation operators keep their existing behavior.
Continuation also cannot be combined with `complete_after(ComputeCalls)`; a callback
count does not express remaining job work.

## Recap

One input starts one active job. Publish bounded work, request another turn when more
remains, and retain an owned value plus register its matching capacity condition when
blocked. Explicit source EOS lets current jobs, queued inputs, and downstream outputs
finish naturally. The counter checks exact turn parity; the image pipeline checks
ordered, owned payload delivery through a depth-one route.

## Current limits

Python and foreign POD and generated-schema values support ordinary Python publication and C++
`try_emit`. Python `try_emit` currently rejects these payload kinds with
`PYTHON_TRY_EMIT_PAYLOAD_UNSUPPORTED` without consuming the value. Scalar, Python object and
owning-Tensor attempts retain their documented support. Declaring a POD/schema port is not an error.

There is no public plan or handle query for drain capability, or authored drain-permission API.
Request-time failures name the unsupported route. Cost in mixed continuation and ordinary
partitions has not been separately characterized; ordinary no-continuation measurements do not
establish that scaling cost. Python payload parity, drain-capability inspection, and mixed-partition
cost characterization remain planned extensions.