> This page is for NeMo Relay, version v1.0.0.
> For other versions, use one of these documentation indexes:
> - Latest (v0.11.2) (default): https://docs.nvidia.com/nemo/relay/latest/llms.txt
> - dev: https://docs.nvidia.com/nemo/relay/dev/llms.txt
> - v1.0.0: https://docs.nvidia.com/nemo/relay/v1.0.0/llms.txt
> - v0.11.2: https://docs.nvidia.com/nemo/relay/v0.11.2/llms.txt
> - v0.10.4: https://docs.nvidia.com/nemo/relay/v0.10.4/llms.txt
> - v0.9.4: https://docs.nvidia.com/nemo/relay/v0.9.4/llms.txt
> - v0.8.4: https://docs.nvidia.com/nemo/relay/v0.8.4/llms.txt

> For clean Markdown of any page, append .md to the page URL. For a task-oriented documentation index, fetch https://docs.nvidia.com/nemo/relay/llms.txt. Use the documentation version matching the installed NeMo Relay package: latest follows the latest stable release, vX.Y.Z identifies a retained release snapshot, and dev documents development changes. Preserve the selected version when following links; do not mix examples or API contracts from different versions. Fetch the relevant section's /llms.txt before individual pages instead of loading a complete version index.

# Adding Scopes and Marks

> Group instrumented calls under a request or agent run and add optional checkpoint events.

Use this guide to group related tool and LLM calls under one agent run, request,
workflow, or operation, and to add optional checkpoint events.

The basic scope setup is included in [Instrument a Tool Call](/nemo/relay/v1.0.0/instrument-applications/instrument-tool-call)
and [Instrument an LLM Call](/nemo/relay/v1.0.0/instrument-applications/instrument-llm-call).
Start with one of those Execute examples, then return here when you need more
control over grouping or checkpoints.

## What You Build

You will group one agent run in a scope, emit two checkpoint marks, and verify
the events received by a subscriber.

A **scope** groups related work, such as an agent run, request, or workflow step.
Tool calls, LLM calls, and marks attach to scopes so Relay can show which work
belongs together.

A **mark** records a named checkpoint within that work, such as “plan created” or
“retry scheduled.” It represents a single moment and can include data describing
what happened.

#### Prepare

Complete one binding Quick Start guide first:

* [Python Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/python)
* [Node.js Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/nodejs)
* [Rust Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/rust)

Choose the work you want to group. Common examples include:

* One HTTP request
* One agent run
* One workflow step
* One background job
* One tenant-isolated experiment

#### Instrument

Register a temporary subscriber, then enter the scope before tool and LLM work
begins. Emit marks for important checkpoints that do not wrap a callback, and
close the scope when the agent run, request, or workflow ends. The highlighted
lines below show the scope and mark calls in each binding.

#### Run

Run the complete example for your binding in the project from its Quick Start.
Each example creates one `agent-run` scope, emits two marks, and prints the
received events before removing the temporary subscriber.

#### Python

Save the following code as `scopes_and_marks.py` in your Quick Start project:

```python title={"scopes_and_marks.py"} maxLines={0} highlight={[16, 21, 22]}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import nemo_relay


def main() -> None:
    """Emit two checkpoint marks within an agent scope."""

    def log_event(event: nemo_relay.Event) -> None:
        print(f"{event.kind} {event.name}")

    nemo_relay.subscribers.register("scope-check", log_event)

    try:
        with nemo_relay.scope.scope(
            "agent-run",
            nemo_relay.ScopeType.Agent,
            input={"request_id": "req-123"},
        ) as handle:
            nemo_relay.scope.event("planning-started", handle=handle, data={"step": 1})
            nemo_relay.scope.event("planning-finished", handle=handle, data={"step": 2})
    finally:
        nemo_relay.subscribers.flush()
        nemo_relay.subscribers.deregister("scope-check")


if __name__ == "__main__":
    main()

```

API references: [`nemo_relay.scope.scope`](/nemo/relay/v1.0.0/reference/api/python-library-reference/nemo-relay/scope#scope) and [`nemo_relay.scope.event`](/nemo/relay/v1.0.0/reference/api/python-library-reference/nemo-relay/scope#event).

Run it from the project directory:

```bash
uv run python scopes_and_marks.py
```

#### Node.js

Save the following code as `scopes-and-marks.cjs` in your Quick Start project:

```js title={"scopes-and-marks.cjs"} maxLines={0} highlight={[19, 23, 24]}
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const {
  ScopeType,
  deregisterSubscriber,
  event,
  registerSubscriber,
  flushSubscribers,
  withScope,
} = require('nemo-relay-node');

async function main() {
  registerSubscriber('scope-check', (runtimeEvent) => {
    console.log(`${runtimeEvent.kind} ${runtimeEvent.name}`);
  });

  try {
    await withScope(
      'agent-run',
      ScopeType.Agent,
      async (handle) => {
        event('planning-started', handle, { step: 1 }, null);
        event('planning-finished', handle, { step: 2 }, null);
      },
      null,
      null,
      null,
      null,
      { request_id: 'req-123' },
    );
  } finally {
    await flushSubscribers();
    deregisterSubscriber('scope-check');
  }
}

module.exports = { main };

if (require.main === module) {
  main().catch((error) => {
    console.error(error);
    process.exitCode = 1;
  });
}

```

API references: [`withScope`](/nemo/relay/v1.0.0/reference/api/nodejs-library-reference/nemo-relay-node#withscope) and [`event`](/nemo/relay/v1.0.0/reference/api/nodejs-library-reference/nemo-relay-node#event).

Run it from the project directory:

```bash
node scopes-and-marks.cjs
```

#### Rust

Use the following code as `src/main.rs` in your Quick Start project:

```rust title={"src/main.rs"} maxLines={0} highlight={[19, 28, 35, 43]}
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use nemo_relay::scope::{
    self, EmitMarkEventParams, PopScopeParams, PushScopeParams, ScopeAttributes, ScopeType,
};
use nemo_relay::subscriber::{deregister_subscriber, flush_subscribers, register_subscriber};
use serde_json::json;
use std::sync::Arc;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    register_subscriber(
        "scope-check",
        Arc::new(|event| {
            println!("{} {}", event.kind(), event.name());
        }),
    )?;

    let handle = scope::push_scope(
        PushScopeParams::builder()
            .name("agent-run")
            .scope_type(ScopeType::Agent)
            .attributes(ScopeAttributes::empty())
            .input(json!({"request_id": "req-123"}))
            .build(),
    )?;

    scope::event(
        EmitMarkEventParams::builder()
            .name("planning-started")
            .parent(&handle)
            .data(json!({"step": 1}))
            .build(),
    )?;
    scope::event(
        EmitMarkEventParams::builder()
            .name("planning-finished")
            .parent(&handle)
            .data(json!({"step": 2}))
            .build(),
    )?;

    scope::pop_scope(PopScopeParams::builder().handle_uuid(&handle.uuid).build())?;
    flush_subscribers()?;
    let _ = deregister_subscriber("scope-check")?;
    Ok(())
}

```

API references: [`push_scope`](/nemo/relay/v1.0.0/reference/api/rust-library-reference/nemo-relay/scope/fn-push-scope), [`event`](/nemo/relay/v1.0.0/reference/api/rust-library-reference/nemo-relay/scope/fn-event), and [`pop_scope`](/nemo/relay/v1.0.0/reference/api/rust-library-reference/nemo-relay/scope/fn-pop-scope).

Run it from the project directory containing `Cargo.toml`:

```bash
cargo run
```

#### Verify

Running the example prints:

**`Expected output`**

```text title="Expected output"
scope agent-run
mark planning-started
mark planning-finished
scope agent-run
```

The two `scope agent-run` lines are the start and end of the same scope.
The named marks are checkpoints within it.

Check that the subscriber prints:

* One scope start event for `agent-run`
* One mark event for `planning-started`
* One mark event for `planning-finished`
* One scope end event for `agent-run`

> **Flush Subscriber Delivery**
>
> The examples flush subscriber delivery before removing the temporary subscriber.
> Keep this cleanup so queued events are delivered before the program exits. If a
> subscriber callback emits another event, flush again before checking the output.

If marks appear outside the intended trace, pass the active scope handle explicitly or make sure the mark is emitted while the scope is active.

## When to Add Marks

Use marks for checkpoints that should appear in the event stream but do not wrap a callback:

* Request accepted
* Plan created
* Memory loaded
* Routing decision made
* Final answer assembled
* Retry scheduled

Use a nested scope instead of a mark when the work has a meaningful start and end boundary, child work, or a duration that matters.

## Emit Typed Marks and Metrics

The generic mark API can attach a `data_schema` describing the opaque `data`
payload and a typed log `severity`. In Python, pass `data_schema=` and
`severity=` to `scope.event`; in Node.js, pass `dataSchema` and `severity` as
the final `event` arguments; and in Rust, set `data_schema` and `severity` on
`EmitMarkEventParams`. These options let OTLP log export preserve the schema
and severity without requiring application-defined metadata keys.

Use the binding's metric helper for a validated metric group: `scope::metric()`
in Rust, `scope.metric()` in Python, or `metric()` in Node.js. See
[Emit Log and Metric Marks](/nemo/relay/v1.0.0/configure-plugins/observability/opentelemetry#emit-log-and-metric-marks)
for the metric measurement shape and routing rules.

## Production Checklist

Use this checklist before running the pattern in production traffic.

* Keep scope names stable enough for filtering and dashboards.
* Use marks for business checkpoints, not verbose debug logging.
* Include only JSON-compatible `data`, `metadata`, `input`, and `output` payloads.
* Do not attach sensitive payloads unless a mark or scope
  [event sanitizer](/nemo/relay/v1.0.0/reference/event-sanitizers) removes them before subscriber
  and exporter delivery.
* Propagate the active scope stack when work crosses thread or worker boundaries.

## Next Steps

Use these links to continue from this workflow into the next related task.

* Add tool instrumentation with [Instrument a Tool Call](/nemo/relay/v1.0.0/instrument-applications/instrument-tool-call).
* Add model-provider instrumentation with [Instrument an LLM Call](/nemo/relay/v1.0.0/instrument-applications/instrument-llm-call).
* Export severity-tagged marks and metric measurements with
  [OpenTelemetry](/nemo/relay/v1.0.0/configure-plugins/observability/opentelemetry#emit-log-and-metric-marks).
* Use [Code Examples](/nemo/relay/v1.0.0/instrument-applications/code-examples#scope-and-context-helpers) for explicit scope-stack propagation helpers.