Skip to content

fix: subagent-type linkage, SDK streaming, session provenance, doctor + mcp hardening - #686

Merged
anshss merged 12 commits into
mainfrom
subagent-type-linkage
Aug 4, 2026
Merged

anshss merged 12 commits into
mainfrom
subagent-type-linkage

Conversation

@anshss

@anshss anshss commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

One PR covering the full ticket: subagent-type attribution, plus five more sections the operator asked to land alongside it. Each section below is independently testable; see per-section "Tests" for what pins it.

A — SDK streaming spans vanish on bare next(), create(stream=True) was zero-token

tokenjam/sdk/integrations/{anthropic,openai,litellm}.py: every provider's stream wrapper finalizes (records usage, stamps the streaming data-quality signature, ends the span) only via for/with consumption. __next__ bare-delegated straight to the underlying stream, bypassing that entirely — driving a stream by hand with next() in a loop (the standard manual-iteration idiom) left the span open forever, however cleanly the stream actually finished.

  • All three __next__ methods now finalize on StopIteration/any exception, idempotently (a _finalized guard — load-bearing for litellm specifically, since a double _tj_litellm_active.reset raises).
  • anthropic.Messages.create(stream=True) returns the raw Stream[MessageStreamEvent] SSE iterator (no .usage attribute — that only exists on .stream()'s MessageStream), so it fell through the hasattr(response, "usage") gate and produced a zero-token span regardless of what was generated. Added _RawStreamWrapper, which accumulates usage from message_start/message_delta events, including cache tokens (previously missing on the .stream() path too, unlike the non-streaming branch).
  • litellm's cache-token extraction (_set_usage_attributes/_extract_cache_tokens) was already correct on both sync and async paths — untouched.

Tests: tests/unit/test_stream_usage_capture.py — new: bare-next()-until-StopIteration for all three providers, _RawStreamWrapper via both for and bare next(), cache tokens, and the litellm contextvar-release-exactly-once guard.

B — Diverged ingest_secret 401s silently; DB-locked error names the wrong host

  • tj doctor now checks that every config on the search path (project-local .tj/config.toml + global) agrees on ingest_secret, reusing the comparison the config-load-time warning already does (core.config.find_diverged_secret_config, extracted as the shared source of truth for both).
  • The CLI's "Database is locked" error named only the CONFIGURED api.{host,port} for THIS invocation, which can differ from what the process actually holding the lock booted with. It now also names the real holder (PID/port/config) from ~/.local/share/tj/server.state when resolvable, and says so plainly when the recorded PID is no longer a running tj serve.

Tests: tests/unit/test_doctor_ingest_secret.py, tests/unit/test_main_lock_holder_hint.py.

C — Content overlay: the other half of the subagent-type fix

A corpus first ingested with [capture] prompts=false carried permanent NULL content even after the flag was re-enabled — a plain backfill re-run only ever INSERTed new spans, same shape of gap as sub_agent_type below. Extended the SAME primitive (renamed bulk_overlay_subagent_attrs → bulk_overlay_span_attrs, one mechanism, not two): the attributes JSON column overlays additively via json_merge_patch(parsed, stored) — the STORED side wins on any key both carry (RFC 7396 merge-patch semantics: the second argument wins), so a key the row already has can never be replaced, only genuinely-new keys get added. Gated on a capture toggle actually being on AND the re-parsed span carrying more than baseline provenance keys, so the common capture-off case never re-queues every existing span for a no-op payload.

Also adds tj doctor's "Captured content backfill" check + --repair — the other side of the existing capture-off check (which only flags the toggle being off, saying nothing about backfilled history that predates turning it on).

Tests: tests/unit/test_doctor_content_capture_gap.py; test_reingest_backfills_captured_content_onto_existing_spans in test_backfill.py updated (a plain re-run now does what only --reingest used to).

D — No provenance recorded at ingest (migration 21)

Nothing recorded what PRODUCED a session. Two independently-maintained predicates (core.agent_kind vs core.alerts.is_interactive_coding_agent) re-derive a "coding vs SDK" answer from agent_id naming conventions and disagree BY DESIGN on Codex prefix-vs-exact matching (see agent_kind's module docstring).

The fix is the missing column, not merging the predicates — both stay exactly as they were. All five existing call sites of is_interactive_coding_agent are untouched, and test_alerts.py::test_is_interactive_coding_agent_margin_cases passes unmodified.

sessions.source is set at the strongest signal each ingest path actually has:

  • A literal constant in the two dedicated backfill adapters (core/backfill.py, core/ingest_adapters/codex.py) — each parses ONLY that tool's own transcripts, not a guess.
  • agent_kind.classify_agent_kind (the tighter of the two predicates, reused rather than duplicated) at the live path (core/ingest.py), which genuinely sees a mix of Claude Code / Codex / SDK telemetry.
  • Fill-once via COALESCE in upsert_session, matching plan_tier's existing discipline.

Also additive on the same row: task_statement_hash (a one-way hash of the normalized first user prompt — never the raw text, and never even normalize_task_statement's masked-but-still-legible output) and dominant_model — the "did this repeat prior work" signal core.optimize.repeat_task needs. Backfilled where the transcript is still on disk; unrecoverable once Claude Code prunes it (measured: 99.9% available under 30 days, 3.6% at 30-60 days, 0% beyond).

No new repair path needed: a plain tj backfill claude-code re-run already overlays these onto existing sessions via the SAME additive-upsert discipline — verified end to end, and against the operator's real corpus (see below).

Tests: tests/unit/test_session_provenance.py — Claude Code/Codex backfill stamping, live-path classification (parametrized over the exact predicate-divergence case), fill-once, the two predicates' independence, and the self-healing overlay on a pre-migration session.

E — tj mcp's read-only fallback bypasses migrations

cli/cmd_mcp.py's read-only fallback (duckdb.connect(path, read_only=True)) bypasses DuckDBBackend.__init__/run_migrations entirely. A store behind on schema used to surface a raw BinderError/CatalogException the first time a tool touched the gap. Now detects the gap up front (missing_expected_tables/missing_expected_columns — pure information_schema SELECTs, safe read-only) and every @mcp.tool() wrapper degrades to one clear "run tj serve once (it migrates on boot) or tj doctor --repair" message via a new _wrap_tool_error helper, instead of the raw DuckDB exception text.

Tests: tests/unit/test_mcp_readonly_schema_gap.py — forces the real failure against a real DuckDB file with a real column dropped (not a mocked exception), confirms it degrades, and confirms an UNRELATED duckdb error with no known gap still passes its real message through.

F — --project removed (breaking change), not fixed

The section this ticket originally opened as ("--project backfill scoping ignores the flag") got a different resolution from the operator: remove --project entirely rather than fix its scoping. The project/dashboard-namespace name is now unconditionally derived from the repo (git remote) or folder name (_derive_project_name — the existing default-derivation, reused, not duplicated) — that was already the default nearly everyone ended up with; the flag and its interactive prompt were ceremony that only ever created divergence.

  • Removed the --project CLI option and the interactive project-name prompt (_prompt_project_name) it fed — both --claude-code and --add-project now derive unconditionally, no prompt.
  • This is a breaking CLI change. --project stays declared (hidden) purely to catch a script still passing it and fail with an explicit message ("--project has been removed. The project name is now taken from the repo/folder name automatically.") instead of Click's generic "no such option".
  • An existing agent's hand-entered project name is respected, never silently rewritten. Both _onboard_claude_code and _onboard_add_project now only apply the derived name to a brand-new agent entry, or one whose project field is still unset — silently renaming a live agent would orphan its dashboard history under a new identity, a data-loss-shaped bug even though no rows are deleted.
  • Swept and updated: CLI help text, docs/cli-reference.md, docs/installation.md, and every test that used --project as a non-interactive convenience flag (stripped) or tested the removed behavior directly (rewritten to test the new derive/respect-existing behavior).
  • Did NOT add --project-style root/backfill scoping as a replacement — the operator was explicit that removing the flag removes the false promise the original scoping bug was about; no new behavior was requested.

Tests: tests/unit/test_onboard_project_flag_removed.py (new — the explicit removal error); tests/unit/test_onboard_add_project.py rewritten (respects an existing hand-entered namespace, fills one for a new/unset agent); test_onboard_first_run.py, test_onboard_path_branch.py, tests/integration/test_cli.py updated.

G — proxy ingestion question: PARKED, no code touched

Confirmed no changes to proxy/audit.py, proxy/wiring.py, or response-usage parsing anywhere in the proxy. This section is an open design question the operator will resolve later; nothing in this PR depends on or blocks it.

What contradicted the original diagnosis (subagent-type-linkage, the original half)

The original brief's Part 1 ("make core/ingest.py, the live OTLP path, populate sub_agent_type") didn't apply. There is no separate live-ingest path for Claude Code subagent data to fix there — that module is the generic SDK/OTLP path, and Claude Code's own OTLP telemetry is structurally a flat tree with no subagent identity at all (api/routes/sessions.py:24's existing docstring). sub_agent_id/sub_agent_type are written in exactly one place: core/backfill.py, called either on-demand or continuously by transcript_sync.py's catch-up loop — THAT is the live ingest path for this data, and it already derived the type correctly on new spans. The real gap was the overlay onto existing rows (now generalized in section C above to cover content too).

One bug found only through live-corpus testing, not code review: UPDATE ... FROM read_json(...) ... RETURNING crashed with an internal DuckDB fatal error (a false-positive PRIMARY KEY violation, zero actual duplicate keys in the batch — verified) against the real ~700k-row spans table at ~25k-row overlay batches, on DuckDB 1.5.1. A synthetic minimal table did not reproduce it. Fixed by dropping RETURNING and computing the changed-count via a separate COUNT(*) query sharing the same join/WHERE, under the same write-lock hold.

Live-corpus verification (subagent-type + provenance)

Measured on a SCRATCH COPY of the operator's real ~/.tj/telemetry.duckdb — copied, repaired, measured, deleted; the original file's mtime confirms it was never touched.

  • Subagent type: before, $4,392.73 unresolved (96.6% of subagent spend). After a plain ingest_claude_code run: spans_retagged=52,392, unresolved dropped to $3,081.67 (67.2%). The remaining 67.2% is NOT a bug — 100% of it carries taskKind: "in_process_teammate" (the deliberate _PER_DISPATCH_TASK_KINDS carve-out), verified against every remaining span's on-disk sidecar.
  • Provenance: of 7,070 sessions, 2,717 got source filled by a plain re-run (the rest have no transcript left on disk to re-derive from), 100% agreeing with classify_agent_kind — 0 disagreements. The OLD documented divergence between is_interactive_coding_agent and classify_agent_kind still reproduces on a sample of the same corpus's agent_ids (confirms neither predicate was altered).

Tests / Verification (repo-wide)

  • ruff check tokenjam/ and mypy tokenjam/ clean (full repo, every round of edits including section F).
  • 639 tests passed across sections A–E's touched areas (backfill, bulk insert, ingest accounting, transcript sync, doctor checks x6, MCP server + read-only fallback, SDK streaming x3 providers, session provenance, agent_kind/alerts/framing, repeat_task, storage backend parity), 5 skipped (pre-existing e2e/API-key gates). A separate sweep of section F's onboard changes: 217 passed across 8 onboard test files + 93 passed in tests/integration/test_cli.py. One pre-existing, unrelated failure found in that sweep and confirmed via git stash to fail identically without any of this branch's changes (test_home_when_db_populated_but_no_config_is_set_up) — not touched, out of scope. Full suite not run locally — relying on CI for the rest.
  • Merged origin/main into the branch four times over the course of this work (clean each time; the branch was also independently merged with main by another process mid-session — merged that in too, no content lost, confirmed by an empty diff).

What's NOT in this PR

  • Section G (whether the proxy is an ingestion path) — parked per the operator's explicit instruction; no code touched (see section G above).
  • The parked live-ingest insert_span row-at-a-time item — explicitly YAGNI-gated, left alone.
  • Did not merge core.agent_kind and core.alerts.is_interactive_coding_agent, and did not retrofit is_interactive_coding_agent's five call sites to read the new sessions.source column — the brief was explicit that the fix is the column, not the merge, and doing either risks the exact regression it warned against.
  • Did not deeply wire core.optimize.repeat_task's clustering functions to consume the new task_statement_hash/dominant_model columns instead of a live raw-prompt argument — that module's precision/gating is measurement-validated and deliberately conservative (see its own module docstring); swapping its data source is a separate decision from adding the columns it would consume, and I didn't want to touch a delicate, already-tuned analyzer without a dedicated measurement pass of its own.
  • litellm's async _AsyncStreamWrapper has no __anext__ at all (only __aiter__ → an async generator) — a caller doing manual await wrapper.__anext__() would hit an AttributeError immediately rather than silently losing data, a different (self-evident, not silent) failure mode than what section A's brief called out. Left alone to keep scope to the named line numbers.
  • Did not extend the MCP server's summarize tool wrappers (landed via an origin/main merge mid-session) to use the new _wrap_tool_error helper — they weren't part of this PR's diff and I didn't want to touch code outside what I authored.

anshss and others added 2 commits August 4, 2026 13:30
…or repair

A normal backfill only ever inserted spans whose span_id was new, so a column
added after a span was first ingested (sub_agent_type, migration 19) could
never fill on a row that already existed — it was never "new" again. On the
operator's real corpus this left the overwhelming majority of subagent spend
with no resolved type, breaking the per-agent-type cost attribution
subagent_rightsizing and cost_proposals depend on.

Adds a set-based overlay (bulk_overlay_subagent_attrs / COALESCE, strictly
additive — never clobbers an already-resolved value) that a plain backfill run
now applies to existing rows, wired into the same bulk path the continuous
transcript-sync catch-up loop already calls, so it self-heals without a flag.
Also adds a `tj doctor` check + `--repair` action that runs an unbounded pass
and reports what changed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 4, 2026 08:02
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR hardens streaming telemetry finalization, historical span/session enrichment, diagnostics, MCP schema compatibility, and onboarding project derivation.

  • Finalizes provider streaming spans under manual iteration and captures Anthropic raw-stream usage.
  • Additively overlays newly recoverable span attributes and records session provenance through schema migration 21.
  • Adds doctor diagnostics and repair paths for content, subagent linkage, secret divergence, and lock-holder state.
  • Degrades MCP tools cleanly when a read-only database has an outdated schema.
  • Removes the project override while preserving existing configured namespaces.

Confidence Score: 5/5

The PR appears safe to merge based on the eligible follow-up findings available in this review.

No blocking failure remains in the available follow-up review scope.

Important Files Changed

Filename Overview
tokenjam/sdk/integrations/anthropic.py Adds idempotent stream finalization and usage aggregation for Anthropic raw SSE streams.
tokenjam/sdk/integrations/openai.py Ensures manual synchronous stream iteration finalizes spans on exhaustion or failure.
tokenjam/sdk/integrations/litellm.py Makes streaming finalization idempotent and releases LiteLLM suppression state exactly once.
tokenjam/core/backfill.py Adds recoverable span-attribute overlays and derives session source, task hash, and dominant model from transcripts.
tokenjam/core/db.py Adds migration 21 session fields, fill-once upsert behavior, schema expectations, and bulk additive span overlays.
tokenjam/core/ingest.py Stamps live-ingested sessions with classified source provenance.
tokenjam/cli/cmd_doctor.py Adds diagnostics and repairs for unresolved subagent linkage, historical content gaps, and divergent ingest secrets.
tokenjam/cli/cmd_mcp.py Detects missing expected schema objects before exposing a read-only database to MCP tools.
tokenjam/mcp/server.py Centralizes MCP tool error degradation for known read-only schema gaps.
tokenjam/cli/cmd_onboard.py Removes project-name overrides, derives namespaces automatically, and preserves existing configured namespaces.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Providers[Provider streams] --> Wrappers[SDK stream wrappers]
  Wrappers --> Live[Live ingest]
  Transcripts[Claude Code and Codex transcripts] --> Backfill[Backfill adapters]
  Backfill --> Overlay[Additive span overlay]
  Live --> Sessions[Session provenance upsert]
  Overlay --> DB[(DuckDB spans and sessions)]
  Sessions --> DB
  Doctor[tj doctor] --> DB
  MCP[tj mcp] --> Schema{Current schema?}
  Schema -->|Yes| DB
  Schema -->|No| Guidance[Migration guidance]
Loading

Reviews (6): Last reviewed commit: "fix(sdk): add __anext__ to litellm's asy..." | Re-trigger Greptile

anshss and others added 7 commits August 4, 2026 13:52
…cp degrades on schema gap

Three independent fixes bundled with the subagent-type-linkage work per the
same ticket:

- tj doctor now checks that every config on the search path agrees on
  ingest_secret (a project-local + global config with different secrets
  silently 401s span pushes between the SDK and a daemon started from a
  different cwd); factored the comparison out of the existing config-load-time
  warning so there's one source of truth for both.
- The DB-locked CLI error used to name only the configured api.{host,port}
  for THIS invocation, which can differ from what the process actually
  holding the lock booted with. It now also names the real holder (PID/port/
  config) from server.state when resolvable, and says so plainly when the
  recorded PID is no longer a running tj serve.
- tj mcp's read-only fallback connects duckdb directly, bypassing
  run_migrations/schema-self-heal. A store behind on schema used to surface a
  raw BinderError/CatalogException the first time a tool touched the gap;
  it now detects the gap up front (read-only-safe SELECTs against
  information_schema) and every tool degrades to one clear "run tj serve
  once" message instead.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…oken create(stream=True)

Three SDK provider patches (anthropic, openai, litellm) wrap a streamed
response to capture trailing usage and end the span, but only via `for`/
`with` consumption. Every wrapper's `__next__` bare-delegated straight to the
underlying stream, bypassing the finalize logic entirely — a caller driving
the stream by hand with `next()` in a loop (the standard manual-iteration
idiom, not just `for`) left the span open forever: never ended, never
exported, however cleanly the stream actually finished.

Also: `anthropic.Messages.create(stream=True)` returns the raw
`Stream[MessageStreamEvent]` SSE iterator, not the `MessageStreamManager`
`.stream()` returns — it has no `.usage` attribute at all, so the existing
`hasattr(response, "usage")` gate silently produced a zero-token span for
every streamed `create()` call regardless of what was generated. Added
`_RawStreamWrapper`, which accumulates usage from the `message_start`/
`message_delta` events themselves (cache tokens too — previously missing on
the `.stream()` streaming path as well, unlike the non-streaming branch which
always extracted them).

litellm's `_set_usage_attributes`/`_extract_cache_tokens` cache-token
extraction was already correct on both sync and async streaming paths and is
untouched — only the `__next__` bypass and the finalize-must-run-exactly-once
guard (a double `_tj_litellm_active.reset` raises) were fixed there.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…n 21)

Nothing recorded what PRODUCED a session — every reader re-derived a
"coding vs SDK" answer from agent_id naming conventions, via one of two
independently-maintained, deliberately divergent predicates
(core.agent_kind vs core.alerts.is_interactive_coding_agent — see
agent_kind's module docstring for why they intentionally disagree on Codex
prefix-vs-exact matching). The fix is the missing column, not merging the
predicates: both stay exactly as they were, all five existing call sites of
is_interactive_coding_agent are untouched, and the pinned margin-case test
(test_alerts.py::test_is_interactive_coding_agent_margin_cases) still
passes unmodified.

sessions.source is set at the strongest signal each ingest path actually
has: a literal constant in the two dedicated backfill adapters (each parses
ONLY that tool's own transcripts — not a guess), and
agent_kind.classify_agent_kind (the tighter, already-existing predicate,
reused rather than duplicated) at the live path, which genuinely sees a mix
of Claude Code / Codex / SDK telemetry. Fill-once via COALESCE in
upsert_session, matching plan_tier's existing discipline.

Also additive on the same row: task_statement_hash (a one-way hash of the
normalized first user prompt — never the raw text, and never even the
normalize_task_statement output, which is masked but still legible) and
dominant_model, the "did this repeat prior work" signal
core.optimize.repeat_task needs. Backfilled where the transcript is still on
disk; unrecoverable once Claude Code prunes it (measured: 99.9% available
under 30 days, 3.6% at 30-60 days, 0% beyond).

No new repair path needed: a plain (non---reingest) tj backfill claude-code
re-run already overlays these onto existing sessions via the same
additive-upsert discipline the previous subagent-type-linkage overlay uses —
verified end to end.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…tor check

A corpus first ingested with [capture] off carries permanent NULL prompt/
completion/tool_input content even after the flag is turned on later — a
plain backfill re-run only ever INSERTed new spans, the same shape of gap
the subagent-type-linkage overlay closed for sub_agent_id/sub_agent_type.

Extends the SAME primitive (renamed bulk_overlay_subagent_attrs ->
bulk_overlay_span_attrs, one mechanism, not two): the attributes JSON column
now overlays additively via json_merge_patch(parsed, stored) — the STORED
side wins on any key both carry (RFC 7396 merge-patch semantics), so a key
the row already has can never be replaced, only genuinely-new keys get
added. _dedup_new_spans queues a span for the content half only when a
capture toggle is actually on and the re-parsed span carries more than the
baseline provenance keys, so the common capture-off case never re-queues
every existing span for a no-op payload.

Also adds `tj doctor`'s "Captured content backfill" check + --repair — the
other side of the existing capture-off check, which only flags the toggle
being off and says nothing about backfilled history that predates turning
it on.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss anshss changed the title fix: overlay sub_agent_type onto existing spans + doctor repair fix: subagent-type linkage, SDK streaming, session provenance, doctor + mcp hardening Aug 4, 2026
anshss and others added 3 commits August 4, 2026 14:44
… now

BREAKING CHANGE: `tj onboard --project X` no longer works. Any script that
passed it now gets an explicit error ("--project has been removed. The
project name is now taken from the repo/folder name automatically.")
instead of Click's generic "no such option" — the flag stays declared,
hidden, purely to catch this and explain why.

The interactive project-name prompt (_prompt_project_name) is removed too —
leaving the flag gone but the prompt in place would have been worse than
either alone. The project/dashboard-namespace name is now unconditionally
derived from the repo (git remote) or folder name (_derive_project_name,
the existing default-derivation, reused rather than duplicated) — that was
already the default nearly everyone ended up with; the flag and the prompt
were ceremony that only ever created divergence.

An EXISTING agent that already carries a hand-entered project name (from
before this change) is left untouched: both _onboard_claude_code and
_onboard_add_project now only apply the derived name to a brand-new agent
entry, or one whose project field is still unset. Silently rewriting a
live agent's namespace would orphan its dashboard history under a new
identity — a data-loss-shaped bug even though no rows are deleted.

The scoping bug this was originally filed against (a whole-tree backfill
regardless of --project) needs no separate fix: removing the flag removes
the false promise it was making. No root-scoping behavior was added.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The ingest-secret divergence check (section B) used a bare `import
tomllib`, which is stdlib only from Python 3.11+ — pyproject.toml declares
`requires-python = ">=3.10"`, so every `tj doctor` invocation on 3.10 raised
ModuleNotFoundError, cascading into ~8 integration test failures.

Matches the guard this same file already carries at _check_mcp_wiring
(sys.version_info >= (3, 11) -> tomllib, else tomli as tomllib) rather than
inventing a second spelling. tomli>=2.0 is already declared in pyproject.toml
for python_version < '3.11', so no dependency change needed.

Verified against a real CPython 3.10.20 interpreter (uv venv), not just
mypy/ruff: tests/integration/test_cli.py (93 passed) plus every test file
this branch's sections A-F touch (133 passed) run clean under it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
_AsyncStreamWrapper had no __anext__ at all -- only __aiter__, returning a
separate async generator. A manual `await wrapper.__anext__()` (the async
parallel to the sync bare-next() idiom section A's fix already closed) hit
AttributeError immediately: Python's `async for` only ever drives
__aiter__()'s generator, never the wrapper's own __anext__.

A loud crash rather than the sync bug's silent data loss, but still wrong --
manual async iteration deserves the same instrumentation as manual sync
iteration, not a crash. Mirrors _SyncStreamWrapper exactly: same
_consume/_finalize split, same idempotency guard (finalizing twice would
double-reset the litellm-active contextvar token, which raises), same
STREAM_USAGE_REPORTED-stamped-unconditionally convention. litellm's async
cache-token extraction was already correct and stays untouched.

Verified against a real CPython 3.10.20 interpreter (uv venv), not just
mypy/ruff: the new tests drive the wrapper by hand with real
`await __anext__()` calls to a genuine StopAsyncIteration, plus a mixed
__anext__-then-__aiter__ case proving the finalize guard holds across both
paths on the same instance.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@anshss
anshss merged commit 1118935 into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the subagent-type-linkage branch September 18, 2026 21:03
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.

1 participant