Repository navigation
feat: user feedback, and full manager control over accounts - #77
Merged
OsherElhadad merged 94 commits intoAug 17, 2026
Merged
OsherElhadad merged 94 commits into
OsherElhadad merged 94 commits into
Conversation
added 30 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]>
The default hosted pipeline ([format, dedup, failed_run, cmdfilter, extract,
cachesplit], sync) spent most of its CPU re-doing work it had already done. A
CPU profile over 24 real captured Claude Code requests (median 600 KB, 71
messages) attributed the rewrite path as: normalize 44%, wireBreakpoints 22%
(and it runs twice per request), a full transcript deep-clone per component 10%.
None of that is component work.
Six changes, each measured on that capture, output verified byte-identical:
- wireBreakpoints walked the body with seven `#.field` gjson queries, each a
full re-scan that squashed every matched array. Now one pass over the
top-level object, with a substring prefilter before any structural parse
(neither spelling can be a field if "cache" is not even in the bytes), and
the post-rewrite cap re-count only when something actually changed — an
untouched body still carries exactly the inbound count.
- The pipeline deep-cloned the whole transcript per component for its revert
snapshot. It now keeps ONE snapshot and re-clones only the messages a
component changed; a revert re-establishes an independent copy, because
req.Input then aliases the one we were holding. Every snapshot entry is
still exactly one clone of a live message, so fidelity is unchanged — two
new tests fail without either half.
- The lossless round-trip check (two unmarshals into `any` plus a DeepEqual)
ran for all ~70 messages up front; it only matters for a message a component
changed, so it is computed on demand.
- Every normalized message was marshalled twice: once in normalize, once for
the count-change rebuild path only summarize takes. The rebuild now reads
slot.pre.
- normalize called encoding/json.Unmarshal on a type that implements
json.Unmarshaler, so encoding/json contributed nothing but a checkValid
re-scan of bytes gjson had already parsed — 40% of the unmarshal cost. It
calls UnmarshalJSON directly, and fetches each message's `content` once.
- ContentKey is memoized (like internal/tokens.Count): every offloader asks
skipReduce about every candidate, so one request normalized and sha256'd the
same tool output three or four times. Keyed by (len, hash) — a wrong key
here would mean a wrong stashed original, unlike a stale token count.
Measured, 24 real captured requests, same test code both sides:
end-to-end 552.6 ms -> 253.3 ms (-54%)
one median req 15.6 ms -> 6.9 ms (-56%), 9554 -> 3232 allocs (-66%)
per-component duration_ms, pipeline total 1.75 ms -> 1.06 ms (-39%)
live /compact through the proxy, 73 requests, median 37.1 -> 19.2 ms
live LLM calls through the gateway, cg_added_ms_avg 37.1 -> 25.8
Byte-identical output verified over 373 real captured requests (73
Terminal-Bench + 300 SWE-bench) via a golden hash of every rewritten body, with
the hashes recorded on the unmodified code. Fail-open, never-worse and
reversibility are untouched; the #32 replay test still puts breakpoints on the
wire for 72 of 73 requests.
What did NOT help and was reverted: prefiltering normalize's content walk on a
"tool_result" substring (no measurable change — real user messages nearly all
carry one).
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]>
The pipeline snapshots messages before each component so it can revert on error/panic/never-worse. When the JSON round-trip clone fails, fallbackClone falls back to bifrost's DeepCopyChatMessage — and per [email protected]/schemas/utils.go its block copier (deepCopyChatContentBlock, l.803) copies only Type, Text, Refusal, ImageURLStruct, InputAudio and File. ChatContentBlock also carries three non-OpenAI fields (chatcompletions.go l.1122-1128): CacheControl, Citations and CachePoint. All three were silently dropped. So on that path a revert did not restore the message, it degraded it: a request that arrived with cache_control on a block came back out without it. That is the never-worse invariant broken on the least visible path — the one that only runs after something else already went wrong — and it is not cosmetic here. A dropped breakpoint is a full cache write instead of a cache read, ~12.5x the price, and getting breakpoints onto the wire is the entire point of cachesplit/cacheinject. The clone now restores the three fields after bifrost's copy, cloning the pointer values (TTL/Scope/Enabled) rather than sharing them, so snapshot and live message stay independent in both directions. The failure is reachable, not theoretical: ChatMessageContent.MarshalJSON errors when a message carries both string and block content, which a component can produce, and that is what the new test builds. TestFallbackCloneKeepsCacheFields fails on the parent commit ("revert dropped cache_control: a prompt-cache breakpoint is gone from the wire") and passes here. Output equivalence unchanged: golden hashes still match over the same 373 real captured requests (73 Terminal-Bench + 300 SWE-bench), the #32 replay still puts breakpoints on the wire for 72 of 73, and the latency benchmarks are unmoved (253 ms over 24 requests, 6.5 ms median request, 3222 allocs) since this path is off the hot path. Signed-off-by: Osher-Elhadad <[email protected]>
Signed-off-by: Osher-Elhadad <[email protected]> # Conflicts: # proxy/proxy.go
…ssage The writeback ran sjson.SetBytes over the WHOLE body per changed message. sjson allocates and copies the entire request for every write, so the cost was O(k * body): 30 rewritten tool outputs on a 600 KB request copied ~18 MB to produce one 600 KB result. Each write also re-scanned the body with gjson to find its target, and applyMetaWrites did the same once per metadata key. Now each changed message's own bytes are edited and all of them are spliced back in one pass. The output is byte-identical, not merely equivalent JSON, because sjson's splice is local: appendRawPaths ([email protected]) emits json[:res.Index], recurses into that subtree's Raw, then appends json[res.Index+len(res.Raw):]. Editing a message and putting it back at the message's span is therefore the same bytes as editing at "messages.<i>.<rest>" on the whole body. Everything outside an edited span is copied verbatim, which is what invariant I1 requires. Two things make that safe rather than clever: - Spans come from the offsets gjson already produced for each message, plus the byte shift splitVolatileTail now reports (it rewrites the top-level `system` value, so everything after it moves). Re-parsing the messages array to find the spans instead was the obvious version and it was SLOWER than what it replaced: measured on the median captured request, one array parse is 1.21 ms against 0.44 ms for a whole-body sjson write, so it only paid above ~3 rewrites per request. That version was a 13% regression; this one has no extra parse, and drops one that rebuildCountChanged was already duplicating. - gjson documents Index as "zero means index unknown" and it is relative to whatever json the Result came from, so no span is trusted on its word: the body's own bytes at that span must equal the message's Raw or the splice declines and the original request is forwarded. A wrong offset therefore costs a rewrite, never a corrupt body. The shift needs its own test, because captured traffic cannot cover it: Claude Code orders the body `messages` before `system`, so the split shifts nothing on real requests, and json.Marshal of a map sorts keys the same way. TestSpliceRewrites- EveryMessageAtItsOwnSpan builds the body with `system` first and both splits and rewrites in one request; it fails (fail-open, no rewrite forwarded) with the shift hard-coded to 0 and with it off by one. Measured, 24 real captured requests: end-to-end 253.6 ms -> 243.5 ms (-4.0%) bytes allocated 167 MB -> 144.5 MB (-13.4%), allocs unchanged one median request 6.61 ms -> 6.60 ms (flat) Per-component duration_ms is untouched by construction — pipeline.runOne's timer wraps the component call, and this is all after it, so the -39% stands. Output verified byte-identical over 1868 real captured requests (73 Terminal-Bench + 1795 SWE-bench) against golden hashes recorded before the change, and the #32 replay still puts breakpoints on the wire for 72 of 73. applyMetaWrites now takes the message rather than the body, since metaWrite.path was already message-relative; bodyIndexOf is gone, splitSlotPath does that job. Signed-off-by: Osher-Elhadad <[email protected]>
Both sides rewrote the breakpoint counter for different reasons, and both reasons stand. Reconciled to ONE implementation: the perf branch's single structural walk (ParseBytes().ForEach + mayHold/elemMarks), accumulating into the metadata branch's location-split Breakpoints instead of one int. The split is what feeds the four dashboard columns; the single pass is what takes the counter off ~22% of the rewrite path. Neither needed the other's implementation — the walk already knows which top-level key it is under, so the location comes out free, where the 7-path form had to derive it from the query string. wireBreakpoints stays as the one-line Total() wrapper the cap check calls. Kept from fix/clone-and-writeback: the conditional re-count (an untouched body carries exactly the inbound count, so n > inbound is false by construction), the duplicate normPre marshal loop's removal (slot.pre already holds it), and the spliceMessages writeback with its fail-open span check. Kept from the observability work: every DEBUG line behind its `debug` guard, dumpToolOutputs, and the cap-breach ERROR — now on the session-bearing context logger, which is why it no longer repeats "session" as an attribute. sort.Ints was the only caller of "sort"; slices was already imported for formatGates, so spliceMessages uses slices.Sorted(maps.Keys(edits)). Verified: gofmt/vet clean, go test -race green. Byte-identity goldens reproduce on 373 captured requests (73 terminal-bench + a 300-request swebench prefix). The merged counter returns the same per-location numbers as the 7-path version on 3736 real bodies (every captured request, inbound and post-pipeline). #32 replay: breakpoints reach the wire on 72 of 73. Per- component duration_ms unchanged — components/pipeline.go is byte-identical to the perf branch and Pipeline.Run holds the same cumulative CPU. Signed-off-by: Osher-Elhadad <[email protected]>
A secret in a log attribute's KEY was emitted verbatim: scrubAttr tested the key name and then replaced only the value. The key is as untrusted as the value — ranging over parsed data puts data in the key slot — so a credential-shaped key now takes the whole attr with it. The auth-header rule matched to end of LINE. Fail-safe for a log record and destructive for captured transcript content, which the dashboard shows users: a minified JSON tool result with an "authorization" field lost every field after it. The value now stops at a string/field terminator as well as the newline; a bare 'Authorization: Bearer <token>' line still has nothing to stop at but the newline, so the log case is unchanged. dash.RedactHeaders had no production caller — nothing in the capture path records request headers at all — so the allowlist implied a live protection that did not exist. Deleted rather than wired up, with the docs corrected to say headers are never captured; git history holds the allowlist if they ever are. scrubToken read h.Get, the FIRST value of an auth slot, while copyHeaders forwards ALL of them: two Authorization headers, provider key then our token, sent the token upstream. It now checks every value, and decides on a prefix match rather than the exact length LooksLikeToken requires — a token that lost one character was not token-shaped, so it was forwarded as a caller credential. Authentication stays strict; only the scrubbing decision is liberal. Also names the two credential classes a pattern denylist knowingly misses (base64-encoded, and prefix-less opaque keys outside a named field), so the next reader does not add speculative patterns for them. Signed-off-by: Osher-Elhadad <[email protected]>
Three findings from a security review of the tenant package, each with a test that fails without the fix. RegisterAccount treated "email_verified_at = 0" as "nobody owns this address", but migration v3 added that column with DEFAULT 0, so every account created before email auth migrates to unverified while being in daily use. An unauthenticated POST to /api/register with a colleague's address therefore installed the caller's password on a live account, locking the owner out of the dashboard (token login refuses an account that has a password) and leaving only the mailed code in the way of a full takeover. The claim is now gated on the account never having been usable — no password and no token row at all — and returns ErrEmailTaken otherwise. The v3 upgrade also stamps every account holding a live token, in the same step that adds the column, so the existing accounts are never in the claimable state; the same statement runs again as v4 for databases that already reached v3. BindAgentKey upserted ON CONFLICT DO UPDATE SET tenant_id, which moved a digest another tenant had bound to whoever asked for it, unaudited. With capture_content defaulting on, that redirects the victim's request transcripts to the thief's dashboard. Binding a digest owned by someone else is now refused, a transfer has to be an unbind by the owner followed by a rebind, keys shorter than 20 characters are rejected so low-entropy strings cannot be claimed, and bind and unbind both write an audit row. decodeHash accepted any non-zero argon2 parameters, so a poisoned row made every sign-in attempt against that account a 1 GiB allocation. Parameters above a small multiple of our own are now treated as a corrupt hash. Also orders Audit by rowid within a timestamp: one Update writes every changed field with the same millisecond, which left the order inside a change arbitrary. Signed-off-by: Osher-Elhadad <[email protected]>
…unset key_env The tenancy cache is where a tenant's frozen compaction decisions live, and it evicted on recency alone. Registration is open to a whole /8, so max+1 throwaway accounts sending one request each evicted every real tenant's state, and each victim's next turn re-wrote its cached prefix at ~11.5x the read price. Entries that have seen a second request are now last in line for eviction rather than pinned — the bound still holds, and evicting one is logged as its own case, because it means the cap itself is the binding constraint. The front entry is never the victim, so a newcomer cannot be starved by a full cache of active tenants. setKey returned the same nil for 'no key_env, caller pays' and 'key_env named but unset', so a half-finished config edit fell through to forwarding whatever the caller sent. In gateway mode that is a PLACEHOLDER — non-empty, so the 'no credential' check passed it — which published the placeholder to a third party and returned its 401 for the operator to chase. The second case is now a sentinel error and a 502 naming the upstream, with the variable name in the log only. No key_env at all still means caller-pays, unchanged. Signed-off-by: Osher-Elhadad <[email protected]>
MinAgentKeyLen refuses a provider key under 20 characters, so the 11-char bob-own-key fixture no longer binds. The rename is a merge-time break between the agent-key floor and the tests that predate it, not a behaviour change. Recorded while doing it: a real credential measured on this box is 25 characters, so the floor of 20 clears legitimate keys by only five. If any supported provider issues a shorter key, the floor is a functional refusal rather than a security win. Signed-off-by: Osher-Elhadad <[email protected]>
The panels read like documentation: a 40-word note under every heading, a
three-line paragraph under every bar, and a caption under every stat tile
restating the tile's own label. This moves the explanations behind native
<details> disclosures and keeps in the layout only what a reader cannot infer.
Copy:
- Every panel note is one line. The long version folds into a <details
class="why">, which is keyboard-operable and collapsed by default.
- The four savings denominators keep their distinct server-side labels AND
grow an always-visible `numerator ÷ denominator` line, so shortening the
prose cannot make two different ratios read as the same measurement.
- Tile sub-lines survive only where they carry a fact the label cannot: a
formula, a p95, or the gross/unique distinguisher. Six were deleted.
- Headings lose their trailing clauses ("Honest savings waterfall" →
"Savings waterfall", "Latency: context-guru vs upstream" → "Latency").
Layout and accessibility:
- Fix white-on-accent on the primary button in dark mode: 2.99:1, measured,
on four screens. New --on-accent token, dark ink on the light-blue accent.
- Fix horizontal body scroll at 360px (377px wide): the identity group in the
top bar could neither shrink nor wrap. All four widths are now clean.
- .clip applied to any element, not just td/code, so the 96-character user
agent in "Signed-in machines" stops setting that card's width.
- The bar label column is capped at 220px instead of 30%, so a bar no longer
starts a third of the way across a wide panel.
- The six request-metadata filters move behind one "More filters" disclosure,
badged with how many are set. Thirteen controls wrapped to two rows and
pushed the first number below the fold.
- The filter bar is hidden on the five views that read no filter.
Restyled what landed plain:
- Usage: capped label column, styled in-heading dimension picker, tighter
rows. The direct value labels on both bars and the always-present legend
are unchanged — blue-green is the tritan-weak pair.
- Auth: full-width primary, tracked-out 6-digit code box, amber countdown
under a minute, token fallback folded away, and the sign-in/register tabs
hidden during phase two. The countdown still measures against the server's
absolute expiry; only its styling reads the remaining seconds.
- Request drawer: 24 flat key/value pairs become four captioned bands, the
cache_control breakpoints become four labelled slots instead of one
run-on string, and a null temperature/top_p renders as italic "unset"
rather than an em dash that could be read as a dash-shaped zero.
Logs affordance: the Config tab and the request drawer carry copyable text for
the Loki-backed Grafana dashboard — the tunnel, the address, and a LogQL query
scoped to the request's own session. Deliberately not a hyperlink and not an
iframe: Grafana binds loopback, so a link would be dead until the tunnel is up,
and an iframe would mean loosening the CSP.
Fix a real regression on the way: two top-level `loadSessions` declarations, one
for the Sessions tab and one for the account's signed-in machines. The later
declaration wins, so the Sessions tab and both of its pager buttons called the
account loader — the tab rendered no rows at all and painted "Could not list
your sessions" into a Settings card. The account one is now loadMachines.
Verified in Chromium against a seeded database: 642 painted foreground/background
pairs measured for WCAG contrast across every tab in both themes, 0 failures
(tightest 4.64:1); no horizontal body scroll at 360/768/1024/1440; every new
disclosure reachable by Tab with a visible focus ring.
Signed-off-by: Osher-Elhadad <[email protected]>
cg_llm_cost_usd was the delta of the PROCESS-GLOBAL cheap-model counters across a request's lifetime, so on a multi-tenant proxy any other tenant's compaction call that returned inside that window was billed to whichever request happened to be in flight. From the row it propagated into tenant_spend, the tenant's month-to-date figure on its settings page, and cg_tenant_cg_llm_cost_usd. It was also a side channel: a tenant could infer other tenants' compaction activity from its own rows. Give each request its own cheapmodel.Sink, carried on the context, and read that in capture.finish. The context is the plumbing point that already reaches every model call — apply builds components.Ctx from it, components derive their timeouts from it, and internal/extract sees only a context.Context — so no call path can miss it silently. The process totals are untouched: /stats, the Prometheus cg_llm_* series and the benchmark harness still report what this proxy spent overall. One consequence worth naming: an observe-mode shadow run happens on the pool's context, so its spend now lands on no row instead of on some later request's row. Test: a request whose own pipeline has no model at all, with another tenant's 10000-in/2000-out call made mid-flight, was charged $0.04; now $0.00, while a request that runs its own summarizer is still charged for it. Signed-off-by: Osher-Elhadad <[email protected]>
The janitor's own doc comment has always described three rules with fairness first, but the code ran the byte rule first. DB.Prune's byte rule has no tenant column and cannot have one — a byte budget is a property of the whole file — so it deletes the oldest rows in the whole table. Reached while ONE tenant's traffic is what pushed the database over budget, it therefore evicts the quiet tenants (theirs are the oldest rows) and leaves the offender's recent history in place. Run enforceQuotas first, and reclaim the pages a quota trim frees before the byte rule measures the file: a delete leaves the pages allocated, so without the reclaim the byte rule still sees the size the offender caused and evicts anyway. The three-rule sequence moves into Recorder.janitorPass so the order lives in one place, and the comments on both rules now describe what the code does. Test: 20 old rows belonging to a quiet tenant against 400 recent rows from a tenant over its 50-row quota, with the database over its byte budget. The quiet tenant used to lose all 20 rows; it now keeps them and the byte rule has nothing left to do. Signed-off-by: Osher-Elhadad <[email protected]>
frame-ancestors, base-uri and form-action do not fall back to default-src, and nginx sets no X-Frame-Options, so the dashboard's self-only CSP left all three at their default of "anything". The session cookie is SameSite=Lax, which means a cross-site frame renders the UNAUTHENTICATED sign-in gate — so the realistic abuse is UI-redress phishing of the sign-in form rather than riding an existing session, and on a service reachable from a whole /8 with open self-registration that is worth closing. Append frame-ancestors 'none'; base-uri 'none'; form-action 'self'. The UI needs none of the three: it has no <base>, embeds no frames, and its forms carry no action and are handled by fetch. Signed-off-by: Osher-Elhadad <[email protected]>
…t's rows Three deployment-facing fixes in the hosted-mode startup path. CONTEXT_GURU_DUMP and CONTEXT_GURU_CAPTURE are now fatal in hosted mode. Both are read once at package init (proxy.capturePath, apply.dumpPath) and append to one process-wide file: no tenant column, pristine bodies, and on a path the redactor never runs. In a multi-tenant deployment that is a shared plaintext transcript of every tenant's source code, written whether or not any tenant consented to content capture. The rule existed only as prose in docs/hosted.md; it now has to survive one careless Environment= line. Single-tenant and local runs keep both hooks. DASHBOARD_MAX_ROWS_PER_TENANT defaults to 100000 instead of 0, and the shipped unit sets it explicitly. A fairness rule that has to be switched on is not a fairness rule: at 0 the janitor's quota pass returns immediately, and the only bound left is the global byte rule, which evicts the quiet tenants. 100k rows is above any plausible legitimate week against a 7-day retention window (~14k requests/day sustained) and about 10% of the 512 MiB byte budget for metric-only rows, so several heavy tenants coexist before the byte rule has anything to do. A manager can still override it per tenant. -register-domains no longer claims the address is UNVERIFIED — a mailed verification code has been mandatory since the email-auth work. What remains true, and is what the help now says, is that reachability is not entitlement. Tests boot the real main() in a subprocess: hosted mode with either variable set exits non-zero naming it, single-tenant mode still starts, the flag's usage output carries a non-zero default, and the shipped unit sets a positive one. Signed-off-by: Osher-Elhadad <[email protected]>
An observation runs on the pool, and the pool's context is
context.Background() by design — the request's is cancelled the moment the
response is written. logging.From therefore fell through to the process
default and every line the observation wrote lost the per-request logger: all
four of cg.cache_boundary, cg.component (x2) and cg.run went out with no
tenant, no route and no provider. With DEBUG on, a {tenant="X"} selector
showed that tenant's requests and none of its pipeline decisions, and
apply.BodyOpts's panic recovery — whose own comment says a panic is the line
you most want attributed to a tenant — was anonymous on exactly the path
where nobody is watching the response.
Lift the logger out of the request context before enqueueing and re-attach it
inside the job. It is a value, so it outlives the request safely; only
cancellation belonged to the context, which is why only the context is
swapped. No new field on reqInfo: the context it already carries is where the
logger lives.
The other half is telling a projection from an enforced run. `mode` is now
stamped once, on the logger, where apply resolves it — so the decisions, the
run summary, whatever a component logs, and the panic recovery all carry it,
for every caller including /compact, and no call site can forget to. Three of
the four lines had no mode at all; cg.cache_boundary passed it as an attr of
its own, and drops that now to avoid rendering the key twice.
The logs dashboard's two component panels split on mode accordingly. They are
the panels that were empty for observe traffic before this, and they would
otherwise have started silently mixing never-enforced projections into
enforced totals the moment the tenant label appeared.
internal/logging's package doc claimed every line of a request's lifecycle
carries tenant and session. It now says how work that crosses the off-path
boundary keeps it, and names the three classes of line that are not
request-scoped: pre-authentication refusals, startup, and a resource's lines
about itself. The pool's own two lines are the last of those — they hold a
job, not a request, so the tenant goes in the job key, which is the only place
they can name whose measurement was dropped.
Signed-off-by: Osher-Elhadad <[email protected]>
…as zero The breakpoint count is made BY THE PIPELINE, and in observe mode the enforced path runs no pipeline — so the four cache_bp_* columns are zero on such a row for the same reason every other trace-derived field is. Casting the sum to TEXT keyed those rows as "0", the same bucket as a request that genuinely arrived without a breakpoint: three rows (a real 0, a real 3, and an observe row whose request did carry 3) collapsed to map[0:2 3:1]. Every other dimension keys unset as "", which GroupRow.Key documents the UI as labelling unset — and dash/ui already renders `g.key || '(not set)'` in both the chart legend and the table, so no UI change is needed. It matters more here than for an obviously-empty field: a proxy running wholly in observe mode drew one full-height "0" bar over its entire traffic and read as the finding "none of my traffic sets a cache breakpoint", about traffic nobody inspected. Bypassed rows are deliberately untouched: apply counts breakpoints before it consults Bypass, so their zero is a counted zero. Signed-off-by: Osher-Elhadad <[email protected]>
…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]>
Two comments still explained themselves in terms of a cap that no longer
exists — each tenant's traffic bills the credential its own agent sends, so
there is no shared budget and nothing is ever refused over money.
- refuse()'s WARN rationale listed "a spend cap" among the reasons a request
is turned away, alongside reasons the counter actually has (rate_limit,
concurrency, auth, forbidden, no_upstream, upstream_error);
- tenant_spend justified its existence as "a cap the tenant could reset". The
table still earns its place, for the honest reason: a SUM over requests
shrinks as retention evicts history, so a REPORTED month-to-date figure
would fall while the invoice rose.
The same stale list in the refusals panel's help text went out with the
dashboard's mode split, two commits back, since it is the same file.
Comment-only, no behaviour change.
Signed-off-by: Osher-Elhadad <[email protected]>
added 24 commits
August 17, 2026 07:20
The browser was refusing registration before the server saw it: the password fields carried minlength=12, so the form's own validation was the gate people actually hit. Server, form and hint text now all say 8. 8 is the operator's chosen floor and is lower than this file would pick alone. What makes it defensible here is that the password is not the only barrier: every sign-in also needs a code mailed to the address, each verify is capped at 5 attempts before the code is destroyed, attempts are rate-limited per email and per client address, and each guess costs a 64 MiB argon2id hash. Online guessing is bounded by those. Offline guessing against a stolen hash is where a short password loses, and that is the trade. Signed-off-by: Osher-Elhadad <[email protected]>
… 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]>
… 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)
… 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]>
…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]>
… 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)
… 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)
… 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)
… 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]>
…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]>
…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]>
…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]>
Grafana was loopback-only, reachable through an ssh tunnel. Publish it on the front end at /grafana/ without publishing an admin console to 9.0.0.0/8. Two doors, and the outer one is ours. nginx auth_request asks the proxy's new GET /api/authz/grafana before forwarding anything; it answers 204 only for a manager's cg_dash session and 401/403 otherwise, so Grafana never sees a request that fails the gate — not even to render its login form, which would otherwise be a password-guessing target in front of every tenant's spend. The endpoint is one row in ctlRoutes with the existing ctlManager scope, so it reuses webPrincipal + IsManager() rather than introducing a second idea of who an administrator is, inherits the cookie-only rule (a proxy token cannot open the dashboards), and is covered by TestEveryControlRouteEnforcesItsScope as it stands. Grafana's own login remains the second door, with anonymous access off. Grafana needs GF_SERVER_ROOT_URL + GF_SERVER_SERVE_FROM_SUB_PATH to generate redirects and asset URLs under the sub-path, so the installer sets both; without them every asset 404s. That moves Grafana's API too, so grafana-status now probes /grafana/api/health — the bare path answers 301, which curl -sf reports as down. Two credential findings alongside it: - The admin password no longer rides the docker run argv, where /proc/<pid>/cmdline is world-readable to any local user for the life of the call. It goes through --env-file: 0600, root-owned, on the /run tmpfs so it never reaches a disk, removed as soon as the container exists. - 20-local.conf, documented as the home for METRICS_TOKEN, is 0600 instead of 0644 — including on boxes that already have the file, where only the content is left alone, not the mode. And the finding that installing the nginx config overwrote the live file before validating it: on a failed nginx -t the old config was already gone while nginx served the previous one from memory, so nothing looked wrong until the next reload took the front end down. It now backs up, swaps, tests, and rolls back. Deploy order: the endpoint only exists once the proxy restarts, and the gate fails closed until then — a manager sees 401 too. nginx needs no change when it does. Signed-off-by: Osher-Elhadad <[email protected]>
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)
…tion-and-control-plane
…k/8-observe-logging-and-bench-harness
…-feedback-and-manager-control
OsherElhadad
changed the base branch from
stack/8-observe-logging-and-bench-harness
to
feat/hosted-tls-and-agent-compaction
August 17, 2026 08:29
OsherElhadad
merged commit Aug 17, 2026
253bf32
into
feat/hosted-tls-and-agent-compaction
9 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. Last of nine.
Feedback. Eight star questions plus mandatory prose, each question something a manager could act on: overall, whether the agent still performs as well as before, per-agent behaviour, components, latency, observability, ease of setup, and likelihood to recommend. Per-agent questions are asked only for agents that account has actually sent traffic for, so a Claude Code user is never asked to rate Bob.
The comment minimum is enforced server-side with whitespace collapsed, so neither 50 spaces nor padded text passes; the browser counter uses the identical rule, so the counter and the server cannot disagree.
Stored in the control database, not the metrics database — the latter is a derived view that is renamed aside and rebuilt on a schema bump, and somebody's written answer is not derivable from anything.
tenant_idis deliberately not a cascading foreign key: feedback must outlive the account, so email and label are copied in at write time.Mailing is off the request path: store commits first, then delivery is attempted, so a dead or unconfigured relay costs a notification and never an answer — and
mailed_at = 0surfaces that in the product rather than only in a log.headerSafestrips CR/LF and C0 controls from recipient and subject for every mail path, since free text reaches an email.There is no read route for a plain user at all. "You said 2, the average is 4.4" is itself a disclosure about other people's answers.
Manager control. Edit any account's whole configuration (validated by the same strict loader the proxy builds with, so a typo is a 400 naming the key and nothing partially applies); disable with a reason that reaches the agent's 403; purge a tenant's storage; delete the account entirely.
Delete and purge cross both databases plus cold storage, and the order is load-bearing: objects before the index that names them, data before the account (so a failure stays retryable instead of orphaning rows nothing answers to), then a second sweep because capture is async. Both require the email or id typed back and write an audit row that outlives the account. A manager cannot delete themselves.
A/B testing, with its limits in the payload. A variant is a label on a set of accounts that selects nothing, so assigning one cannot break an agent. There is deliberately no variant column on the metrics table — that needs a schema bump, which in this repo renames the whole database aside, and a mutable label should not cost anyone their history. Per-variant rollups fold each account's existing aggregates. The confounds are stated on-screen above the table and shipped in the API payload, so the numbers cannot be quoted apart from their limits: assignment is not randomised, workloads are not held constant, per-request cost is not per-task cost, and today's label retro-tags past traffic. No significance test.
Passwords. Own change requires the current one; self-service reset; manager-initiated reset that mails the owner a code and can neither see nor set the password — a manager who could set one could sign in and read that user's transcripts.
tenant.SetPasswordis no longer dead code whose comment claimed a flow that did not exist.Two infrastructure bugs found while in there: the control plane had no table-driven scope test (scope is now data, enforced by a wrapper before each handler), and
dash's in-memory DSN omittedforeign_keys(1)— soON DELETE CASCADEwas off in every test while on in production.