Skip to content

feat(observability): correlate OpenCode calls with invocations - #2884

Merged
giuliolovisotto merged 4 commits into
mainfrom
glovisotto/opencode-call-ownership
Sep 10, 2026
Merged

giuliolovisotto merged 4 commits into
mainfrom
glovisotto/opencode-call-ownership

Conversation

@giuliolovisotto

@giuliolovisotto giuliolovisotto commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Correlates OpenCode model requests with their exact AgentInvocation by retaining OpenCode's X-Session-Id request header as a single allowlisted capture field. During rollout finalization, calls whose client session matches an observed OpenCode invocation are projected as canonical AgentInvocation.model_calls references.

This avoids timestamp, ordering, payload, and model-name inference. Calls with absent, conflicting, or unknown session ownership retain the existing model_call_ownership_unavailable gap. The session header is client-declared correlation evidence, not an authentication boundary.

The standalone OpenCode harness supplies an explicit title so OpenCode does not make an auxiliary title-model request under the same session identity. Invocation-owned performance totals include every call listed by the harness, including compaction calls when they are also listed on the invocation.

This PR is the producer half of a stack. Stacked draft #2885 lets call-level rollout-health checks consume exact invocation-owned calls when TrajectoryTurn placement is unavailable.

Validation

  • pytest tests/unit_tests/test_rollout_observability.py tests/unit_tests/test_base_responses_api_model.py tests/unit_tests/test_rollout_collection.py responses_api_agents/opencode_agent/tests/test_app.py -q (336 passed)
  • OpenCode 1.17.11 local binary smoke against a localhost OpenAI-compatible endpoint: one /v1/chat/completions request; its X-Session-Id exactly matched the session persisted in OpenCode's SQLite database; no auxiliary title request
  • Producer association helper coverage: 100% (required: 96%)
  • pre-commit run --all-files

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format/copyright pass).
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

@copy-pr-bot

copy-pr-bot Bot commented Aug 31, 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.

@giuliolovisotto giuliolovisotto changed the title Correlate OpenCode model calls with invocations feat(observability): correlate OpenCode calls with invocations Sep 1, 2026
@giuliolovisotto giuliolovisotto changed the title feat(observability): correlate OpenCode calls with invocations [1/3] feat(observability): correlate OpenCode calls with invocations Sep 2, 2026
@giuliolovisotto
giuliolovisotto force-pushed the glovisotto/opencode-call-ownership branch from a636c29 to 382aad9 Compare September 3, 2026 08:44
@giuliolovisotto
giuliolovisotto marked this pull request as ready for review September 3, 2026 09:52
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Sep 4, 2026
@Glorf

Glorf commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

/claude review

@claude

claude Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

SHIP — no reliability concerns.

Reviewed the OpenCode model-call ownership change end to end. Correctness holds:

  • Association ordering / join contract: associate_opencode_session_calls runs before join_model_call_observations and appends ModelCallRefs that join resolves by model_call_id, mirroring the existing claude_code compaction path in merge_model_call_capture_into_record. Fail-safe: wrapped in try/except → model_call_ownership_unavailable(detail=opencode_session_join_failed) on error.
  • Non-mutating + idempotent: invocations are model_copy(update=...)'d so the source bundle stays untouched; _matching_reference_keys dedups already-present refs, so association+join is stable across repeat runs (covered by test_join_model_calls_uses_exact_opencode_session_ownership).
  • Misattribution guards: _unique_request_header returns None on conflicting/duplicate x-session-id values (fail-safe), and the new --title "NG dummy title" flag suppresses OpenCode's auxiliary title-model request that would otherwise share the policy session id and be counted as a policy call. Empty/missing session ids skip cleanly.
  • No async/API surface touched; new module carries the SPDX header; imports are stdlib/internal only.

Test coverage is thorough (long-rollout scaling, phantom-call retention, other-producer passthrough, dedup, failure-path gaps).

Non-blocking NOTE: the updated _build_ng_perf docstring now (correctly) documents that compaction calls sharing an invocation's client_session_id are summed into that invocation's token totals. For OpenCode no calls were owned before, so this is net-new signal rather than a regression — but be aware the token-efficiency numbers now fold in compaction overhead for OpenCode rollouts. Author's call whether that's the intended semantics.

Comment thread nemo_gym/base_responses_api_model.py Resolved
@Glorf

Glorf commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

@giuliolovisotto added 3 comments, please review what is feasible/applicable in this PR context

Keep session association producer-owned and non-mutating. Index exact references so long rollouts remain linear, while missing or failed client correlation stays explicitly unowned.

Signed-off-by: Giulio Lovisotto <[email protected]>
Pass an explicit title so OpenCode does not issue an auxiliary title-model request under the policy session. Clarify that ng_perf sums every invocation-owned call, including compaction when listed there.

Signed-off-by: Giulio Lovisotto <[email protected]>
Signed-off-by: Giulio Lovisotto <[email protected]>
@giuliolovisotto
giuliolovisotto force-pushed the glovisotto/opencode-call-ownership branch from 8799ef2 to 64f3136 Compare September 10, 2026 14:17
@giuliolovisotto giuliolovisotto changed the title [1/3] feat(observability): correlate OpenCode calls with invocations feat(observability): correlate OpenCode calls with invocations Sep 10, 2026
@giuliolovisotto
giuliolovisotto enabled auto-merge (squash) September 10, 2026 14:23
@giuliolovisotto
giuliolovisotto merged commit 71d4690 into main Sep 10, 2026
38 checks passed
@giuliolovisotto
giuliolovisotto deleted the glovisotto/opencode-call-ownership branch September 10, 2026 14:31
giuliolovisotto added a commit that referenced this pull request Sep 10, 2026
## What does this PR do?

Extends five rollout-level checks to consume exact model-call references
owned by either `TrajectoryTurn` or `AgentInvocation`:

- `model_call_failed`
- `model_call_missing_token_counts`
- `model_call_runaway_generation`
- `model_call_zero_completion_tokens`
- `trajectory_capture_mismatch`

The runner resolves exact references before deduplicating captured
calls. Equivalent turn and invocation references therefore evaluate a
call once, while an unbindable turn reference remains a correspondence
finding without hiding a valid invocation reference. It never infers
ownership from list position, timestamps, model names, or payload
similarity. Repeated contradictory references for one call identity
produce one mismatch finding without making the binding complete.

Failed-call terminality follows the saved captured-call order. A
length-limited call whose response payload was not retained makes
`model_call_runaway_generation` unobserved instead of being treated as
an empty response.

Structural checks remain `TrajectoryTurn`-only.
`rollout_token_count_mismatch` and `task_no_successful_model_calls`
retain their existing turn-bound aggregate accounting. The
rollout-health documentation states these evidence boundaries
explicitly.

This PR is stacked on and depends on #2884, which produces exact
OpenCode `AgentInvocation.model_calls` ownership.

### Validation

- `pytest tests/unit_tests/test_rollout_health.py -q` (64 passed)
- Health and runner coverage: 98% (required: 96%)
- Combined stack suite: 425 passed, 13 subtests passed
- `pre-commit run --all-files`
- `cd fern && npm run check` (0 errors)

## Checklist

- [x] I have read the [contributing
guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format/copyright pass).
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

---------

Signed-off-by: Giulio Lovisotto <[email protected]>
Co-authored-by: ritaneves <[email protected]>
jkyi-nvidia pushed a commit that referenced this pull request Sep 11, 2026
…2884)

## What does this PR do?

Correlates OpenCode model requests with their exact `AgentInvocation` by
retaining OpenCode's `X-Session-Id` request header as a single
allowlisted capture field. During rollout finalization, calls whose
client session matches an observed OpenCode invocation are projected as
canonical `AgentInvocation.model_calls` references.

This avoids timestamp, ordering, payload, and model-name inference.
Calls with absent, conflicting, or unknown session ownership retain the
existing `model_call_ownership_unavailable` gap. The session header is
client-declared correlation evidence, not an authentication boundary.

The standalone OpenCode harness supplies an explicit title so OpenCode
does not make an auxiliary title-model request under the same session
identity. Invocation-owned performance totals include every call listed
by the harness, including compaction calls when they are also listed on
the invocation.

This PR is the producer half of a stack. Stacked draft #2885 lets
call-level rollout-health checks consume exact invocation-owned calls
when `TrajectoryTurn` placement is unavailable.

### Validation

- `pytest tests/unit_tests/test_rollout_observability.py
tests/unit_tests/test_base_responses_api_model.py
tests/unit_tests/test_rollout_collection.py
responses_api_agents/opencode_agent/tests/test_app.py -q` (336 passed)
- OpenCode 1.17.11 local binary smoke against a localhost
OpenAI-compatible endpoint: one `/v1/chat/completions` request; its
`X-Session-Id` exactly matched the session persisted in OpenCode's
SQLite database; no auxiliary title request
- Producer association helper coverage: 100% (required: 96%)
- `pre-commit run --all-files`

## Checklist

- [x] I have read the [contributing
guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format/copyright pass).
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

---------

Signed-off-by: Giulio Lovisotto <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
jkyi-nvidia pushed a commit that referenced this pull request Sep 11, 2026
## What does this PR do?

Extends five rollout-level checks to consume exact model-call references
owned by either `TrajectoryTurn` or `AgentInvocation`:

- `model_call_failed`
- `model_call_missing_token_counts`
- `model_call_runaway_generation`
- `model_call_zero_completion_tokens`
- `trajectory_capture_mismatch`

The runner resolves exact references before deduplicating captured
calls. Equivalent turn and invocation references therefore evaluate a
call once, while an unbindable turn reference remains a correspondence
finding without hiding a valid invocation reference. It never infers
ownership from list position, timestamps, model names, or payload
similarity. Repeated contradictory references for one call identity
produce one mismatch finding without making the binding complete.

Failed-call terminality follows the saved captured-call order. A
length-limited call whose response payload was not retained makes
`model_call_runaway_generation` unobserved instead of being treated as
an empty response.

Structural checks remain `TrajectoryTurn`-only.
`rollout_token_count_mismatch` and `task_no_successful_model_calls`
retain their existing turn-bound aggregate accounting. The
rollout-health documentation states these evidence boundaries
explicitly.

This PR is stacked on and depends on #2884, which produces exact
OpenCode `AgentInvocation.model_calls` ownership.

### Validation

- `pytest tests/unit_tests/test_rollout_health.py -q` (64 passed)
- Health and runner coverage: 98% (required: 96%)
- Combined stack suite: 425 passed, 13 subtests passed
- `pre-commit run --all-files`
- `cd fern && npm run check` (0 errors)

## Checklist

- [x] I have read the [contributing
guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format/copyright pass).
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

---------

Signed-off-by: Giulio Lovisotto <[email protected]>
Co-authored-by: ritaneves <[email protected]>
Signed-off-by: Junkeun Yi <[email protected]>
pull Bot pushed a commit to Stars1233/Gym that referenced this pull request Sep 18, 2026
## What does this PR do?

Adds canonical `TrajectoryTurn` records to `opencode_agent` and
`opencode_sandboxed_agent` when observability is enabled. This makes
their persisted assistant content usable by
`rollout_missing_agent_turns` and `agent_turn_hollow` health checks,
while preserving the invocation-owned model calls introduced by NVIDIA-NeMo#2884
and consumed by NVIDIA-NeMo#2885.

### Evidence contract

- A turn is one persisted OpenCode assistant message with provider-step
evidence (`step-start` or `step-finish`). Its native message/part IDs
establish membership; ordering only numbers turns within a session.
- Answer text, reasoning, and tool calls come from that message's parts.
Compaction summaries and explicitly synthetic shell/subtask bookkeeping
do not become policy turns.
- `question` stays unset: the persisted user message is not proof of the
complete provider request. `step_count` counts completed provider steps
cumulatively within each session.
- `TrajectoryTurn.model_calls` stays empty. Existing exact
`AgentInvocation.model_calls` ownership is preserved; this PR does not
infer turn-to-call links from order, timing, or content similarity.
- Interrupted, malformed, or incomplete evidence retains known content
and records `turns_unavailable`, preventing content checks from
declaring a partially observed trajectory healthy or hollow.

There are no changes to health-check semantics, model servers, OpenCode
itself, or existing configs. Call-level checks continue to consume
invocation ownership; token-total reconciliation and the task-level
successful-call check still require complete turn bindings.

### Validation

- 184 agent, rollout-health, and observability regression tests passed;
190 rollout-collection tests passed.
- New shared parser: 100% statement coverage. Existing
application-module coverage is 93.07% (local) / 83.30% (sandboxed); this
is not a claim of 100% coverage for those modules.
- `pre-commit run --all-files` passed.
- Real local OpenCode 1.17.11 run through Gym's model proxy: executed a
Python calculation, wrote and verified `391`, produced three canonical
turns and four invocation-owned captured calls. Content and owned-call
checks evaluated with zero findings; overall verdict remained
`unobserved` because token reconciliation lacks per-turn call
references.
- Both SQLite parsers produced identical canonical turns from the local
live database.
- Real Docker-backed OpenCode 1.17.11 smoke on ARM64: the sandboxed
agent's `run()` path executed a Python calculation, wrote and
independently verified `391`, exported its native SQLite evidence, and
finalized with `opencode_finished=true`. It produced three canonical
turns and three exactly invocation-owned captured calls. Independent
checks confirmed native message/part membership and capture/session
ownership. Health reports contained zero findings; content and
owned-call checks evaluated, while overall verdict remained `unobserved`
because token reconciliation lacks per-turn call references.
- Docker smoke scope: a temporary driver supplied an already-created
Docker sandbox because this branch's Docker provider lacks
`serialize()/connect()` support. Sandbox reconnection was not exercised;
agent execution, export, observation parsing, verification, and
finalization used the real implementation. The small verifier checked
the generated file, not a SWE-bench task. Existing sandbox-lifecycle
timing and verifier-observation gaps remained. No repository files were
changed for this smoke.

The live run used a supported explicit OpenCode provider config. The
automatic provider config reproduced an existing incompatibility:
assistant tool-call history containing `reasoning: ""` is rejected by
Gym's chat schema (HTTP 422). That separate issue is unchanged by this
PR.

## Checklist

- [x] I have read the [contributing
guidelines](https://docs.nvidia.com/nemo/gym/latest/contribute/development-setup).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format/copyright pass).
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

---------

Signed-off-by: Giulio Lovisotto <[email protected]>
@qiaochuz-nv

Copy link
Copy Markdown
Contributor

POR Test Summary — OpenCode Model-Call Ownership (#2961)

Verdict: PASS — 3/3 named cases

Added end-to-end ownership coverage and ran it on a clean Gym checkout at d6d7685.

Scenario Result Observed behavior
README rollouts PASS Two real OpenCode rollouts each captured 2 calls; every call was owned only by the invocation matching its persisted session
Subtask session PASS 3 captured calls split correctly between root (2) and child (1); the child call was not attributed to the root
Missing/unknown/conflicting sessions PASS All 3 probe calls remained unowned with precise ownership gaps, while the 2 legitimate OpenCode calls in the same rollout stayed correctly owned

Each assertion joins three independent evidence surfaces: the durable capture record's client session, OpenCode session-derived agent observations, and the canonical ng_trajectory/ng_perf projection. The cases also verify that invocation token totals count owned calls only and that unreadable/fallback session artifacts do not silently substitute rollout-level ownership.

  • QA testcase: opencode_call_ownership
  • QA run: 20261006T174943108985Z-cd8938cc
  • Duration: 7m 57s
  • Execution: real OpenCode CLI and real inference-provider calls; no model mocks or product source patches

This is post-merge POR coverage of the correlation contract introduced by #2884.

This branch was previously deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants