Repository navigation
feat(activity): work sessions and the failure timeline (Spec 124 PR-1) - #1918
Merged
Merged
Conversation
Audit trail for unattended agent runs: every call belongs to a work session, sessions are kept a week and pruned whole (bodies before rows), each session carries failure facts, upstream events join the timeline, read through Web UI and CLI. Review round 1 (opencode gpt-6.1-sol) findings are applied. Round 2 was interrupted and has not returned a verdict.
REST tool calls, 2026-07-28 MCP requests and a second credential on a shared connection had no work session of their own. The work session is now resolved at the emit site from the request: principal with the credential generation, client name or REST surface, and the optional X-MCPProxy-Run label. - tracker: run name key field, Touch (idle clock per attempt), daily bound on named sessions per principal - session store: one work session per credential key on a connection - auth: a pending rotated secret authenticates with its own prefix - attribution carries work session, owning user and run name to every row, including limiter sheds
storage.AttemptRoleOf classifies a row as the counted row of an attempt, a failure and a policy block, with no state besides the row. - a blocking policy decision emitted next to a tool_call row (generation change, review not recorded, output sanitisation) goes through emitActivityCompanionDecision and is marked Companion - builtin management refusals are classified proxy_policy - a limiter rejection carries the attempt id its dispatch path minted, not the transport request id that sibling attempts share
…ntion (spec 124 D3, D4) Storage writes a per-session index entry and the session summary in the transaction that writes the activity row. Summaries keep attempts, failures and policy blocks per server, with the last failure's class, tool and reason. - one-time backfill of rows written before this feature, pairing old completion and blocked-decision rows; missing summaries are rebuilt at start - retention: summaries by age (session_retention_days, default 7, no count cap); over the size cap, bodies of the oldest rows go first, then rows outside the window, then whole sessions, then the last session is trimmed - a shortfall record says when the caps could not hold the window - activity_max_records default 100000 -> 400000 - new activity type upstream_event registered on every surface BREAKING (behaviour): under the size cap the oldest rows now lose their argument and response bodies before any row is deleted.
A failed call now has its cause next to it: connection lost, process exited, OAuth refresh failed, login required, connection restored. - upstream/types: each state mutation records a Transition under the state lock with its time; one drain delivers them in order (the existing callback is dispatched sync on some paths and async on others and carries no time) - oauth: an audit observer where the refresh actually runs reports every refresh that was sent and failed, once per flight; the refresh manager numbers schedule installs and accepted failures per server so a login-required mark cannot be reopened or cleared by a late notification - runtime: events are written synchronously with the time of the change, the diagnostics code and its fixed message, never the raw error; repeats collapse per minute and per owner, at most 120 rows per server per hour - owned upstream events are readable only by their owner and administrators on the activity list, summary, export and detail
GET /api/v1/work-sessions, /work-sessions/{id} and /work-sessions/{id}/timeline.
- list: failed only (policy blocks in or out), token, client, profile, run,
error class, time range, sort by last failure or last activity
- timeline: rows and the upstream events of the servers the session called,
in time order, positioned at first_failure, failure:<n>, row:<id> or end
with up to 250 rows either side; bodies omitted unless asked for; the
lifetime failure count is given when earlier failures are no longer stored
- scope: unlike /api/v1/sessions these are open to agent tokens. A caller
sees its own sessions, with every value recomputed from the servers in its
reach; a foreign session, one with nothing in reach and a missing id answer
with the same not found
…indow (spec 124 D7) GET /api/v1/diagnostics and mcpproxy doctor gain activity_retention: the window, whether a work session inside it lost rows, the cause, the start of the oldest complete session and the setting to raise. Administrators only. Silent in the CLI when there is no shortfall.
…ec 124 PR-1) - docs: activity-log (work sessions, run name, upstream events, what a cap removes and in which order, the shortfall), rest-api (three doors), agent-tokens (one token per agent) - e2e: the morning-after scenario through REST in test-api-e2e.sh - frontend: unit tests for the session_retention_days field (restart flag) and the upstream_event type in the System view
…124) The project of a connection that disclosed its workspace (basename only) travels on the attribution to the row and the session summary. Benchmarks for SC-006: the session list and one timeline page cost the same with the log doubled (2.7 ms vs 2.8 ms for 1,000 sessions; 4.0 ms vs 4.0 ms for a page of a 50,000-row session).
- a run name rejected by the daily bound is no longer cached or touched under the rejected name; the store caches under the effective key - a retry after a failed connection-record write resolves the retrying credential's own session instead of inheriting the first credential's - the runtime's work-session tracker is created once under concurrent first use (resolution now happens on request goroutines) - an unpersisted connection pins one session per credential provisionally, so every row of a prompt request agrees - the principal uses a 96-bit generation from the secret's hash; the display prefix has only four random characters - the invalid-run-name warning set is bounded
- ownership reads a legacy row's credential from its internal arguments, so a mixed legacy session becomes ownerless instead of staying the first credential's - a whole-session removal marks the summary in its first batch, is hidden from readers and is finished at the next start; the shortfall is recorded before the first row goes - expiry is re-checked in its first transaction - the running byte count follows the summaries the pass rewrites - one bounded, chunked scan per pass measures the log and nominates rows by sniffing the stored bytes; the acting steps re-read and re-check. The body-stripping watermark is gone, so a late older row is still considered - stripping keeps the internal identity arguments of legacy rows - the truncated start is the earliest row still stored - a record cap of one is a cap - the last failure's server and facts are selected in one deterministic pass - the connection count is the number of distinct connections - the backfill never writes more than one batch per transaction
- a full transition queue folds two adjacent records into one (with a count) instead of dropping the oldest; a loss and a recovery stay apart - the hourly row bound is kept per hour of the event, so a late event does not reset it; repeats merge from 100 rows an hour, and past 120 an event with nothing of its kind and owner to merge into is not recorded - the collapser forgets rows, hours and servers that can no longer matter - an established stdio connection that fails is a process exit; it never carries the exit-before-initialize code - the numbered token-saved notification is sent outside the manager's lock - a refresh failure carries its diagnostics code when it has one
…imeline Both sides added activity types (upstream_event here, skill_access on main): the CLI system view test and the Web UI type lists keep both. NewMCPProxyServer keeps both start-up calls. unit-tests.yml takes main's 60m timeouts (#1928 raised them too). ROADMAP.md and the swagger files are regenerated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dumbris
added a commit
that referenced
this pull request
Nov 18, 2026
… PR-A Spec 124 belongs to 124-session-failure-timeline (#1918), so this spec moves to 126 (free on main and every open branch). Schema 17 is still unclaimed. PR-A is now instrumentation only (FR-033..FR-040): install anchor with install_origin/install_age, per-window completion counters kept apart from dispatch (upstream_outcomes), window coverage, a starter classifier and a sticky success scope. The receiver copies the new counters into heartbeat_events, and mcpproxy-dash owns the cohort query that matches new installs across days 0-6 and 7-13 and reports coverage gaps as rows. Onboarding facts move to PR-B at the next free schema version. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- oauth: a reschedule that arrives after the schedule was given up does not re-arm it (a transient failure racing a terminal outcome). - activity summary: a skill_access row (Spec 125) is not a tool call; it goes to the residual like an upstream event, so Usage errors equal Activity errors + blocked for administrators too. - work sessions: an administrator-only row type never joins a work session, so its time, row count or position cannot show through the session doors to a scoped caller. - config: session_retention_days is restart-gated in the core as well; the window is set once at startup and both settings UIs say so. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- storage: an administrator-only row stores no work-session id, so retention never counts it as part of a live session it was never indexed into, and the work_session_id filter names no session whose timeline lacks it. - activity summary: every administrator-only row type goes to the residual (a blocked skill is not a refused call), alongside upstream events. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…re; the cause of a session that starts during an outage Release QA F1: a call to a server that is not connected was always recorded as network / "could not be reached", including a server that is up and waits for a login (logged out, parked for sign-in, failed on OAuth). managed.SignInRequired is now the one rule for the class of such a call (both not-connected call paths and the code_execution sub-call, which recorded proxy_internal) and for the upstream event: a logout and a restart into "OAuth authorization required" now record login_required. A network failure is never a login requirement, even with an earlier OAuth error flag left set. The session reason for auth without an upstream status reads "The upstream server needs a login." Release QA F2: a session that failed on a server which was already down when it started had no cause row (FR-023 span rule). The timeline now places the latest event of each such server from before the start ahead of the start row, marked precedes_session, while no connection_restored followed it; same owner rule (FR-025), reach rule and failure positions. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- events: only a change into the error state or a logout's disconnect is a login requirement; a retry into Connecting that still carries the old login error is not (it reopened a closed requirement on every re-login). - sign-in rule: only transport failures (refused, reset, DNS, TLS, timeout, cancelled, NETWORK_*) count as network; an HTTP status such as 401 is an answer from a reachable server and leaves an OAuth failure a login need. - F2: an event from before the session is evidence only when it is a connection event (lost, process exited, login required), happened after this core process started (the recovery after a restart is not recorded), no recovery happened later (rows compared by last_at, since repeats merge into a row), and the session's failure on that server is network or auth. - code_execution: the override applies only to the managed client's not-connected refusal (new ErrClientNotConnected); a retired instance or a moved generation keeps its own class. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- F2: the open event is the connection row that happened last across the whole bounded walk, compared with every recovery by last_at: a recovery that merged into an older row still closes a newer loss. - F2: the gate is any network or auth failure on the server in the session (partition UnavailableFailure), not only its last failure. - F1: an HTTP answer that says nothing about credentials (5xx, 429, 404, legacy SSE) is never a login need, even with a stale OAuth error flag. - doc comment of ErrConnectionGenerationChanged restored; docs describe the narrowed rules. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- the event from before the session must explain the failure: a network failure is explained by connection_lost / process_exited, an auth failure by login_required (the refresh manager can raise one while the connection stays up). Partition flags NetworkFailure / AuthFailure replace UnavailableFailure; the query takes the kinds per server. - a repeat merged into a row after the session started is not known to be before it: such a row is judged by its first occurrence, so a recovery during the session does not hide the cause from before it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…res (F2 round 4) Opus round 4 on a482840: - the clamp of last_at to the session start applies to recoveries only: a loss repeated during the session merges into its row from before it, which the span walk does not show, so that row is the cause and counts at its last repeat. - login_required is no longer offered as a cause from before the session: a token save ends a login requirement without writing a row, so an earlier one cannot be judged; a call that waited for a login already says so on its own row (F1). AuthFailure is dropped; NetworkFailure remains. - docs: one row per server, network failures only, the merged-row rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…2 round 5) Opus round 5 on b6d70ff: a loss counts at its last repeat only up to the end of the session's span, so a loss merged into a pre-session row after the session ended cannot bring back a loss a recovery had closed. The storage function's comment and tests now say the kinds are the caller's (the timeline asks for connection_lost / process_exited). Co-Authored-By: Claude Opus 5.5 <[email protected]>
TestStartBackgroundMonitoring_IsIdempotent compared runtime.NumGoroutine with a baseline. Under -shuffle a goroutine left by an earlier test ended during the measurement and the count fell below the baseline (4 vs 5). Count the backgroundHealthCheck goroutines of this client from the stacks instead; the test still fails when the idempotency guard is removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dumbris
enabled auto-merge (squash)
November 18, 2026 17:05
The zero-calls check counted every request the fake upstream received. Clients left by earlier tests keep sending DELETE / close requests to closed ports, and when the kernel reuses one for this fixture the check failed (seen on #1921 and #1918). Count only non-DELETE requests to the configured /mcp endpoint, which every dial by the core starts with, and log the ignored ones. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dumbris
disabled auto-merge
November 18, 2026 18:25
…ust POST /mcp Follows 23fadb5. Counting only non-DELETE requests to /mcp leaves two gaps: a real request from the proxy under test that is a DELETE, or an OAuth request the proxy derives from the target's origin (/.well-known/..., /authorize, /token, /register), is ignored; and /mcp is a path other tests' clients use too, so a leftover client's POST to a reused port still counts. The fake upstream now lives at a path unique to the fixture (/mcp-e2e-<random>). Every request on a path containing that token counts, whatever its method or headers, and so do the origin-derived OAuth endpoints. Anything else cannot have been built from this fixture's config: it is recorded by method and path only (no headers or session IDs) and logged, and the failure message lists both sets. TestTPAFetchFixture_ForeignCloseVersusCallsToTheConfiguredTarget reproduces the stray: a real mcp-go client holding a legacy session closes after its server's port was rebound to the fixture, and its DELETE / is recorded, not counted; deliberate POST, session-carrying DELETE, path-derived and root OAuth discovery and /register on the fixture all count. #1918 CI run 44349461004 logged 1,335 refused DELETE close requests of this kind; what its two counted requests were is not recorded and is not claimed here.
Dumbris
enabled auto-merge (squash)
November 18, 2026 18:29
Dumbris
added a commit
that referenced
this pull request
Nov 18, 2026
Dumbris
disabled auto-merge
November 18, 2026 21:15
TestCallToolsRunsInParallel used 50ms calls against a computed 500ms serial time. At the default max_parallel of 8 that is two 50ms waves, so the batch had only 75ms of fixed headroom for VM setup, first-use warmup and goroutine wake-ups. The shuffled -race job on a loaded runner spent 113ms there (212.85ms vs 175ms). One injected 115ms stall reproduces it locally (228ms). SC-001 (specs/096-batched-call-tools/spec.md) asks for 10 calls with a fixed 300ms latency, at the default max_parallel, to finish in under 35% of a measured serial call_tool() loop. The test now measures exactly that, after one warm-up execution. The same 115ms stall then gives 726ms against a 1.05s budget. The idle ratio is 0.20. It also pins the default to the spec's 8, checks that no more than 8 calls are in flight, and checks that all 20 calls reached the stub. Mutations still fail: default 3 (1.21s vs 1.05s), default 4 (pin), max_parallel 3 (1.21s). Test-only; the runtime is unchanged.
TestApproveWithBlockNeverDispatchesBlockedTool timed out on Linux amd64 (job 135158464590). It failed at the wait for a worker to see TOOL_BLOCKED, after the direct probe just before it had already succeeded. The fixture runs two upstream managers with independent connection counters; production has one. The direct probe re-binds the StateView DiscoveryEpoch to the proxy manager's live client on every poll, but the worker wait did not. When the unquarantiner's background discovery pass re-stamped the epoch after the probe returned, every worker got the fail-closed "tool discovery has not completed" refusal for the whole 15s and never reached the disabled-tool gate. Injecting one stale re-stamp after the probe reproduces it: the old test fails "Condition never satisfied" after about 16s, as in CI, and the new one passes. The worker wait now re-binds through the same helper. Only worker calls count, and the helper neither counts nor dispatches. The workers are joined on every path, so a failed require no longer leaves them running past the test, and both failure messages carry the last outcome. The zero-dispatch assertion is unchanged.
…ver the real push TestToolsListChanged_TrustedServer_DoesNotJoinPreChangeList failed on Ubuntu (job 135193801169): expected "changed", got "approved", in 0.27s. Its stage server advertised tools.listChanged. Since #1915 (GH #1910) that gives the client a standing GET stream, so the test's own DeleteTools/AddTool also pushed a real list_changed: two notification-driven runs, not one. When the real push took the per-server discovery marker first, the test's manual onUpstreamToolsListChanged was coalesced and returned at once, and the record was read before the owning run had stored "changed". A 300ms head start for the real push reproduces it 3/3. The owning run was fresh and did store "changed", so production behaviour is correct. The test's server no longer advertises the capability, so the manual call is the only notification. The test now: - marks its own run through a context value and requires that run to have happened, instead of counting every run; - arms only after connect-time discovery has run and released the marker, since that discovery could otherwise absorb the notification. With the head start the test passes. Reverting the fix fails it on the own-run check, and reintroducing the joining bug (a fresh list adopting the in-flight one) fails it on the status. TestToolsListChanged_AdvertisedPush_HoldsChangedContract covers the transport path the first test now avoids. A trusted manual-mode upstream advertises the capability, changes its approved tool and pushes the notification itself. The test waits for discovery to settle, then requires "changed", the old ApprovedHash kept and the previous description recorded. It fails without the capability and with trust_mode auto. Test-only. Both tests pass 50/50 under -race, 20/20 with GOMAXPROCS=1, and 10/10 with -tags server -shuffle=on.
…in a fresh process Two failures on #1918's merge ref with main (job 135221641659), both test-only. 1. TestToolsListChanged_TrustedServer_DoesNotJoinPreChangeList timed out in requireConnectDiscoverySettled, which waited for a run of the connect hook. Startup discovery is not always connect-owned. When another trigger holds the per-server marker (the session re-initialise path calls the notification handler), the connect trigger is coalesced and its follow-up runs the owner's closure, so the connect hook never runs. Injecting a startup notification call reproduces CI's message with the old helper (1/3); the new one passes 20/20 under the same injection. requireDiscoverySettled does not care which trigger ran discovery. For 200ms without a break it requires: - the StateView records a completed discovery on the live connection epoch; - the marker is free and no follow-up is pending; - the baseline is still approved. On timeout it names the condition that was still false. The own-run assertion still catches a late owner. 2. TestSelectableProfileNames_PinOutcomesDoSameWork read 1 / 47 / 35 allocations at tolerance 0, where the code does 1 / 1 / 1. AllocsPerRun counts every malloc in the process, and a full internal/server run on this tree still has 967 live network-recovery watchers (one per upstream.Manager an earlier test never shut down) and 2218 goroutines when the test runs. The inflation did not reproduce on demand locally, so this is not claimed as the proven mechanism. runInFreshProcess reruns the test, and its sibling TestProfileMiddleware_RefusalWorkIndependentOfFleet, alone in a fresh copy of the test binary, at the same tolerance. A deliberate extra allocation in selectableNames still fails through the child (1 vs 2). Shutting down the managers that internal/server tests leak is a separate follow-up.
Dumbris
added a commit
that referenced
this pull request
Nov 19, 2026
…1934) ## Summary `TestRetire_HTTPDialParked_OldEndpointReceivesNothing/http/remove` failed once in the shuffled unit-test job on #1931 (job 135134947938, seed `1795038088268204092`) with `expected: 0, actual: 3` requests and 0 Authorization headers. This PR makes the retire fixture count only its own endpoint's traffic. It is a test-only change; no production code is touched. ## Classification: fixture contamination, not a retirement defect - **The retired instance did not send it.** The instance under test only ever sends `Authorization: Bearer qa-secret…`, and the CI run counted 0 Authorization headers next to the 3 requests. - **The test is clean in isolation.** On main `898572804`: 300/300 runs under `-race` and 100/100 with `GOMAXPROCS=1` (6 subtests each). The full package with the CI seed passes 3/3 on macOS and 6/6 on Linux (Docker, ephemeral port range narrowed to 1,024 ports). - **Senders seen directly.** In a scratch copy, every upstream request was tagged with its server and creating test, and a trap bound the free ports during the retire subtests. With only `internal/upstream` running, the trap caught 0 requests. With `server`, `runtime`, `httpapi` and four more packages running in parallel, as `go test ./...` does on CI, it caught 535 requests in two iterations: - `POST /` `initialize` with no Authorization, tagged e.g. `github|TestCallTool_ProfileV3_RestDispatchPreservesTypedRefusal`. 29 of the 30 tagged tests are in `internal/server`; the 30th tag carried a server name but no test name. - `GET /` listen streams and `DELETE /` closes with stale session ids. - **Which these are.** Clients from `internal/server` tests keep reconnecting to the ports of their own closed counting upstreams. When the OS reuses one of those ports for this fixture, the traffic lands here. - **What is shown and what is inferred.** The multi-package run shows this traffic exists and has the CI failure's shape: requests without credentials, three per reconnect attempt. That this exact traffic caused the historical CI run is inferred, not traced; the CI job kept no per-request record. The same class as the stray-client isolation in #1918's `dc864055d`, here across processes. ## Fix - The fixture serves its endpoint under a unique path (`/fx-<random>/mcp`, or `/fx-<random>/sse` with `WithStaticBasePath`). - It counts a request when its path carries that token, with or without credentials, or when it carries the fixture's own credential on any path. `httpServerConfig` now gives each fixture a unique bearer. - Origin-level OAuth paths are counted whoever sends them, so the fixture fails closed. These are `/.well-known/*` and mcp-go's default `/authorize`, `/token` and `/register`, which an OAuth attempt may reach without the token or a credential. This was review round 1, from gpt-6.1-sol. - Everything else is answered 404 and kept in `strays()`. - The handler and every field are in place before `Start`. - The zero-request assertions are unchanged. New tests: - `TestRetire_HTTPDialParked_StrayTrafficOnThePortIsNotTheOldEndpoint` runs the parked-dial scenario while a stranger sends `POST /`, `GET /` and `DELETE /` to the port. With the old fixture it fails exactly like CI, for both http and sse: `expected: 0, actual: 3`. - `TestCountingUpstream_CountsItsEndpointAndItsCredentialAnywhere` holds the controls. A request to the endpoint without credentials is counted. The fixture's credential on another path is counted. Origin-level OAuth paths are counted. Strangers on other paths, with or without their own credential, are not counted. ## Verification (macOS, `-race` unless noted) | Run | Result | |---|---| | `-run 'Retire\|CountingUpstream' -count=20` | ok | | same, `GOMAXPROCS=1 -count=10` | ok | | full package, CI seed, CI skip list | exit 0 | | full package, CI seed, under CPU load, 3 runs | exit 0 ×3 | | full package, `-shuffle=on -count=2` | ok | | golangci-lint v2 (`.github/.golangci.yml`), bare and `--build-tags server`, new from `origin/main` | 0 issues each | One earlier full-package run with the CI seed reported `FAIL` while both lint runs loaded the machine. Its output was not captured: the command kept only the last line. The later runs listed above used the final handler ordering and all passed. That failure is reported here as uncaptured, not as explained. A note on the barrier itself: disabling the retired checks in `dialgate`, plus connect cancellation in the managed client, still produced no traffic in the parked scenario, because further guards stop the dial. That is unchanged by this PR. The fixture's detection is covered by the control test above. ## Review | Round | Reviewer | SHA | Result | |---|---|---|---| | 1 | opencode `gpt-6.1-sol`, fixture chunk | `8b0057b05` | 1 medium: origin-level OAuth paths uncounted. Fixed in `6e7f49ad8` | | 2 | `gpt-6.1-sol`, fixture / tests | `6e7f49ad8` | CLEAN / 2 P2: exact stray counts, missing controls | | 2 | Claude Opus 5.5 | `6e7f49ad8` | same medium, plus 2 low. Fixed in `467da1fd5` | | 3 | Claude Opus 5.5 | `467da1fd5` | CLEAN: 11 filter mutations killed; real connects and the full OAuth fallback counted, 0 strays | | 3 | `gpt-6.1-sol`, tests | `467da1fd5` | 1 P3: shared stray marker. Fixed in `c1690a366` | | 4 | `gpt-6.1-sol` | `c1690a366` | P3 fixed; 1 P2: unbounded hook waits. Fixed in `e62c7610c`. The first try returned no verdict and was not counted | | 5 | `gpt-6.1-sol` | `e62c7610c` | CLEAN | | 5 | Claude Opus 5.5 | `e62c7610c` | CLEAN: 13 filter and recording mutations killed | Follow-ups, not blocking: - Add a control row for a foreign credential on the endpoint path, so the `auth` counter's "any Authorization" rule is pinned. Opus low; the request counter already catches it. - Rewrap one 113-character comment line. ## Not in this PR The `internal/server` tests that leave reconnecting clients behind are the source of the stray traffic. They are a separate cleanup. ## Merge condition Both reviewers are clean on `e62c7610c`. Merge that exact SHA once CI is green; if the head moves, review it again. Auto-merge is not armed.
Dumbris
added a commit
that referenced
this pull request
Nov 19, 2026
…ient outlives its test (#1936) ## Summary Test-only. `internal/server` fixtures created `upstream.Manager`s and never shut them down. Each one kept its network-recovery watcher (#1931) running, and its clients kept reconnecting to their fixture's closed port, for the rest of the package run. Those reconnects are the stray traffic that #1918 (fresh-process allocation tests) and #1934 (retire-fixture isolation) worked around. This PR fixes the source. The numbers below come from the end of a full `go test -v -race -timeout 60m -coverprofile … -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/server/` run: | | goroutines | `(*networkRecovery).run` | `startOAuthEventMonitor` | lumberjack `millRun` | |---|---|---|---|---| | main 58a824e | 3196 | **1273** | 44 | 276 | | this branch | 739 | **0** | 0 | 0 | To find the sources, I labelled each watcher goroutine with the test frame that created it (a temporary local patch, not committed). Every leaked watcher came from a direct `upstream.NewManager` in a test file. `createTestProxyWithRuntimeCfg` alone accounted for about 70% of them. None came from a runtime or server that wasn't closed. ## Changes - **`newTestUpstreamManager` / `shutdownUpstreamOnCleanup`** (`upstream_fixture_cleanup_test.go`): all 37 direct `upstream.NewManager` calls in the package now call `ShutdownAll` when the test ends. This includes the shared `createTestProxyWithRuntimeCfg`. - **`stopUpstreamBeforeFixtureClose`**: some fixtures start their upstream after the manager exists: `startCountingUpstream` and the prompt-upstream helpers in `mcp_prompt_scope_test.go` and `scope_retained_effects_test.go`. They now remove the client in a cleanup registered after the listener's close, so it runs first: the client disconnects while the stub still listens and never redials a closed port. The old `DisconnectAll` cleanups in the prompt loops ran after the fixture had already closed. - `mcp_code_execution_test.go` (package `server_test`) defers the shutdown so it runs before the storage close it depends on. - `scope_latency_test.go` inlines the shutdown, because `scope-latency.yml` copies that one file onto the merge-base checkout, where the helper doesn't exist. - **Guard**: a new `TestMain` (`leak_guard_main_test.go`) fails an otherwise passing run if any `(*networkRecovery).run` goroutine is still alive after the last test. It polls for up to 10s and prints the first 5 stacks. I checked that it catches a leak: with the helper's shutdown commented out, `-run TestAggregatedPrompt_ScopeUsesCanonicalOwner` fails with "2 upstream.Manager network-recovery watcher(s) still running". - `MCPPROXY_NETWORK_RECOVERY=off` is not set anywhere. No production code changed. The leaks were all in test fixtures. ## Found, not fixed (production shutdown gap) The 739 goroutines that remain are mostly 227 × `(*Server).forwardRuntimeStatus` and 227 × `(*Server).listenForRoutingModeRefresh`. `NewServer` starts both (`server.go:488`, `:504`), and `Server.Shutdown` stops neither: - `listenForRoutingModeRefresh` ranges over a `SubscribeEvents` channel that is never unsubscribed. - `forwardRuntimeStatus` ranges over `Runtime.statusCh`, which nothing closes. They sit idle on a channel receive and send no network traffic. They are harmless in a real process, which exits after `Shutdown`. In tests they are still 2 leaked goroutines per server. I left them for a separate production change. ## Verification - Full `internal/server` race run: `ok … 1457.449s coverage: 83.5%`, and the guard passes. - `golangci-lint run --config .github/.golangci.yml --new-from-rev=origin/main ./...`, bare and `--build-tags server`: 0 issues.
Dumbris
added a commit
that referenced
this pull request
Nov 20, 2026
`roadmap.yaml` had no epics after Spec 117. This PR adds them and regenerates `ROADMAP.md`. - **Shipped:** 118 auto-rescan (#1689), 118 pin visibility boundary (#1684, #1688, #1821), 119 (#1740), 120 (#1781), 122 (#1818) and 123 (#1886, #1887, #1888, #1891). - **In review:** 121 install surfaces (#1711). There is no `spec:` link yet because its folder exists only on the PR branch. - **In progress:** 124 (PR-1 #1918 done; PR-2 CLI and PR-3 Web UI to do) and 125 (spec plus PR-1..3 done; PR-4 Web UI to do). Merged PRs are listed as done child tasks, so `--check-github` doesn't flag a merged PR under an in-progress epic. - **Spec-only PRs:** 127 (#1943), 128 (#1944) and 129 (#1945). Merge this after #1943, #1944 and #1945. Until then, `--check-github` reports their `spec:` links as unresolved; `--check`, the pre-commit hook, passes. Not covered: Spec 126 (#1940, open) and the unsynced tasks.md checkboxes for 123 and 124.
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.
Pull Request
Description
Spec 124 "Session Failure Timeline", PR-1 of 3 (record and keep). PR-2 adds the CLI and PR-3 the Web UI; neither is in this change. Spec, plan and tasks are in
specs/124-session-failure-timeline/.Why. When an agent run fails, the operator has to rebuild what happened from separate activity rows, and the rows that explain it (a server dropped, a login expired) are not recorded next to the calls. This PR gives every recorded attempt a work session and records upstream events as rows of that timeline.
What changed
internal/server/worksession_resolve.go): principal with the credential generation (including the matched secret of a staged rotation), client name or REST surface, and theX-MCPProxy-Runlabel. One work session per credential key on a connection; a daily bound on named sessions.storage.AttemptRoleOfdecides what a row contributes. A blocking decision next to atool_callis a companion and is not counted twice; builtin management refusals areproxy_policy.SaveActivitywrites the row, thework_session_rowsindex entry and thework_sessionssummary (per-server partitions, lifetime vs stored counters) together. One-time backfill and a startup repair.storage.RunActivityRetentionis one pass: summaries bysession_retention_days(default 7), bodies of the oldest rows first, rows outside the window, whole sessions, then a trim of the last one, with a shortfall record.activity_max_recordsdefault is now 400000.upstream_event(internal/runtime/upstream_events.go) from ordered state-transition capture (internal/upstream/types/transition.go), the refresh coordinator's audit observer and numbered refresh-manager notifications. Rows carry theMCPX_*code and a fixed message only, collapsed per minute and owner.GET /api/v1/work-sessions,/{id},/{id}/timeline. A scoped caller sees its own sessions, with facts recomputed from the servers in its reach, and a uniform 404 otherwise.activity_retentionsection.session_retention_dayssettings field and theupstream_eventtype label.docs/features/activity-log.md"Work sessions and the failure timeline",docs/api/rest-api.md"Work sessions".No new dependencies.
For the reviewer
activity_max_recordsdefault; a REST tool call's activity row now carries surfacerest; in the 24h activity summary anupstream_eventrow is counted under "other", not under errors or success, so Activity errors + blocked still equals Usage errors.internal/oauth/refresh_manager.go). This was the last fix on the branch and is the part that has had the least review.code_executionsub-call that finishes after its session was reaped does not reinstate it; a folded transition record keeps counts and the end state, not the exact interleaving; an event row keeps the time of the first occurrence delivered.errorstill lists connection events while the Errors tile does not count them (PR-3); a real-fixture test of what the state manager emits (T051).origin/mainis merged in (merge commit7bd0a7055);oas/was regenerated withmake swagger.Testing