Skip to content

Fix onboarding writing an unreachable OTLP endpoint, and detect it in doctor - #696

Merged
anshss merged 2 commits into
mainfrom
otel-endpoint
Aug 4, 2026
Merged

anshss merged 2 commits into
mainfrom
otel-endpoint

Conversation

@anshss

@anshss anshss commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Onboarding wrote an OTLP endpoint that cannot be reached from the machine it was writing to, so agent telemetry was exported to nowhere and dropped silently.

The bug

The tj-managed block in ~/.zshrc set:

export OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:<port>

host.docker.internal is the address a process inside a container uses to reach a service on its host. On a host it does not resolve at all. Verified from a plain login shell:

DOES NOT RESOLVE: host.docker.internal ([Errno 8] nodename nor servname provided, or not known)
resolves: 127.0.0.1

Every span an agent session emitted therefore failed at DNS resolution, before a connection was ever attempted, with no error surfaced anywhere.

The loss was invisible because a second path covers most of it. Transcript parsing (core/backfill.py) recovers token and cost spans in delayed batches, so dashboards kept showing numbers. Two Claude Code OTel event types have no transcript equivalent and nothing reconstructs them, so those were lost outright:

  • claude_code.tool_decision (permission allow/deny, and whether auto- or user-approved)
  • claude_code.api_error (an errored request may never land as a transcript message at all)

On the reporter's machine, 4,581 of 4,581 spans in a 24h window carried attributes.source = "backfill.claude_code". Zero arrived over OTLP.

What changed

Endpoint. _otel_endpoint_host() picks the host for the machine being written to: loopback normally, the Docker gateway name only when tj is itself running inside a container and that name resolves, and TJ_OTEL_HOST overrides both for a setup neither case describes (a shell rc exported into a container, a daemon on another machine). A container that publishes no host-gateway name falls back to loopback, because an unresolvable hostname fails earlier and more silently than a wrong-but-resolvable one. The port continues to come from config, which is the port the daemon binds.

Repair, not just "stop re-offending". The managed block is delimited by a stable sentinel pair and every managed block (current sentinel plus every legacy marker) is stripped before exactly one fresh block is written, so re-running onboarding corrects an endpoint an older install already wrote. This machinery existed; what was missing was a test that it repairs a bad endpoint rather than only a stale marker. Added a full onboard -> uninstall round trip over a profile seeded with both legacy markers and a stale bad endpoint, asserting one correct block after onboard and zero residue after uninstall.

Secrets: stop minting per-project ones. tj onboard with no persona flag minted a fresh ingest_secret into a project-local .tj/config.toml. The daemon is launched from a unit file naming the global config explicitly, so it always authenticates with the global secret whatever directory anything else runs from; a project-local secret is one the daemon can only reject, and spans signed with it are discarded with a 401 nothing reports.

I took the "stop writing them" option rather than making project-local secrets a supported concept. The product already treats the global config as the single source of truth for this key (daemon unit file, managed shell block, every persona onboarding path), and per-project secrets would need per-project daemons to mean anything. So:

  • ensure_global_ingest_secret() is now the only minting site. It adopts the existing global secret and only mints when there is none, so re-onboarding never rotates a working secret.
  • align_project_secret_to_global() rewrites a stale project-local secret to the global value. The global value always survives, because the managed shell block that every already-configured integration reads carries it; adopting the project value would break all of them at once. The repair is a textual edit of the one key, so the surrounding comments in a hand-written config are not deleted as a side effect, and it is reported rather than done silently.

Detection: a real check, not an ambient warning. load_config printed a divergence warning to stderr on every invocation of every command, derived from a static file diff, in front of unrelated output, while nothing was listening on the endpoint at all. That is noise which teaches people to read past warnings. It is gone.

tj doctor now probes the pipeline for real: it reads the endpoint from the shell profile (what an agent session actually inherits, not what the config intended), resolves the host, opens a TCP connection, and when something answers, authenticates with the secret that block signs with. One verdict per layer.

The divergence detection itself is kept and still reported by tj doctor's ingest-secret check. Its tests were inverted, not deleted: they now pin that load time is silent and that the same state is still detectable on demand.

Verification

Endpoint repair, run against a throwaway HOME. Seeded with the exact broken state (a legacy-marker block plus a current-sentinel block naming an unreachable host and the wrong port):

--- seeded ~/.zshrc ---
# my own env
export FOO=bar

# ocw harness observability
export OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:7391
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer legacy-token"

# >>> tokenjam OTEL (managed) >>>
export OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:7500
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer stale-token"
# <<< tokenjam OTEL <<<

--- after re-onboarding writes the block ---
# my own env
export FOO=bar

# >>> tokenjam OTEL (managed) >>>
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_PROTOCOL=http/json
export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:7391
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer <redacted>"
# <<< tokenjam OTEL <<<

Both legacy blocks and the bad endpoint gone, exactly one block, user content preserved, port matching the daemon's bind port.

tj doctor, isolated HOME, all three states:

# nothing listening
⚠  OTLP endpoint: http://127.0.0.1:7799 (~/.zshrc) resolves but nothing is
listening (Connection refused). Start the daemon with `tj serve`, then re-run
`tj doctor`.

# something listening, secret accepted
✓  OTLP endpoint: http://127.0.0.1:7799 (~/.zshrc) is reachable and accepted
the configured ingest secret.

# something listening, secret rejected
✗  OTLP endpoint: http://127.0.0.1:7799 (~/.zshrc) is reachable but rejected
the ingest secret in that block (401), so every span it pushes is discarded.
Re-run `tj onboard --claude-code` to rewrite the block with the secret the
daemon uses.

Tests:

python -m pytest tests/unit -k "onboard or config or doctor or secret" -q
534 passed, 1 skipped, 4016 deselected

python -m pytest tests/unit -q          4532 passed, 17 skipped, 2 xfailed
python -m pytest tests/integration -q   657 passed
ruff check tokenjam/                    All checks passed
mypy tokenjam/                          Success: no issues found in 276 source files

New coverage: tests/unit/test_doctor_otlp_endpoint.py (each probe layer, plus an assertion that no check message can carry a secret), tests/unit/test_global_ingest_secret.py (adopt-not-rotate, global-survives alignment, comment preservation), endpoint-host selection cases in tests/unit/test_onboard_zshrc_otel.py, and the two round-trip tests in tests/integration/test_cli.py.

Onboarding wrote `OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:<port>`
into the user's shell profile unconditionally. That hostname is the address a
process INSIDE a container uses to reach its host; on a host it does not resolve
at all, so every span an agent session emitted failed at DNS and was dropped
silently. Token and cost figures still appeared, because transcript backfill
recovers those in delayed batches, which is why the loss went unnoticed: the two
Claude Code event types with no transcript equivalent (tool decisions and API
errors) simply never existed.

Endpoint: `_otel_endpoint_host()` chooses the host for the machine being written
to. Loopback normally, the Docker gateway only when tj is itself running in a
container and the name resolves, and `TJ_OTEL_HOST` overrides both for a setup
neither case describes. The port already came from config (the daemon's bind
port), and still does.

Repair: the managed block was already sentinel-delimited and rewritten whole, so
re-onboarding now CORRECTS an endpoint an older install left behind. Pinned by a
full onboard -> uninstall round trip seeded with both legacy markers and a stale
bad endpoint, asserting one correct block after onboard and zero residue after
uninstall.

Secrets: `tj onboard` (no persona flag) minted a fresh ingest secret into a
project-local `.tj/config.toml`. The daemon is launched from a unit file naming
the global config, so it can only ever reject that secret. `ensure_global_ingest_secret()`
is now the single minting site and adopts the global value when one exists;
`align_project_secret_to_global()` rewrites a stale project-local secret. The
global value always survives, because the shell block and every already-working
integration carry it.

Detection: the every-invocation stderr divergence warning is gone. It fired in
front of every command on a fault the user cannot act on from there, while
nothing was even listening. `tj doctor` now resolves the endpoint the shell
profile actually declares, opens a TCP connection, and authenticates with that
block's secret, reporting a verdict per layer: unresolvable host, nothing
listening (naming a port mismatch), rejected secret, or healthy. The divergence
assertions were inverted rather than deleted, so the same tests now pin silence
at load time plus detectability on demand.

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

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR changes onboarding to choose a host-reachable OTLP endpoint, centralizes ingest-secret ownership in the global config, and adds live endpoint diagnostics to tj doctor.

  • Rewrites managed shell telemetry blocks during onboarding and removes legacy residue during uninstall.
  • Adds DNS, TCP, and authenticated HTTP checks for the shell-configured OTLP endpoint.
  • Aligns project-local ingest secrets with the daemon’s global secret and removes ambient divergence warnings.
  • Adds focused unit and integration coverage for endpoint repair, secret alignment, and doctor verdicts.

Confidence Score: 4/5

The PR does not yet appear safe to merge because the previously reported IPv6 endpoint failures, valid-TOML alignment gap, and destructive global-config rewrite remain.

Bare IPv6 hosts are still emitted and probed with malformed URL authorities, single-quoted project secrets still evade repair and continue producing authentication failures, and minting a missing global secret still rewrites existing configuration through a lossy serializer.

Files Needing Attention: tokenjam/cli/cmd_onboard.py, tokenjam/cli/cmd_doctor.py, tokenjam/core/config.py

Important Files Changed

Filename Overview
tokenjam/cli/cmd_onboard.py Adds environment-aware endpoint selection and project-secret alignment, but the previously reported IPv6 URL formatting defect remains.
tokenjam/cli/cmd_doctor.py Adds layered OTLP reachability and authentication checks, while the authenticated probe still reconstructs IPv6 authorities without brackets.
tokenjam/core/config.py Centralizes global secret minting and textual project alignment, but both previously reported TOML alignment and config-preservation defects remain.
tests/unit/test_doctor_otlp_endpoint.py Thoroughly covers IPv4 DNS, connection, authentication, and secret-redaction outcomes but does not cover the outstanding IPv6 behavior.
tests/unit/test_global_ingest_secret.py Covers normal global-secret adoption and double-quoted project alignment but not the two outstanding TOML preservation cases.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    O[ tj onboard ] --> G[Global config and ingest secret]
    G --> Z[Managed shell OTel block]
    Z --> A[Agent session]
    A --> E[OTLP endpoint]
    E --> D[TokenJam daemon]
    X[tj doctor] --> Z
    X --> R[DNS resolution]
    R --> T[TCP connection]
    T --> H[Authenticated status probe]
Loading

Reviews (2): Last reviewed commit: "Merge branch 'main' into otel-endpoint" | Re-trigger Greptile

f"export OTEL_LOGS_EXPORTER=otlp\n"
f"export OTEL_EXPORTER_OTLP_PROTOCOL=http/json\n"
f"export OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:{port}\n"
f"export OTEL_EXPORTER_OTLP_ENDPOINT=http://{host}:{port}\n"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 IPv6 endpoint formatting breaks

When TJ_OTEL_HOST is a bare IPv6 literal such as ::1, onboarding writes the invalid URL http://::1:<port>, causing telemetry exports to fail. Even when the stored endpoint is bracketed correctly, doctor reconstructs its authenticated probe URL without the required IPv6 brackets.

Knowledge Base Used: CLI (tj)

Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/cli/cmd_onboard.py
Line: 1699

Comment:
**IPv6 endpoint formatting breaks**

When `TJ_OTEL_HOST` is a bare IPv6 literal such as `::1`, onboarding writes the invalid URL `http://::1:<port>`, causing telemetry exports to fail. Even when the stored endpoint is bracketed correctly, doctor reconstructs its authenticated probe URL without the required IPv6 brackets.

**Knowledge Base Used:** [CLI (`tj`)](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/cli.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread tokenjam/core/config.py
Comment on lines +627 to +634
patched, count = _re.subn(
r'(?m)^(\s*ingest_secret\s*=\s*)"[^"]*"',
lambda m: m.group(1) + f'"{secret}"',
text,
count=1,
)
if not count:
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Valid secrets escape alignment

When a project config uses a valid single-quoted TOML value such as ingest_secret = 'old-secret', parsing detects the divergence but this double-quote-only regex finds no replacement and silently returns. The stale secret remains active, so telemetry from that project continues to receive 401 responses.

Knowledge Base Used: Core Data Model

Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/config.py
Line: 627-634

Comment:
**Valid secrets escape alignment**

When a project config uses a valid single-quoted TOML value such as `ingest_secret = 'old-secret'`, parsing detects the divergence but this double-quote-only regex finds no replacement and silently returns. The stale secret remains active, so telemetry from that project continues to receive 401 responses.

**Knowledge Base Used:** [Core Data Model](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/core-data-model.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment thread tokenjam/core/config.py
Comment on lines +590 to +594
path = global_config_path()
config = load_config(str(path)) if path.exists() else TjConfig(version="1")
secret = _secrets.token_hex(32)
config.security.ingest_secret = secret
write_config(config, path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Secret minting rewrites config

When an existing global config lacks an ingest secret, this path round-trips the entire file through write_config merely to add one key. That unnecessarily removes user-authored comments and formatting and drops extension keys not represented by TjConfig.

Knowledge Base Used: Core Data Model

Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/config.py
Line: 590-594

Comment:
**Secret minting rewrites config**

When an existing global config lacks an ingest secret, this path round-trips the entire file through `write_config` merely to add one key. That unnecessarily removes user-authored comments and formatting and drops extension keys not represented by `TjConfig`.

**Knowledge Base Used:** [Core Data Model](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/core-data-model.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@anshss
anshss merged commit d237d58 into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the otel-endpoint 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