Repository navigation
feat(dash): capture request metadata, and give the service real structured logging - #71
Merged
OsherElhadad merged 16 commits intoAug 17, 2026
Conversation
added 9 commits
August 16, 2026 18:48
…st correlation The proxy had slog calls but no logging: no handler was ever installed, so DEBUG went nowhere, and the only per-component lines came from metrics.Slog at INFO with neither tenant nor session on them — several lines per request, burying the request itself. Four things: - internal/logging owns the level/format/sink decision (CG_LOG_LEVEL, CG_LOG_FORMAT, CG_LOG_FILE) and installs the default handler. Local use needs no configuration: text on stderr. CG_LOG_FILE adds a JSON sink for a log shipper and is the ONLY thing that makes logs leave the box. CG_LOG_PLAIN=1 opts out entirely, swapping in the stdlib's own text handler. - Credentials are scrubbed on the way OUT, so a careless call site added later cannot leak one — which matters more now that the caller's own provider key flows through request handling. A ReplaceAttr covers attribute values (including the ones baked in by Logger.With) and a wrapper handler covers the message. The patterns are the ones dash already used: they moved to internal/redact and dash/redact.go delegates, because two copies of a credential denylist is one copy that goes stale. - Every line of one request's lifecycle carries the tenant id — never its token — and, from the point apply resolves it, the session. The logger travels in the request context, which is why no component signature changed. - The lines say what was DECIDED, not just what happened: one INFO per request, and at DEBUG the cached-prefix boundary, the bypass gate, the expand loop's resolved-against-unresolved counts, why a stream had to be buffered, and one line per component with its verdict, token delta and the gates that turned candidates away. Those gate names and counts are read off the same Report.Gates map /stats sums into components.<name>.gates, so a log line and the metric cannot disagree. Signed-off-by: Osher-Elhadad <[email protected]>
Grafana stores no logs, so something had to. Loki wins on the property that matters more than any feature comparison: it is read through the Grafana already running on this box, so a latency spike on the service dashboard is one click from the log lines for the same tenant and the same minute — one thing to secure, back up and explain. Its storage model is also the same shape as the Prometheus beside it: a single binary indexing a handful of labels, chunks on the local filesystem, one more container. Elasticsearch would search better and wants a JVM and gigabytes of RAM on a box whose job is serving agent traffic; ClickHouse is a better analytical store than reading logs is an analytical problem; files and grep — kept as the fallback — cannot answer "every line for this tenant's session over three days" without a human and an ssh session, which is the question this exists for. - `install.sh grafana` now brings up all four containers, loopback only, and installs the logrotate snippet. `grafana-status` checks Loki's readiness (not just its port — it answers while the ingester still rejects pushes), that the log file exists, that lines actually arrived in the last ten minutes, and which tenants Loki has seen. That last set of checks exists because a healthy promtail in front of an empty log directory renders an empty dashboard with no error anywhere. - The proxy never talks to Loki. It writes the journal always and CG_LOG_FILE as JSON when set; promtail owns delivery and remembers its position. A shipper inside the process being debugged loses exactly the logs you need when that process is what is going wrong. - `tenant` and `level` are Loki labels; `session` and `component` deliberately are not — a session label would mint one stream per agent conversation and eventually take the index down. They are read out of the JSON at query time, which is what the dashboard's two text fields do. - The logs dashboard filters by tenant, session, level and component, and its gate table answers "the component did nothing and I cannot tell why" off the same Report.Gates map /stats sums. Single-tenant proxies log tenant="local" rather than an empty string, which promtail would drop — leaving the selector empty for exactly the people running this locally. Signed-off-by: Osher-Elhadad <[email protected]>
A request row recorded what happened to a request but nothing about what the
request ASKED for, so the levers that explain a cost were invisible: reasoning
effort, thinking budget, sampling parameters, and — the one this project exists
to reason about — where the prompt-cache breakpoints sat.
Capture, normalized across both dialects (Anthropic `output_config.effort` /
`thinking.{type,budget_tokens}` / object `tool_choice` / block `system`; OpenAI
`reasoning_effort` / `max_completion_tokens` / string `tool_choice`), plus the
provider's stop reason off the same response bytes the token tiers come from.
Real columns, not a JSON blob: every field is either GROUPED BY in an aggregate
or shown on the row, so a blob would put json_extract() in the middle of every
aggregate and give free text somewhere to hide from the redactor. The sampling
columns are NULLABLE because "unset" and "0" are different facts and 0 is a
legitimate value — a sentinel would make a deterministic request read as an
unspecified one.
Client-supplied metadata is attacker-influenced input, so each text field passes
through a credential-shape check and an identifier-shape bound BEFORE the insert,
never on read. Unrecognized-but-harmless values survive verbatim: a dashboard
that renders ordinary data as «redacted» lies about its own coverage.
Breakpoints ride on apply.Trace, split by location, from the count the pipeline
already makes to respect the provider's cap of four — so placement costs the
request path nothing. The remaining fields are one structural pass over the
top-level object, measured at 0.55 ms/MB against 2.7 ms/MB for a per-field query
loop, and it never parses `messages`.
/api/breakdown groups requests, tokens and spent-vs-saved by one allowlisted
dimension, so per-model cost, cost by reasoning effort and cost by breakpoint
count are one query rather than three that can drift. Per-day usage bars need no
new query at all: bucketing already happens in SQL, so a day is a parameter.
Schema version 6 — the intended migration for a derived view: the old file is
renamed aside and the non-derived tables carried across.
Signed-off-by: Osher-Elhadad <[email protected]>
Left behind by the switch from a per-field query loop to the single pass; a package-level var nothing reads is not a compile error, so nothing caught it. Signed-off-by: Osher-Elhadad <[email protected]>
…s tenant logging.Debugging(ctx) is the single guard for "is anyone reading DEBUG", used by apply's decision loop and extract_llm's candidate accounting instead of each one reaching for Enabled(). And BodyOpts's panic recovery now logs through the request's own logger — a panic is the line you most want attributed to a tenant, and it was going out on the default logger with nothing on it. Signed-off-by: Osher-Elhadad <[email protected]>
The UI reads all fifteen fields as top-level keys, which holds only while Meta is embedded anonymously; a json tag on that field would nest them and blank the request drawer with nothing else failing. Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]> # Conflicts: # proxy/proxy.go
added 7 commits
August 17, 2026 06:50
Resolving the connect-ibm-service.md conflict took the credential branch's version wholesale, because its facts were current and the prose branch's were stale. That discarded the prose branch's anchor fix: use-with-claude-code.md's 'The one-liner' heading had become 'Steps', and hosted.md was repointed while this file was not. mkdocs build --strict catches it; the merged tree did not build until now. Both docs branches passed on their own - taking one side of a conflict wholesale is what lost it. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit df749b5)
…e median The regression this guards - content redaction on the request goroutine, ~53ms - is unconditional work, so it lands on every sample including the fastest. Contention only ever makes a sample slower. The minimum is therefore the statistic least polluted by the machine while staying fully sensitive to the defect. The median gate failed roughly one run in three on a loaded box, with the package run alone. A gate that reports the machine rather than the code gets ignored exactly when it is right. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit a2b665c)
A fixed 5ms budget cannot mean the same thing at both ends of this machine's range. Idle, a fake-upstream request settles near 1-2ms; with the suite saturating 16 cores its own median was 331ms. The gate was reporting the machine, failing about one run in three with nothing wrong. Budget is now max(5ms, 10% of the measured baseline), which catches the ~53ms regression at any baseline while contention that slows both handlers equally cannot trip it. The median stays the statistic: the minimum was tried and is worse, being one unaveraged sample - in one run the paired medians differed by 1.27ms where the paired minima differed by 8.13ms. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 3aad033)
The limiter is charged before the argon2 verify, deliberately, because 64 MiB per attempt is itself an amplifier. So the attempts the loop is allowed each pay a full KDF, and on a contended machine those can outlast the limiter's own one-minute window - at which point the earliest attempts have aged out and the bound correctly did not fire. From inside the test, "not limited" and "the window expired underneath us" are indistinguishable, and failing on the second is a test reporting the machine rather than the code. It now skips with the elapsed time named when the loop outran the window, and still fails outright when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 26e8e50)
… conclude Same root cause as the sign-in limiter test: each registration the loop is allowed hashes a password with argon2 at 64 MiB, so on a contended machine the allowed attempts outlast the limiter's one-minute window and age themselves out. The bound then correctly does not fire, which from inside the test looks exactly like the bypass it is checking for. It now skips with the elapsed time named when the loop outran the window, and still fails when it did not. Signed-off-by: Osher-Elhadad <[email protected]> (cherry picked from commit 0531c36)
…ter tests The form's own minlength=12 was refusing registration before the server saw it. Server, form and hint now all say 8; the mailed code, the 5-attempt cap, the per-email and per-address rate limits and a 64 MiB argon2id hash are what bound online guessing. The limiter tests are timed because each attempt they are allowed pays a full KDF, so on a loaded machine they outlast the one-minute window they exist to exhaust - which reads as a bypass when it is not. Signed-off-by: Osher-Elhadad <[email protected]>
OsherElhadad
changed the base branch from
stack/2-credentials-and-auth
to
feat/hosted-tls-and-agent-compaction
August 17, 2026 08:29
OsherElhadad
merged commit Aug 17, 2026
16f5820
into
feat/hosted-tls-and-agent-compaction
5 checks passed
OsherElhadad
added a commit
that referenced
this pull request
Aug 17, 2026
…servability (#79) Lands the nine reviewed PRs (#69, #78, #71-#77) on main. Caller-pays credentials: each request's own provider key is forwarded upstream and a request without one is refused, so no account spends the operator's credential. The per-tenant spend cap goes with it. Email+password accounts with a mailed second factor, 14 confirmed security findings fixed with a failing test each, the rewrite path down from 15.6ms to 6.85ms per request with byte-identical output over 1,868 real captured requests, structured logging with credential scrubbing into Loki, request metadata and a Usage view, a redesigned dashboard, user feedback, full manager control over accounts, and Bob working through the proxy for the first time. Squashed because main carries #67 the same way, and because the nine merge commits GitHub generated for the stack carry no sign-off of their own; every authored commit in them does. The per-PR history stays on feat/hosted-tls-and-agent-compaction and in #69/#78/#71-#77. Signed-off-by: Osher-Elhadad <[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.
Stacked on the PR below.
Request metadata. 15 new columns on
requests: reasoning effort, thinking mode and budget, temperature, top_p, max_tokens, stream, tool_choice mode, tool count, system block count, stop reason, and cache_control breakpoints split by location (system / tools / messages / blocks).The field set was not guessed — it comes from real captured bodies plus a check against current model behaviour, which corrected a stale assumption that would have shipped silently: on current models the reasoning-depth control is
output_config.effort, andthinking.budget_tokensis removed and 400s on recent models. Capturing onlybudget_tokens— the obvious reading of "reasoning effort" — would have recorded nothing for current traffic while appearing to work.Two deliberate deviations from the table's style:
temperature/top_pare nullable, because "unset" and "0" are different facts and 0 is legitimate; and breakpoints are split by location, becausetools/systemrender ahead ofmessages, so one total cannot distinguish good cache placement from bad.Columns rather than a JSON blob: every field is either grouped in an aggregate or shown on the row, so JSON would put
json_extract()inside every aggregate and give the free-text tail somewhere to hide from the redactor.Hot-path cost is nil. Breakpoint counts ride on the count the pipeline already makes to respect the provider's cap of four. The rest is one structural pass — 0.55 ms/MB and 1 alloc, versus 2.7 ms/MB for per-field gjson queries — and it never parses
messages.New
/api/breakdownplus per-day bars (which needed no new endpoint: bucketing already happened in SQL), spent-vs-saved overall and per model.Structured logging.
internal/logging: slog levels with pinned meanings, one INFO line per request, DEBUG for per-component decisions read from the sameReport.Gatesmap/statssums — so a log line and the metric cannot drift. Two pre-existing bugs fixed on the way: nothing ever installed a handler, so every existingslog.Debugwent nowhere, andmetrics.Slogemitted N+1 INFO lines per request with no tenant or session, burying the request itself.Scrubbing is a handler, not a discipline. A
ReplaceAttrcovers attribute values and keys; a wrapper handler covers the message, becauseReplaceAttrnever sees it andslog.Info("upstream "+url+" failed")is the shape that leaks userinfo. The two credential denylists (dashand logging) are merged into oneinternal/redactrather than left to drift.Loki + promtail as two more loopback containers, read through the Grafana already on the box, with a provisioned datasource and a dashboard filterable by tenant, session, level and component. The proxy never talks to Loki — it writes the journal always and a JSON file when configured; promtail owns delivery. A local proxy gets useful stderr logs with no containers, and
CG_LOG_PLAIN=1opts out to a plain stdlib handler entirely.Verified: DEBUG lines carrying a planted Anthropic key, OpenAI bearer, AWS key id,
.envline,postgres://user:pass@URL and a JWT through deliberately careless shapes — secret in the message, wholehttp.Headerin one attr, wrapped error,WithGroup— with zero survivors in text and JSON. Gates summed from the log lines reconcile with/statscomponent-for-component and count-for-count.