Skip to content

feat(token-capture): low-overhead metrics for capture operations, outcomes, digests, and caches - #4218

Open
ananthsub wants to merge 2 commits into
mainfrom
ananthsub/token-capture-telemetry
Open

ananthsub wants to merge 2 commits into
mainfrom
ananthsub/token-capture-telemetry

Conversation

@ananthsub

@ananthsub ananthsub commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Training-token capture runs on every captured model call, yet it emits no OpenTelemetry. In aggregate across a run there is no way to see where its time goes, how often calls are poisoned or masked, how much hashing it repeats, or how large its caches grow. Performance work such as #4213 has to be measured with an external harness, and a regression in it would go unnoticed.

This PR adds a small set of token-capture metrics next to Gym's other attributed metrics, built so they cannot hurt training throughput.

Metric Type Attributes What it answers
gym.token_capture.operation.duration_ms Histogram, buckets roughly doubling from 0.01 ms to 300 s operation, implementing class, token size class (lt_4k, lt_32k, lt_128k, ge_128k; absent without a record), error (error or cancelled, only when the operation did not complete) Where capture time goes, per implementation and sequence length; slow failures
gym.token_capture.operation.tokens_total Counter operation Duration sum per token, so a slower implementation is not confused with longer sequences
gym.token_capture.outcome_total Observable counter outcome, reason from a fixed set Parent resolution, poisoned calls, capture failures, late writes dropped, stale retirements, lock acquisitions, each with a reason from a fixed set
gym.token_capture.digest.calls_total, .bytes_total Observable counters digest kind Duplicated and repeated hashing
gym.token_capture.cache.size Observable up-down counter, read at export cache Lineage, ledger, and index cache sizes per process

Operations timed:

  • At protocol call sites (TokenSink, TokenSource, LineageResolver, CaptureLedger, StagingSink): lineage.resolve, sink.begin_call, sink.put, ledger.record, ledger.record_failure, staging.build_record, staging_sink.stage, source.freeze, source.drop, the control routes' and checkpoint retirement's ledger.manifest, ledger.retire, and ledger.delete, and, when a training framework selects the parent call, ledger.manifest and ledger.begin_call at admission. Each is labelled with the implementing class, so framework-provided implementations (for example NeMo RL's staging sink and source) are measured without changes to them. These timings include waiting for a worker thread.
  • At a checkpoint backend's cut builders: cut.build_prefix_record and cut.build_chunk_record. Ordinary staging goes through the private builder and is timed only as staging.build_record.
  • Inside Gym's file stores: sink.put.in_thread, ledger.record.in_thread, ledger.record_failure.in_thread, ledger.manifest.in_thread, ledger.retire.in_thread, and ledger.delete.in_thread, named after the call-site operation they pair with (the difference is thread-pool queueing), and file_lock.wait only when acquiring the lock took at least 0.1 ms, labelled with the store that waited (a ledger sharing the token store's lock file reports as the ledger).

Operations are named <role>.<method> after the protocol they time. Outcomes reuse the names the capture code already uses, each with a reason from a fixed set:

  • parent_root, parent_resolved (tool_call_turn when matched on the turn's tool calls), and parent_unresolved (the resolver's reason).
  • poisoned, with the ledger failure reason. Gym's ledgers count it when they write the failure row, so a replayed row or one dropped for a retired rollout is not counted.
  • capture_failed: write or build on the model server; build, staging_sink_error, or staging_sink_rejected on the inference worker, matching the worker's capture_failed disposition.
  • late_write_dropped: frozen, or retired when the token store or a ledger refused a write for a retired rollout. A dropped ledger row leaves staged tokens no manifest names.
  • marked_incomplete: no reason after a capture failure, unclassified_request for a request the model server could not classify.
  • retire_skipped: why the source refused the drop, stale_snapshot or not_frozen, from sources that implement the optional drop_with_reason extension (Gym's token store does). Other sources are counted with no reason.
  • lock_acquired: shared or exclusive.

gym.token_capture.operation.tokens_total carries the operation and the implementation, so milliseconds per token can be compared per implementation. The call sites reach the instruments through nemo_gym.models.token_capture.capture_metrics; the name avoids the per-rollout metrics dictionaries this package already uses.

Every ledger poisoning site, including the engine-refusal and uncommitted-call sites on main, now goes through one record_ledger_failure helper in models/token_capture/sink.py, which times the write; the ledger counts the row it writes.

Docs: the metrics table and a "Token-Capture Metrics" section in observability/metrics.mdx.

How it works

flowchart LR
  A["Agent"] --> M["Policy model server<br/>lineage.resolve, sink.put,<br/>ledger.record, ledger.record_failure"]
  M --> W["Inference worker<br/>staging.build_record, staging_sink.stage,<br/>digest counts"]
  C["Consumer<br/>source.freeze, source.drop"] --> F
  M --> F[("Capture files and caches<br/>sink.put.in_thread, ledger.record.in_thread,<br/>ledger.manifest.in_thread, file_lock.wait, cache.size")]
  W --> T[("Framework token store")]
  M -. "OTLP" .-> O["Per-job collector<br/>to the dashboard backend"]
  W -. "OTLP" .-> O
  C -. "OTLP" .-> O
Loading

Keeping it off the critical path:

  • With no metrics exporter, a capture site checks one attribute and gets a shared no-op timer back. The capture package does not import nemo_gym.telemetry until a process has set telemetry up, so importing capture code stays cheap and the package stays a leaf.
  • Outcome and digest counts fire far more often than operations, so they are integer increments in process memory, read by observable instruments at each export. Capture runs on many worker threads, so the increments take a lock (uncontended, about 0.1 µs); a dict read-modify-write would otherwise lose counts even with the global interpreter lock.
  • Every in-process structure is bounded. Instruments and attribute sets are created once; attribute sets are capped per instrument (512) and outcome keys at 256, with new outcomes and reasons beyond that counted under other. Implementation labels are read from the class on each call, so no reference to a class is kept. Cache owners are held weakly, and one owner failing to report does not hide the others.
  • Successful operations carry no outcome or error label, which keeps the histogram's series count down; failures and cancellations get error.
  • An operation slower than 5 s also logs one warning per operation per minute, which survives a crash that loses the last metric export.

Measured per call on a workstation:

Site Metrics off Metrics on
Timed operation 164 ns 5.1 µs
Lock acquisition below the threshold 163 ns 0.4 µs
Outcome or digest count 66 ns 0.2 µs

A captured model call records about 5 to 10 measurements, well under 0.1 ms against model calls of 100 ms or more.

Measuring #4213 with these metrics

As a check that the metrics show real optimizations, #4213's parent (ba18d3dae) and #4213 (b2fde6b54) were each run with this commit applied, plus timing of #4213's checkpoint-cut builders and prefix cache, on a synthetic workload: 24 calls with 2,048 to 65,536 prompt tokens, six checkpoint cuts each, then a completion, three repetitions. Every number came from these instruments through an in-memory reader.

Measure #4213's own report These metrics
Record build, full rebuild 58.21 → 20.85 ms 57.0 → 20.5 ms
Prefix cache init / extend 13.55 / 1.80 ms 6.1 / 0.69 ms
Staging digests per record 2 → 1 2.00 → 1.00
p95 of record build, 32k to 128k tokens (histogram bucket) — 256 → 128 ms; 64 ms with the prefix cache
Bytes hashed still grows with the full sequence 157 → 78 MB; 89 MB with the cache

#4213 has since landed, and the tests now assert one staging digest per record, the behavior on main. They also show that a staged record still computes its extras digest twice, once in the builder and once in the record's validator.

What callers and operators should know

  • Nothing changes unless a metrics exporter is configured: recording is off by default, like the rest of Gym's telemetry. A traces-only process records nothing.
  • A process records these metrics whenever it has an OpenTelemetry metrics provider, whoever set it up. A training framework's inference worker, which runs Gym's staging capture code, records through the provider the framework installed, such as NeMo RL's nemo-lens worker setup, with no call into Gym. The check imports nothing from OpenTelemetry and adds no cost until the metrics SDK is loaded.
  • Diagnosing a manifest-fetch timeout: ledger.manifest minus ledger.manifest.in_thread is time waiting for a worker thread, file_lock.wait is time waiting for the ledger lock, and the rest of the in-thread time is the read. The framework-side wait for a pooled connection is gym.http.connection_pool.queue_duration_ms, already on main.
  • Gym's uvicorn workers export separately. Sum per-process series (cache sizes, counters) by server in dashboards.
  • New dashboard panels are not part of this PR: p50/p95/p99 by operation and size class, call-site versus in-thread time, outcome rates, digest bytes per record, cache sizes by server.

Compatibility

  • New public helper nemo_gym.models.token_capture.sink.record_ledger_failure; the internal ledger poisoning sites call it.
  • TokenCaptureStore.append and FileLineageStore._record now delegate to _append and _record_row; behavior is unchanged.
  • New optional TokenSource extension drop_with_reason(rollout_id, *, snapshot_id, version) -> tuple[bool, str], which TokenCaptureStore implements and drop delegates to. It is opt-in: a source without it keeps working and its refusals are counted with no reason. A TokenCaptureStore subclass that overrides drop must also override drop_with_reason, as its docstring says.
  • RolloutTokenCapture.build_prefix_record and build_generation_chunk_record keep their public keyword-only signatures and docstrings; they now time themselves as checkpoint cuts.
  • TokenCaptureStore._locked takes an optional waiter for the lock-wait label.
  • No configuration or wire format changes.

Issue

No tracking issue. Motivated by the need to measure token-capture performance work such as #4213 in aggregate.

Validation

Rebased onto main at f49b582a10, after the capture package moved to nemo_gym/models/token_capture/ and rollout ids became capture keys. The four reviewed commits are squashed into one, because every one of them touched the call sites the move rewrote. The imports use the new paths, not the deprecation shim. Ledger poisoning sites added on main since the PR opened go through record_ledger_failure: engine refusals in sink.py, and uncommitted calls in model_call_capture.py, which replaced the old base_responses_api_model.py site. Framework-owned admission, also new on main, times its ledger manifest read and its call-intent write.

The tests run against a real OpenTelemetry in-memory metric reader, and each capture method is exercised end to end for every metric family:

  • Token capture (Gym's own path). Two calls of one rollout and a third rollout whose response carries no token ids go through intent registration, parent resolution, and the token write against the file store. The consumer then freezes the rollout, a late write arrives after the freeze, and the rollout is retired twice: once with a snapshot identity the store no longer holds, once for real.
    • Operations: exact sample counts for the intent write, the one store lookup (root requests skip it), the call-site and in-thread write times, the refused late write labelled as an error, freeze, and both drops. Token totals match the written records.
    • Outcomes: one root per rollout, the resolved continuation, the dropped late write, the incomplete rollout, the stale-snapshot retirement, and lock acquisitions. No poisoned calls, since this path writes no ledger.
    • Digests: none, since this path identifies calls by fingerprint.
    • Caches: the lineage cache holds one rollout materialized through its parent's five tokens, and the ledger cache is empty.
    • A contended store lock records one file_lock.wait sample of the hold's length in milliseconds.
    • A rollout whose harness already returned token ids is still frozen for later retirement, and that freeze is timed.
  • External staging (the inference worker stages records and the model server writes ledger rows). A worker capture stages one record and fails to build a second one. The model server's capture handler commits the first acknowledgement to a file ledger and poisons the second.
    • Operations: exact counts for record build (successful, and failed as an error), prefix-record build, sink stage, the ledger write at the call site and in its thread, and the failure row. Token totals match the record.
    • Outcomes: the build failure and the poisoned call with the worker's failure reason. Nothing is marked incomplete, since this path has no local token sink.
    • Digests: exact call counts per kind and exact cumulative and chain byte counts. One staged record computes its extras digest twice, once in the builder and once in the record's validator.
    • Caches: the ledger cache holds the rollout, and no token lineage is materialized.
    • Framework-owned admission records one ledger manifest read at the call site and in its thread, and one call-intent write.
    • A contended ledger lock records one file_lock.wait sample.
  • The existing tests cover the rest: control-route timings, cancellation, attribute and outcome caps, concurrent counts, a failing cache owner, the slow-operation warning, recording through a framework's own meter provider, nothing recorded without an exporter, imports staying off the telemetry stack, and the cost of a disabled site.

Each new test fails on the code without this PR. On main the test module does not import. With only the two metric modules added to main's capture code, every new end-to-end test fails on its first missing measurement. The redundant-freeze test fails without its timer.

Fixed in this round:

  • Cache owners are registered and copied under a lock. Without it, a store built on a capture thread while the export thread copied the owner set raised inside the cache callback, and that export reported no cache sizes. A test that builds stores while exporting lost the cache metric in 17 to 32 of 300 exports in every run without the lock, and in none with it.
  • The test fixture binds the in-process totals itself, as the first captured call does in a server. Before, the cache-owner test passed only when an earlier test had bound them.
  • The test reset forgets cache owners. Before, stores still alive from earlier tests in the same worker added their sizes.
  • The source.freeze on the path for a rollout that already carries token ids is timed like the main path.

Commands, in one venv for this worktree synced with the full-suite extras (nemo-lens and the OpenTelemetry SDK installed, so the gated telemetry code runs and the lens tests do not skip):

uv sync --extra dev --extra ray --extra sandbox --extra openshell --extra telemetry --extra mlflow --extra wandb
uv pip install pytest-xdist pytest-timeout
pytest -o addopts="" -q tests/unit_tests/telemetry/test_token_capture_metrics.py
pytest -o addopts="" -q -n 4 tests/unit_tests/telemetry/test_token_capture_metrics.py
pytest -o addopts="" -q -n 16 -rs tests/unit_tests
pre-commit run --files <changed files>

Results:

  • The token-capture metrics module passed serially, under four workers, and with each test run on its own.
  • The full unit suite passed except for host-specific failures that fail identically on main at f49b582a10 with this branch's tests: the harbor run-summary tests, the Docker PTY pid-record tests (no user namespaces here), and the benchmark listing (the host name resolves to 127.0.1.1).
  • No telemetry, capture, or checkpoint test skipped.
  • pre-commit run on the changed files passed, including the import-linter layering check.
  • Commits are signed off and signed.

Team review round

A team review of the rebased commit found eleven issues and three follow-ups, all fixed in the second commit:

  • Gym's own tool_call_turn parent resolution was counted as other.
  • Late ledger rows for retired rollouts were not counted, and a dropped or replayed failure row still counted as poisoned.
  • A write the token store refused after retirement was counted as frozen.
  • Every staged record was also timed as a checkpoint cut.
  • The unclassified-request incomplete mark was not counted.
  • The checkpoint ledger retire and the file ledger's failure write were untimed.
  • retire_skipped called every refused drop a stale snapshot (now the opt-in extension above).
  • Token totals could not be split by implementation.
  • The lineage index could raise while being summed at export, dropping that store's sizes.
  • Ledger and lineage lock waits were labelled with the token store.
  • The docs disagreed with the code.

Each fix has a test that fails on the first commit and passes on the second. Five mutations that the first commit's tests let through, such as the size-class bound and the slow-operation threshold, now fail a test. The reviewer re-ran its mutations of the fixes against the second commit, and every one failed a test.

A note on one existing test: the disabled-site cost test compares two timings in one process. On this host it failed once in six runs under six test workers while other sessions held the load average near 90, and it passes alone under the same load.

Rollout evidence

N/A: the metrics are off unless an exporter is configured and do not change capture behavior. The synthetic #4213 measurement above exercises the instrumented paths end to end through the OpenTelemetry SDK.

@copy-pr-bot

copy-pr-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@ananthsub
ananthsub force-pushed the ananthsub/token-capture-telemetry branch from 9a32a09 to e8d7525 Compare October 8, 2026 16:41
@ananthsub
ananthsub marked this pull request as ready for review October 8, 2026 16:48
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 8, 2026 16:48
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

@copy-pr-bot

copy-pr-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ananthsub

Copy link
Copy Markdown
Contributor Author

/ok to test 8d65063

@ananthsub
ananthsub force-pushed the ananthsub/token-capture-telemetry branch from 8d65063 to 6a2b334 Compare October 8, 2026 18:07
@yaoyu-33 yaoyu-33 added area:core Shared APIs, servers, telemetry, health, and registries complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 8, 2026
…comes, digests, and caches

Time token-capture operations at protocol call sites and inside Gym's file
stores, count capture outcomes and digest work in process memory, and report
cache sizes at export. Recording is off unless a metrics provider exists.

Rebased onto main after the package moved to nemo_gym.models.token_capture
and rollout ids became capture keys. The ledger failure sites added on main
(engine refusals, uncommitted calls in model-call capture) go through
record_ledger_failure, and framework-owned admission times its ledger
manifest read and call-intent write.

Cache owners are registered and copied under a lock, so a store built on a
capture thread during an export no longer blanks the cache metric for that
export.

Squashes the four reviewed commits:
- feat(token-capture): low-overhead metrics for capture operations, outcomes, digests, and caches
- refactor(token-capture): align metric names with the capture vocabulary
- feat(token-capture): time manifest, retire, and delete, and address review
- fix(token-capture): record through any meter provider in the process

Signed-off-by: Ananth Subramaniam <[email protected]>
…e the remaining sites

Address the team review of the token-capture metrics:

- Count Gym's own tool_call_turn resolution reason instead of folding it
  into "other".
- Count writes refused for a retired rollout, by the token store or a
  ledger, as late_write_dropped/retired, and count poisoned where Gym's
  ledgers write the failure row, so replays and dropped rows are not counted.
- Add an optional TokenSource.drop_with_reason extension, implemented by the
  token store, so retire_skipped says stale_snapshot or not_frozen; sources
  without it are counted with no reason.
- Stage records through the private builder, so ordinary staging is no
  longer also timed as a checkpoint cut, and restore the public builders'
  signatures and docstrings.
- Count the unclassified-request incomplete mark, and time the checkpoint
  ledger retire and the file ledger's in-thread failure write.
- Label ledger and lineage lock waits with the store that waited, add the implementation to the
  token totals, and copy the lineage index before summing it at export.
- Bring the metrics docs and module docstring in line with the code.

Signed-off-by: Ananth Subramaniam <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 950838be Deployed Nov 10, 2026 by copy-pr-bot[bot] via release / finalize / notify #11240
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants