Repository navigation
fix: subagent-type linkage, SDK streaming, session provenance, doctor + mcp hardening - #686
Merged
Merged
Conversation
…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]>
Contributor
|
| 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]
Reviews (6): Last reviewed commit: "fix(sdk): add __anext__ to litellm's asy..." | Re-trigger Greptile
…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]>
… 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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-tokentokenjam/sdk/integrations/{anthropic,openai,litellm}.py: every provider's stream wrapper finalizes (records usage, stamps the streaming data-quality signature, ends the span) only viafor/withconsumption.__next__bare-delegated straight to the underlying stream, bypassing that entirely — driving a stream by hand withnext()in a loop (the standard manual-iteration idiom) left the span open forever, however cleanly the stream actually finished.__next__methods now finalize onStopIteration/any exception, idempotently (a_finalizedguard — load-bearing for litellm specifically, since a double_tj_litellm_active.resetraises).anthropic.Messages.create(stream=True)returns the rawStream[MessageStreamEvent]SSE iterator (no.usageattribute — that only exists on.stream()'sMessageStream), so it fell through thehasattr(response, "usage")gate and produced a zero-token span regardless of what was generated. Added_RawStreamWrapper, which accumulates usage frommessage_start/message_deltaevents, including cache tokens (previously missing on the.stream()path too, unlike the non-streaming branch)._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-StopIterationfor all three providers,_RawStreamWrappervia bothforand barenext(), cache tokens, and the litellm contextvar-release-exactly-once guard.B — Diverged
ingest_secret401s silently; DB-locked error names the wrong hosttj doctornow checks that every config on the search path (project-local.tj/config.toml+ global) agrees oningest_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).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.statewhen resolvable, and says so plainly when the recorded PID is no longer a runningtj 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=falsecarried 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 (renamedbulk_overlay_subagent_attrs→bulk_overlay_span_attrs, one mechanism, not two): theattributesJSON column overlays additively viajson_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_spansintest_backfill.pyupdated (a plain re-run now does what only--reingestused to).D — No provenance recorded at ingest (migration 21)
Nothing recorded what PRODUCED a session. Two independently-maintained predicates (
core.agent_kindvscore.alerts.is_interactive_coding_agent) re-derive a "coding vs SDK" answer fromagent_idnaming conventions and disagree BY DESIGN on Codex prefix-vs-exact matching (seeagent_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_agentare untouched, andtest_alerts.py::test_is_interactive_coding_agent_margin_casespasses unmodified.sessions.sourceis set at the strongest signal each ingest path actually has: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.COALESCEinupsert_session, matchingplan_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 evennormalize_task_statement's masked-but-still-legible output) anddominant_model— the "did this repeat prior work" signalcore.optimize.repeat_taskneeds. 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-codere-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 migrationscli/cmd_mcp.py's read-only fallback (duckdb.connect(path, read_only=True)) bypassesDuckDBBackend.__init__/run_migrationsentirely. A store behind on schema used to surface a rawBinderError/CatalogExceptionthe first time a tool touched the gap. Now detects the gap up front (missing_expected_tables/missing_expected_columns— pureinformation_schemaSELECTs, safe read-only) and every@mcp.tool()wrapper degrades to one clear "runtj serveonce (it migrates on boot) ortj doctor --repair" message via a new_wrap_tool_errorhelper, 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 —
--projectremoved (breaking change), not fixedThe section this ticket originally opened as ("
--projectbackfill scoping ignores the flag") got a different resolution from the operator: remove--projectentirely 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.--projectCLI option and the interactive project-name prompt (_prompt_project_name) it fed — both--claude-codeand--add-projectnow derive unconditionally, no prompt.--projectstays 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"._onboard_claude_codeand_onboard_add_projectnow only apply the derived name to a brand-new agent entry, or one whoseprojectfield 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.docs/cli-reference.md,docs/installation.md, and every test that used--projectas a non-interactive convenience flag (stripped) or tested the removed behavior directly (rewritten to test the new derive/respect-existing behavior).--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.pyrewritten (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.pyupdated.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, populatesub_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_typeare written in exactly one place:core/backfill.py, called either on-demand or continuously bytranscript_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(...) ... RETURNINGcrashed with an internal DuckDB fatal error (a false-positive PRIMARY KEY violation, zero actual duplicate keys in the batch — verified) against the real ~700k-rowspanstable at ~25k-row overlay batches, on DuckDB 1.5.1. A synthetic minimal table did not reproduce it. Fixed by droppingRETURNINGand computing the changed-count via a separateCOUNT(*)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.ingest_claude_coderun:spans_retagged=52,392, unresolved dropped to $3,081.67 (67.2%). The remaining 67.2% is NOT a bug — 100% of it carriestaskKind: "in_process_teammate"(the deliberate_PER_DISPATCH_TASK_KINDScarve-out), verified against every remaining span's on-disk sidecar.sourcefilled by a plain re-run (the rest have no transcript left on disk to re-derive from), 100% agreeing withclassify_agent_kind— 0 disagreements. The OLD documented divergence betweenis_interactive_coding_agentandclassify_agent_kindstill reproduces on a sample of the same corpus's agent_ids (confirms neither predicate was altered).Tests / Verification (repo-wide)
ruff check tokenjam/andmypy tokenjam/clean (full repo, every round of edits including section F).tests/integration/test_cli.py. One pre-existing, unrelated failure found in that sweep and confirmed viagit stashto 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.origin/maininto 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
insert_spanrow-at-a-time item — explicitly YAGNI-gated, left alone.core.agent_kindandcore.alerts.is_interactive_coding_agent, and did not retrofitis_interactive_coding_agent's five call sites to read the newsessions.sourcecolumn — the brief was explicit that the fix is the column, not the merge, and doing either risks the exact regression it warned against.core.optimize.repeat_task's clustering functions to consume the newtask_statement_hash/dominant_modelcolumns 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._AsyncStreamWrapperhas no__anext__at all (only__aiter__→ an async generator) — a caller doing manualawait wrapper.__anext__()would hit anAttributeErrorimmediately 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.summarizetool wrappers (landed via anorigin/mainmerge mid-session) to use the new_wrap_tool_errorhelper — they weren't part of this PR's diff and I didn't want to touch code outside what I authored.