Skip to content

otel: OpenTelemetry traces (OTLP/HTTP+JSON) for agent loop + gateway - #242

Merged
FMXExpress merged 2 commits into
mainfrom
claude/otel-traces
Jun 13, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/otel-traces

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Adds OpenTelemetry traces to PasClaw, mirroring openclaw v2026.2+'s span shape so existing OTel-aware backends (Langfuse, Tempo, Jaeger, Honeycomb, Datadog) recognise our spans without remapping.

Span hierarchy:

HTTP <method> <route>            (gateway: every inbound /v1/* call,
                                  W3C traceparent parsed for parent ctx)
└── openclaw.agent.turn          (one tool loop iteration set)
    ├── chat <model>             (provider request, gen_ai.* attrs)
    └── execute_tool <name>      (serial tool dispatch)

Configuration mirrors openclaw's diagnostics.otel.* block so configs copy/paste cleanly:

{"diagnostics":{"otel":{
  "enabled": true,
  "endpoint": "http://localhost:4318",
  "serviceName": "pasclaw",
  "sampleRate": 1.0,
  "headers": {"Authorization": "Bearer ..."}
}}}

Off by default. Flips on when EITHER diagnostics.otel.enabled=true in config.json OR OTEL_EXPORTER_OTLP_ENDPOINT is set in the environment — matching the standard OTel SDK contract (ops sets the env var at deploy time, the agent picks it up).

Design choices

  • OTLP/HTTP+JSON only. Spec mandates both JSON and protobuf on the http path; every collector groks both, so JSON avoids protobuf vendoring in Pascal.
  • Synchronous-per-trace export. Spans buffer until the root finishes, then ship in one POST. Avoids 5-POSTs-per-turn waste without a background batcher thread.
  • threadvar current-span stack. Per-request gateway spans stay isolated across Indy worker threads.
  • W3C Trace Context (traceparent header) parsed inbound, formatted outbound via CurrentTraceparent.
  • JSON-control-byte escaping on all attribute string values — error messages with embedded quotes won't break the envelope.
  • Test seam. SetExportTransport(@CaptureFn) swaps the OTLP/HTTP transport for a callback, so otel_tests captures the POST body without standing up a real collector.

Known limitations (follow-up PRs)

  • Metrics + logs scoped out. The diagnostics.otel.metrics/logs booleans are reserved fields; only traces are wired.
  • Parallel tool workers don't yet propagate the parent span's threadvar context across the worker boundary; tool dispatches under Cfg.Parallel=True won't appear in traces. Serial dispatch (the default) is fully traced.

Test plan

  • make smoke — green
  • make test — full aggregate green (19 PASS markers)
  • make test-otel — 10 inline assertions + 1 env-mode pass, all green:
    • disabled-by-default emits nothing
    • single root span → canonical OTLP/HTTP+JSON envelope (resourceSpans, scopeSpans, service.name, telemetry.sdk.*)
    • parent/child relationship: same trace id, child.parentSpanId points at parent.spanId; export deferred until root finishes
    • W3C traceparent parsed inbound
    • malformed traceparent tolerated (start fresh trace silently)
    • CurrentTraceparent formats outbound header
    • sampleRate=0.0 drops root spans (no allocation, no export)
    • SetStatus(oscError) → status.code=2 + message preserved
    • All helpers tolerate nil so disabled call sites stay clean
    • JSON-control bytes escaped in attribute values
    • Env-mode pass: Makefile invokes the binary with OTEL_EXPORTER_OTLP_ENDPOINT=http://env-host:4318 --env-mode to exercise the env-var-flips-enabled path (FPC RTL snapshots envp at startup, so we can't mutate mid-process)

Scope check

~1500 LOC (target ~500 + tests). The unit ended up larger than estimated because the OTLP/JSON envelope encoding + W3C traceparent + sampling + threadvar context stack + nil-tolerant helpers all needed inline documentation to be useful. Test file came in at ~500 LOC to cover the corner cases (escaping, malformed headers, sampling edge cases) — happy to split out into a leaner v2 if you'd prefer.


Generated by Claude Code

Adds OTLP/HTTP+JSON tracing to PasClaw, mirroring openclaw v2026.2+'s
span shape so existing OTel-aware backends (Langfuse, Tempo, Jaeger,
Honeycomb, Datadog) recognise our spans without remapping.

Span hierarchy:
  HTTP <method> <route>        (gateway: every inbound /v1/* call,
                                 W3C traceparent header parsed for
                                 cross-service parent context)
   |__ openclaw.agent.turn     (one tool loop iteration set)
        |__ chat <model>       (provider request, gen_ai.* attrs)
        |__ execute_tool <name> (serial tool dispatch)

Configuration mirrors openclaw's diagnostics.otel.* block so configs
copy/paste between projects:

  {"diagnostics":{"otel":{
    "enabled": true,
    "endpoint": "http://localhost:4318",
    "serviceName": "pasclaw",
    "sampleRate": 1.0,
    "headers": {"Authorization": "Bearer ..."}
  }}}

Off by default; flips on when EITHER diagnostics.otel.enabled=true
in config.json OR OTEL_EXPORTER_OTLP_ENDPOINT is set in the env
(matches the standard OTel SDK contract -- ops sets the env var at
deploy time, the agent picks it up).

Implementation notes:

  - OTLP/HTTP+JSON transport only. The OTLP spec mandates both JSON
    and protobuf on the http path; every collector groks both, so
    JSON is the realistic Pascal choice (no protobuf vendoring).
  - Synchronous-per-trace export: spans buffer until the root span
    finishes, then ship in one POST. Avoids 5-POSTs-per-turn waste
    without standing up a background batcher thread.
  - threadvar current-span stack so per-request gateway spans don't
    bleed across Indy worker threads.
  - W3C Trace Context (traceparent header) parsed inbound and
    formatted outbound via CurrentTraceparent.
  - JSON-control-byte escaping on all attribute string values --
    error messages with embedded quotes won't break the envelope.
  - Test seam: SetExportTransport(@CaptureFn) swaps the OTLP/HTTP
    transport for a callback, so otel_tests captures the POST body
    without standing up a real collector.

Known limitations to address in follow-ups:

  - Metrics + logs are scoped out (traces only). The
    diagnostics.otel.metrics/logs booleans are reserved fields.
  - Parallel tool workers don't yet propagate the parent span's
    threadvar context across the worker boundary; their tool
    dispatches won't appear in traces under Cfg.Parallel = True.
    Single-threaded serial dispatch (the default) is fully traced.

Tests pin the observable shape via src/tests/otel_tests.pas:
  - disabled-by-default emits nothing
  - single root span -> resourceSpans envelope with service.name +
    telemetry.sdk.* resource attrs, scopeSpans, span kind enums
  - parent/child relationship: same trace id, child.parentSpanId
    points at parent.spanId; export deferred until root finishes
  - W3C traceparent parsed inbound; malformed header silently
    starts fresh trace (real-world gateways see broken propagation
    all the time -- crashing the handler would be wrong)
  - CurrentTraceparent formats outbound header
  - sampleRate=0 drops root spans (no allocation, no export)
  - SetStatus(oscError) -> status.code=2 + message preserved
  - All helpers tolerate nil so disabled call sites stay clean
  - JSON-control bytes escaped in attribute values
  - Second pass with OTEL_EXPORTER_OTLP_ENDPOINT inherited from the
    Makefile exercises the env-var-flips-enabled path (FPC's RTL
    snapshots envp at startup, so we can't mutate mid-process).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0d1f0717f0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1103 to +1107
Diagnostics.Otel.Enabled := Sub.GetBool('enabled', Diagnostics.Otel.Enabled);
Diagnostics.Otel.Endpoint := Sub.GetStr ('endpoint', Diagnostics.Otel.Endpoint);
Diagnostics.Otel.Protocol := Sub.GetStr ('protocol', Diagnostics.Otel.Protocol);
Diagnostics.Otel.ServiceName := Sub.GetStr ('serviceName', Diagnostics.Otel.ServiceName);
Diagnostics.Otel.SampleRate := Sub.GetFloat('sampleRate', Diagnostics.Otel.SampleRate);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve OTel settings when saving config

These new diagnostics.otel fields are parsed into TConfig, but TConfig.ToJSON has no matching diagnostics emission block. Any command that calls SaveConfig after loading a config with OTel enabled (for example auth/model/MCP/skill updates) rewrites config.json through C.ToJSON and silently drops the whole diagnostics block, so tracing is disabled on the next run unless the user relies only on env vars.

Useful? React with 👍 / 👎.

Code review on PR #242 caught a silent data-loss bug. FromJSON parsed
the diagnostics.otel block into TConfig but ToJSON had no matching
emission, so any command that called SaveConfig after LoadConfig --
auth, model swap, MCP edits, skill installs all do -- rewrote
config.json through ToJSON and silently dropped the whole diagnostics
tree. Users who enabled tracing in config would lose it on the next
config-mutating command with no error telling them why.

Fix: add the symmetric emission block after the gateway block in
ToJSON. Shape mirrors the parse 1-for-1 (enabled, endpoint, protocol,
serviceName, sampleRate, traces, metrics, logs, optional headers
nested object). Always emitted -- same shape the gateway / sandbox
blocks use -- so a `pasclaw config show` round-trip is stable.

Pin the regression with TestConfigRoundTripPreservesOtelBlock in
otel_tests.pas: mutate every otel field away from defaults, ToJSON,
FromJSON the result back, assert every field round-tripped including
both header pairs. Also asserts the diagnostics + otel block keys
are present in the JSON itself so a future refactor that breaks
emission shows up as an actionable failure instead of trivially
passing "default == default" assertions.
@FMXExpress
FMXExpress merged commit 28c0bb2 into main Jun 13, 2026
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Both changelog files were stuck at the 2026-06-10 TUI / background-
subagent / session_search / tool-RPC entries. ~7 weeks of merged
PRs (#214 through #244) had landed without a corresponding entry in
either file -- the git log was the only record of features like the
knowledgebase, inbound MCP server mode, checkpoints + /undo,
heartbeat daemon, shell backends (local | docker), send_message,
promptware defense, Windows shell-output encoding fixes, fs_grep
ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent
--quiet`.

Added (newest first):

  2026-06-13
    #244  agent --quiet log-level clamp

  2026-06-12
    #243  dcc64 search path + agent --quiet / -q
    #242  OpenTelemetry traces (OTLP/HTTP+JSON)
    #241  fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool)
    #240  fs_grep tier 1-4 (deferred hash + skip-dirs + binary
          sniff + size cap)

  2026-06-11
    #239  Windows shell output: auto-detect UTF-8 vs OEM
    #238  Hashline fs_read header mojibake fix (¶ vs ¶)
    #237  Windows shell output: OEM codepage decode

  2026-06-10
    #233  Shell backends (local | docker via IShellBackend)
    #232  Heartbeat daemon + reversible condensation (CCR)
    #230  send_message tool + condenser families + promptware
          defense + task-aware MEMORY.md slicing

  2026-06-09
    #223  /goal Ralph loop + judge model + JSON-aware condenser
    #222  /undo wired into agent + sample dprojs
    #221  Checkpoints (auto-snapshot + TUI /undo)
    #220  mcp catalog: lenient hub projector
    #219  mcp: SSE / Streamable HTTP / stdio hub transports
    #218  Inbound MCP server mode
    #217  onboard: offer to index docs into the knowledgebase
    #214  Knowledgebase (RAG over operator-curated docs)

Skipped from this changelog (build-system / Delphi-fix / FPC-fix
PRs visible in the git log but not user-facing features):
#215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236.

Both files (README.md and docs/changelog.md) updated with the same
entries -- intentional mirror so a reader on either surface sees
the same history. Same prose in both; same footnote refs at the
bottom.

Validated: every [#N] reference in both files has a matching [#N]:
URL footnote (no broken links).
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
PR FMXExpress#242 added src/pkg/otel/PasClaw.Otel.pas and wired it into
PasClaw.Config's implementation `uses` clause, but only the FPC
Makefile's UNIT_DIRS got updated -- src/pasclaw/PasClaw.dproj kept
the pre-FMXExpress#242 search path, so the next dcc64 build of PasClaw.dpr
errored out the moment it pulled PasClaw.Config in:

  PasClaw.Config.pas(611): F2613 Unit 'PasClaw.Otel' not found.

(Line 611 is the new `PasClaw.Otel` entry in the implementation
uses list -- the file itself exists, dcc64 just didn't know to look
under ..\pkg\otel for it.)

Fix: append `..\pkg\otel` to the DCC_UnitSearchPath, slotted right
before `..\pkg\vendor\dmvcframework` to match the order the
Makefile lists it. Same pattern any other new package directory
follows when added to the build.

No behavioural change. FPC build was already green (Makefile has
src/pkg/otel under UNIT_DIRS since FMXExpress#242); this brings the Delphi
project up to parity.
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
The root README.md is 1007 lines covering everything from install
to provider catalog to security to embedding. Useful as a reference,
painful as a landing page. This PR adds /docs/ as a topical tree
that a reader can navigate by topic — README.md is left untouched
so existing GitHub deep-links (README.md#mcp-servers etc.) keep
working.

Pages added:

  index:
    docs/README.md            ← link tree by topic

  getting started:
    docs/getting-started.md   ← install + onboard + first chat
    docs/configuration.md     ← config.json + env vars + $PASCLAW_HOME
    docs/commands.md          ← all 27 top-level commands

  capabilities:
    docs/providers.md         ← 19-entry catalog + fallback + caching
    docs/tools.md             ← built-in tools the model sees
    docs/web-search.md        ← web_search / web_fetch providers
    docs/memory.md            ← workspace/memory/ + FTS5 + vector
    docs/knowledgebase.md     ← pasclaw kb (RAG over docs)
    docs/skills.md            ← $PASCLAW_HOME/workspace/skills/
    docs/sessions.md          ← persistence + resume + steering
    docs/mcp.md               ← MCP servers (stdio + http) + catalog
    docs/cron.md              ← scheduled tasks

  interfaces:
    docs/gateway.md           ← /v1/chat/completions + /v1/responses
    docs/channels.md          ← Telegram/Slack/Matrix/IRC/Discord/...
    docs/embedding.md         ← TPasClawAgent / TPasClawServer

  operations:
    docs/security.md          ← sandbox + denylist + SSRF guard
    docs/observability.md     ← OpenTelemetry + /v1/stats
    docs/troubleshooting.md   ← grep-friendly "user sees X, fix Y"

  inside pasclaw:
    docs/architecture.md      ← system overview + agent loop walkthrough
    docs/contributing.md      ← repo layout + build + test + commit style
    docs/changelog.md         ← feature-by-feature history

  specialised (already there, kept):
    docs/c2w.md               ← container2wasm browser build

Conventions for these pages:
  - Each page is focused on one topic.
  - Cross-links are relative (./<topic>.md#<anchor>).
  - Source-truth comments at the top of each unit are still the
    last word; these pages link to the relevant unit when the
    inline comment is the better source.
  - The README.md changelog and the new docs/changelog.md
    intentionally mirror each other -- when a PR adds a feature
    worth surfacing, both files get an entry.

Three pages have no prior source material in the README and were
written fresh: architecture.md (system overview from the inline
unit comments), contributing.md (build conventions, test
conventions, commit style codified from PR history), and
troubleshooting.md (entries mined from PR descriptions where
real-world issues were diagnosed — Windows OEM mojibake from FMXExpress#237,
config rewrite drops diagnostics from FMXExpress#242, [info] leak in --quiet
from FMXExpress#244, etc.).

README.md is byte-identical to main -- intentional. Splitting it
would break deep-links people have to specific sections. The docs/
tree is purely additive.
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.

2 participants