diff --git a/CLAUDE.md b/CLAUDE.md index 393882ea5..b91d4d8f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,6 +146,7 @@ tail -f ~/Library/Logs/mcpproxy/main.log # main log (macOS; Linux: ~/.mcpproxy/ - **Windows installer**: [docs/github-actions-windows-wix-research.md](docs/github-actions-windows-wix-research.md). **Prerelease** (`next` branch + `v*-rc.*` tags, opt-in, off stable channels): [docs/prerelease-builds.md](docs/prerelease-builds.md). ## Recent Changes +- 126-day-two-activation (PR-A): Go 1.26, backend + docs — telemetry schema 17, instrumentation only (no onboarding, UI or API change). Install anchor: `storage.EnsureInstallAnchor` (own bucket `install_anchor`, written once in `runtime.New` after the Spec 080 shutdown marker and Spec 123 OAuth boot sweep, before any other startup write, only when `config.db` held no record other than `meta/schema_version` at open, `BoltDB.WasEmptyAtOpen`; never from onboarding writes; recorded with telemetry off; read once per process for both `day_two` and `window_age`). `upstream_outcomes {succeeded, unusable, succeeded_non_starter, coverage, window_age}` (`internal/telemetry/upstream_outcomes.go`): one outcome per LOGICAL call that dispatched (dispatch counts requests), begun right after `noteUpstreamDispatched` and deferred (`upstreamOutcome` in `internal/server/mcp_upstream_telemetry.go`) on the wrapper, direct routing and `code_execution` sub-calls, guarded by an AST test; part of the drained window (retries byte-identical); `coverage` from the persisted `outcome_window_undelivered` marker (`outcome_window.go`: set by the first outcome after start or a Drain, cleared after a 2xx only if nothing was counted since that drain, both under the outcome window's own mutex, never `deliveryMu`), `window_age` = install age when the window opened (start or Drain), `install_origin: fresh` personal only. `day_two {install_origin, install_age, success_scope_ever}` personal only (`day_two.go`: UTC calendar-date buckets; `success_scope.go` forward-only ordinal in the activation bucket). `runtime.StarterClassifier` (default false, `SetStarterClassifier` for PR-B) + `Runtime.RecordUpstreamOutcome`. `ScanForPII` closed-object rule `day_two_field_invalid`. Docs: `docs/features/telemetry.md` "Schema v17". **No new dependencies.** - 125-skills-over-mcp (PR-3): Go 1.26, backend + CLI + docs — approved skills reach agents through three read-only built-ins, registered only while `enable_skills` is on (`MCPProxyServer.RefreshSkillsAvailability`: default registry, call-tool, code-execution and direct surfaces; never `/mcp/s/`, never from `code_execution`): `retrieve_skills(query, limit)`, `load_skill(id, offset, limit, version)`, `read_skill_file(id, path, offset, limit, version)` (`internal/server/mcp_skills.go`). Everything comes from the approved copy through `Runtime.AvailableSkill` / `AvailableSkillFile` / `SearchAvailableSkills` (`internal/runtime/skills_agent.go`); one refusal `skill not found: ` for every unavailable reason; reach = `resolveActiveProfileWithSource` → `serverInScope`, tool policy not applied. Search: memory-only Bleve in `internal/skills/index`, one index per reach, every match re-checked against its record. Paging: parts of ≤60,000 bytes with `Version:` in the header. Output policy (`mcp_skills_output.go`): block/redact/strip on the whole file before paging, also on names, descriptions and file names; skills build a detector when a policy is switched on after start. Activity type `skill_access` (administrator-only, like `skill_quarantine_change`). Scoped REST: `GET /api/v1/servers/{id}/skills{,/content}` answer an agent token with available skills from the approved copy through the same policy. Records of skills a listing did not name are bounded (200 per server). Docs: `docs/features/skills.md` "Skills for agents". **No new dependencies.** - 125-skills-over-mcp (PR-2): Go 1.26, backend + CLI + docs — the skills approval gate, still administrator-only and offered to no agent. `decideSkill` (`internal/runtime/skills_quarantine.go`) is the whole status rule: `manual` holds new and changed skills, `scan` approves a new skill only on a clean and complete scan and always holds a changed one, `auto` / `quarantine_enabled:false` approve; a hash equal to the approved one restores approved; `Blocked` survives everything. Scan (`skills_scan.go`): every text file in ≤48 KiB chunks through `ScanToolMetadataVerdict`, after the reads and outside the upstream timeout, 45 s per refresh with follow-up refreshes, 1 MiB and 2 min per skill (`size_cap` / `time_limit` are kept, `coverage` is retried), result bound to the content hash. Review-bound decisions (`skills_approval.go`): `ApproveSkillsReviewedAt` (expected hash per skill + incarnation, whole request refused with nothing written) and `SetSkillsBlockedAt`, records-only writes (`storage.UpdateSkillApprovals`). REST `POST /api/v1/servers/{id}/skills/approve|block|unblock` (409 `review_out_of_date` / `server_replaced`, 422 `skill_unusable`), CLI `mcpproxy skills approve|block|unblock`, `skills show --diff`. Activity type `skill_quarantine_change` is administrator-only on every activity read door and on SSE (`storage.IsAdminOnlyActivityType`). Docs: `docs/features/skills.md` "Reviewing skills". **No new dependencies.** - 125-skills-over-mcp (PR-1): Go 1.26, backend + docs — opt-in Skills over MCP (`enable_skills`, per-server `expose_skills`), visible to administrators only and offered to no agent yet. New leaf `internal/skills` (wire types, `skill://` URI rules, digest + frontmatter verification, `sk1-` content hash); upstream reads through raw `skills/list` / `skills/get` + `ReadResource` with a per-request response limit (`internal/transport/response_limit.go`); bbolt buckets `skill_approvals` + `skill_files` are in the purge set; runtime catalog (`internal/runtime/skills_catalog.go`: single-flight refresh, budgets, capture-ordered apply); admin-only REST `GET /api/v1/servers/{id}/skills{,/content}` and `POST …/skills/refresh` (scoped tokens get 403 before any runtime call; `skills.changed` SSE is dropped for scoped callers); CLI `mcpproxy skills list|show|refresh`. Docs: `docs/features/skills.md`. **No new dependencies.** diff --git a/docs/features/telemetry.md b/docs/features/telemetry.md index f74b92154..ebed85acc 100644 --- a/docs/features/telemetry.md +++ b/docs/features/telemetry.md @@ -10,7 +10,7 @@ MCPProxy collects anonymous usage statistics to help improve the product. This p ## What is collected -MCPProxy sends a **daily heartbeat** containing only aggregate, non-identifying information. The current schema is **version 16** (`schema_version: 16` in the JSON payload); the schema is forward-compatible so older consumers simply ignore fields they don't recognize. +MCPProxy sends a **daily heartbeat** containing only aggregate, non-identifying information. The current schema is **version 17** (`schema_version: 17` in the JSON payload); the schema is forward-compatible so older consumers simply ignore fields they don't recognize. A field counts only on heartbeats whose `schema_version` introduced it: before that version it is **not measured**, never zero or false (see [Coverage](#coverage-a-field-counts-only-from-its-schema-version)). | Field | Example | Purpose | |-------|---------|---------| @@ -47,6 +47,8 @@ MCPProxy sends a **daily heartbeat** containing only aggregate, non-identifying | `feature_flags.idp_provider` | `none` | The configured identity-provider **family** for server-edition SSO (schema v13) — fixed enum `google` / `github` / `microsoft` / `oidc` / `none`. The kind only: never the issuer URL, tenant, client id or display name. `none` when the block is disabled or unset | | `member_count_bucket` | `1-10` | Number of server-edition user accounts, bucketed (schema v13) — fixed enum `0` / `1-10` / `11-100` / `101-1000` / `1000+`. `0` on the personal edition (no counter is installed); omitted only when the counter fails. A count only, never an identity. (Named `member_…`, not `user_…`: the anonymity scanner blocks the home-dir basename as a substring of the whole payload, and `user` is the username of every `USER user` container image) | | `env_markers.is_container` | `true` | Unchanged in v13; read together with the fields above to see how server-edition installs are deployed | +| `upstream_outcomes` | `{"succeeded":"1-10","unusable":"0","succeeded_non_starter":"1-10","coverage":"full","window_age":"d0_6"}` | Completed upstream calls in this counter window, by outcome (schema v17). Bucket labels, a coverage flag and the install age when the window opened — never a name or a timestamp. Both editions; `window_age` only on a fresh personal install. See [Schema v17](#schema-v17--dispatch-vs-completion-and-install-cohorts-spec-126) | +| `day_two` | `{"install_origin":"fresh","install_age":"d7_13","success_scope_ever":"non_starter"}` | Install origin, install age bucket and lifetime success scope (schema v17). Closed enums only; personal edition only. See [Schema v17](#schema-v17--dispatch-vs-completion-and-install-cohorts-spec-126) | | `preflight` | `{"filter_diag_emitted_24h":3,"availability_block_24h":2,"availability_block_reasons_24h":{"server_quarantined":2},"discovery_omission_24h":5}` | Preflight baseline counters (issue #969) — counts only, reason map keyed by a fixed enum. Omitted entirely when nothing was counted. See below | The `server_protocol_counts` map uses a **fixed enum of keys** (`stdio`, `http`, `sse`, `streamable_http`, `auto`) — server names and URLs are never included. Unknown or misconfigured protocol values are bucketed into `auto`. @@ -265,6 +267,57 @@ Five reset-on-accept counters count the refresh lifecycle (the daily check of th **What is deliberately absent.** The bundle's age, `generated_at`, the last-checked and last-activated times, the next-check time, the fetch URL and host, refusal reasons and digests are never transmitted. The freshness view ("how old is the bundle in the fleet") is computed on the receiver by joining `bundle_sequence` against the release timeline, not reported by the client. The anonymity scanner rejects any `tpa_scanner` key outside the whitelist, and the five counters above must be non-negative integers (strings, negatives and floats block the heartbeat). With telemetry disabled (`MCPPROXY_TELEMETRY=false`, `DO_NOT_TRACK`, the CLI or config opt-out) none of these keys, and no `tpa_scanner` object, is sent. +## Schema v17 — dispatch vs completion, and install cohorts (Spec 126) + +Schema v17 is instrumentation only: it adds two objects and changes nothing else. They exist so that new installs can be followed from their first week to their second, and so that "an upstream was called" and "an upstream call worked" are never inferred from each other. + +### Dispatch vs completion + +Two instruments now sit side by side, and they count different things: + +| Instrument | Since | Counts | Unit | +|-----------|-------|--------|------| +| `upstream_tool_call_count_bucket` | v14 | **Dispatches**: requests the core client handed to the transport | Requests. A request repeated after an upstream session was re-initialized counts twice | +| `upstream_outcomes` | v17 | **Completions**: logical calls that dispatched at least one request, by outcome | Logical calls. The same session-recovery repeat is one call and one outcome | + +A logical call is one `call_tool_*` call, one direct-routing call, or one `code_execution` sub-call. A call refused before dispatch (validation, quarantine, a profile or policy, a disconnected server, the concurrency limiter, a moved connection generation) records neither a dispatch nor an outcome. An operator replaying a stored call from the REST API or Web UI records neither. + +### `upstream_outcomes` (both editions) + +A reset-on-accept counter window, like `upstream_tool_call_count_bucket`: it is part of the window keyed by `heartbeat_id`, frozen until an accepted (2xx) heartbeat, and a retry of an undelivered window re-sends it byte-identical. Calls made while a send is being retried go to the next window. + +| Field | Values | Meaning | +|-------|--------|---------| +| `upstream_outcomes.succeeded` | `0` / `1-10` / `11-100` / `101-1000` / `1000+` | Logical calls with a **usable** result: no error, no `isError: true` answer, and not withheld by an output policy (output sanitisation or output-schema validation). The same predicate as `activation.first_real_tool_call_ever` | +| `upstream_outcomes.unusable` | same buckets | Logical calls that dispatched but ended without a usable result: a transport or upstream error, `isError: true`, or a result an output policy withheld | +| `upstream_outcomes.succeeded_non_starter` | same buckets | The subset of `succeeded` that is not on the starter server. No starter exists yet, so it equals `succeeded`; the field is sent anyway so the instrument stays the same when one ships | +| `upstream_outcomes.coverage` | `full` / `partial` | `full` when the counts cover the whole time since the previous accepted heartbeat. `partial` for the first window of a process whose predecessor left recorded outcomes undelivered, and once for the first schema-17 start of an install whose `install_origin` is `existing`. A local marker tracks this: the first outcome after process start, or after each window is detached for sending, sets it; an accepted heartbeat (the shutdown flush included) clears it only when no outcome was recorded after that heartbeat's window was detached (a send detaches its window when it starts, so calls made while it is in flight are still unsent when it is accepted). A fresh install, and a plain restart after a delivered window, are `full` | +| `upstream_outcomes.window_age` | `d0_6` / `d7_13` / `d14_plus` | The install age (as `day_two.install_age` below) at the moment the window **opened**: process start, or the moment the previous window was detached for sending. Present only when `day_two.install_origin` is `fresh`; never next to `existing`, and always absent on the server edition. The install anchor is read once per process, so `day_two` and `window_age` always agree. Frozen with the window, so a retry carries the age it opened at | + +### `day_two` (personal edition only) + +State, read fresh at every heartbeat build; it is not part of the counter window. Omitted on the server edition. + +| Field | Values | Meaning | +|-------|--------|---------| +| `day_two.install_origin` | `fresh` / `existing` | `fresh` when the local data store holds an **install anchor**: a UTC time written once, right after the data store opens at startup, only when `config.db` held no prior data when it was opened (no file, an empty file, or no record in any bucket other than the schema version every open writes). An install upgraded from a build without the anchor has none and reports `existing`; it is never counted as a new install. The anchor is recorded whatever the telemetry setting and is never sent — only the buckets derived from it are | +| `day_two.install_age` | `d0_6` / `d7_13` / `d14_plus` | The difference in **UTC calendar dates** between the anchor's date and the date the heartbeat is built (constant within one UTC date). A negative difference (clock skew) counts as `d0_6`. Present only when `install_origin` is `fresh` | +| `day_two.success_scope_ever` | `none` / `starter_only` / `non_starter` | Whether this install ever got a usable upstream result, and where. Persisted locally, recorded whatever the telemetry setting, and moves forward only (`none` → `starter_only` → `non_starter`). On an `existing` install it covers the time since the upgrade | + +`days_since_install` (v7) is unchanged, but it is not a cohort key: it is stamped on the first telemetry-enabled heartbeat, so it cannot tell an upgrade or a late opt-in from a new install. Use `install_origin` and `install_age` for cohorts. + +**Privacy.** Both objects carry closed enums and bucket labels only: no server or tool name, path, timestamp, free text or new identifier. The anonymity scanner treats them as closed objects and blocks the heartbeat on an unknown key, an out-of-enum value, a non-string value, a nested object, a `window_age` next to `install_origin: existing`, or an `install_age` that does not match the origin; the violation never echoes the offending key or value. With telemetry disabled nothing is sent; the anchor and `success_scope_ever` are still recorded locally. + +### Coverage: a field counts only from its schema version + +A field is measured only on heartbeats with `schema_version >=` the version that introduced it. When a heartbeat is older, the field is **not measured** — do not read its absence as `false`, `0` or `none`. For the day-two questions that means: + +- no `install_origin` / `install_age` below v17 (fall back to the first heartbeat date, and say so); +- no completion counts below v17 (only dispatch-based activity, v14 and later, can be measured, and it is reported under that name); +- `coverage: partial` windows are reported as their own gap, not silently merged. + +Later onboarding fields (the starter, second-client and summary fields) each ship with the release that produces them, at the next free schema version, and follow the same rule. + ## Preflight baseline counters (issue #969) The `preflight` sub-object measures two things the proxy currently does silently: diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 2da6e241e..5416bc339 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -203,6 +203,13 @@ type Runtime struct { refreshManager *oauth.RefreshManager // Proactive OAuth token refresh updateChecker *updatecheck.Checker // Background version checking telemetryService *telemetry.Service // Anonymous usage telemetry (Spec 036) + // starterClassifier decides starter-ness of a (server, incarnation) for the + // schema-17 completion counters (Spec 126 FR-037). nil: the default, which + // answers false. See upstream_outcome.go. + starterClassifier atomic.Pointer[starterClassifierHolder] + // successScopeReached caches the success_scope_ever ordinal this process + // has persisted, so RecordUpstreamOutcome skips the store once reached. + successScopeReached atomic.Uint32 // bundleRefresher is the TPA bundle refresh scheduler (Spec 087 / Spec 101 // US3 B19), registered by the server and started in @@ -541,6 +548,16 @@ func New(cfg *config.Config, cfgPath string, logger *zap.Logger) (*Runtime, erro zap.String("key_id", oauthTokenKey.ID()), zap.Int("sealed_plaintext_rows", sealed)) } + // Spec 126 FR-033: record the install anchor right after the shutdown + // marker (Spec 080 FR-010 keeps that the first DB operation) and the + // Spec 123 OAuth boot sweep, and before every other startup write, before + // telemetry is wired (SetTelemetry reads the anchor once, for day_two and + // window_age) and before the HTTP server and MCP initialisation. Emptiness + // was decided when the store opened, so those earlier writes cannot change + // it; an early write only shrinks the window in which a crash would leave + // a new store without an anchor. Whatever the telemetry opt-out setting. + ensureInstallAnchor(storageManager, logger) + // Close any stale sessions from previous runs if err := storageManager.CloseAllActiveSessions(); err != nil { logger.Warn("Failed to close stale sessions on startup", zap.Error(err)) @@ -4287,6 +4304,10 @@ func (r *Runtime) SetTelemetry(version, edition string) { if err := funnelStore.RecordActivity(db, time.Now().UTC()); err != nil { r.logger.Debug("Failed to record funnel activity at startup", zap.Error(err)) } + + // Spec 126 (schema 17): install anchor provider for day_two and + // window_age, and the first counter window's coverage. + r.wireDayTwoTelemetry() } } diff --git a/internal/runtime/upstream_outcome.go b/internal/runtime/upstream_outcome.go new file mode 100644 index 000000000..1dc97f8fd --- /dev/null +++ b/internal/runtime/upstream_outcome.go @@ -0,0 +1,130 @@ +package runtime + +import ( + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry" +) + +// ensureInstallAnchor writes the install anchor when config.db held no prior +// data at open (Spec 126 FR-033). It never rewrites an anchor and never +// creates one on an existing store. A failure is logged and startup goes on: +// the install then reports install_origin "existing", never a guess. +func ensureInstallAnchor(sm *storage.Manager, logger *zap.Logger) { + if sm == nil { + return + } + if _, _, err := sm.EnsureInstallAnchor(time.Now()); err != nil { + logger.Warn("Failed to record the install anchor", zap.Error(err)) + } +} + +// StarterClassifier decides whether an upstream server is the starter server +// (Spec 126 FR-037): the one the starter door added, identified locally by name +// AND incarnation, so a user's own later add of the same catalog entry (a new +// incarnation) is never starter traffic. Names are used only locally; the +// telemetry registry receives a boolean. +// +// PR-A installs no starter, so the default answers false for every server. +// PR-B replaces it through SetStarterClassifier. Implementations must be safe +// for concurrent use and cheap: IsStarter runs once per successful upstream +// call. +type StarterClassifier interface { + IsStarter(serverName string, incarnation int64) bool +} + +// noStarterClassifier is the PR-A default: no server is the starter. +type noStarterClassifier struct{} + +func (noStarterClassifier) IsStarter(string, int64) bool { return false } + +// starterClassifierHolder lets an interface value live in an atomic.Pointer. +type starterClassifierHolder struct{ c StarterClassifier } + +// SetStarterClassifier installs the starter classifier; nil restores the +// default, which answers false. +func (r *Runtime) SetStarterClassifier(c StarterClassifier) { + if r == nil { + return + } + if c == nil { + r.starterClassifier.Store(nil) + return + } + r.starterClassifier.Store(&starterClassifierHolder{c: c}) +} + +// StarterClassifier returns the installed classifier, or the default. +func (r *Runtime) StarterClassifier() StarterClassifier { + if r != nil { + if h := r.starterClassifier.Load(); h != nil && h.c != nil { + return h.c + } + } + return noStarterClassifier{} +} + +// RecordUpstreamOutcome records the outcome of ONE logical upstream call that +// dispatched at least one request (Spec 126 FR-035, FR-038). usable is true +// for a usable result: no error, no isError:true, not withheld by an output +// policy. The dispatch paths call it once per logical call, through +// MCPProxyServer.noteUpstreamOutcome; a call refused before dispatch never +// reaches it. +// +// The outcome goes to the reset-on-accept counter window (sent only with +// telemetry on). A usable result also advances the persisted +// success_scope_ever, which is local state recorded whatever the opt-out +// setting. nil-safe, and a no-op before SetTelemetry. +func (r *Runtime) RecordUpstreamOutcome(serverName string, incarnation int64, usable bool) { + if r == nil || r.telemetryService == nil { + return + } + starter := usable && r.StarterClassifier().IsStarter(serverName, incarnation) + telemetry.RecordUpstreamOutcomeOn(r.telemetryService.Registry(), usable, starter) + if !usable { + return + } + // The scope only moves forward, so once this process has seen it reach + // the target no read is needed (a busy install would otherwise open a + // bbolt read transaction per usable call). + target := uint32(telemetry.SuccessScopeNonStarter) + if starter { + target = uint32(telemetry.SuccessScopeStarterOnly) + } + if r.successScopeReached.Load() >= target { + return + } + if db := r.telemetryService.ActivationDB(); db != nil { + if err := telemetry.RecordSuccessScope(db, starter); err != nil { + r.logger.Debug("activation: RecordSuccessScope failed", zap.Error(err)) + return + } + for { + cur := r.successScopeReached.Load() + if cur >= target || r.successScopeReached.CompareAndSwap(cur, target) { + break + } + } + } +} + +// wireDayTwoTelemetry connects the schema-17 instruments to storage (Spec 126 +// FR-034, FR-036): the install-anchor reader for day_two and window_age, and +// the first counter window's coverage, decided from the store's state at open +// and the persisted undelivered-window marker. Called from SetTelemetry after +// the activation store is wired. The anchor itself is written earlier, by +// ensureInstallAnchor in New, right after the store opens (after the Spec 080 +// shutdown marker and the Spec 123 OAuth boot sweep). +func (r *Runtime) wireDayTwoTelemetry() { + sm := r.storageManager + if sm == nil || r.telemetryService == nil { + return + } + r.telemetryService.SetInstallAnchorProvider(func() (time.Time, bool, error) { + return sm.InstallAnchor() + }) + r.telemetryService.InitOutcomeWindow(sm.WasEmptyAtOpen()) +} diff --git a/internal/runtime/upstream_outcome_test.go b/internal/runtime/upstream_outcome_test.go new file mode 100644 index 000000000..a521e1e1d --- /dev/null +++ b/internal/runtime/upstream_outcome_test.go @@ -0,0 +1,199 @@ +package runtime + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry" +) + +// Spec 126 FR-035 to FR-038 (T082): the runtime side of the completion +// counters — the starter classifier, the outcome entry point, and the +// telemetry wiring (install anchor provider, first-window coverage). + +type stubStarter struct { + name string + inc int64 +} + +func (s stubStarter) IsStarter(name string, inc int64) bool { return name == s.name && inc == s.inc } + +func newOutcomeRuntime(t *testing.T, dataDir string, telemetryOn bool) *Runtime { + t.Helper() + cfg := newPreChurnTestConfig(dataDir) + cfg.Telemetry = &config.TelemetryConfig{Enabled: &telemetryOn} + rt, err := New(cfg, filepath.Join(dataDir, "config.json"), zap.NewNop()) + require.NoError(t, err) + return rt +} + +// FR-037: in PR-A the default classifier answers false for every server. +func TestStarterClassifier_DefaultAnswersFalse(t *testing.T) { + rt := newOutcomeRuntime(t, t.TempDir(), true) + defer rt.Close() + c := rt.StarterClassifier() + require.NotNil(t, c) + require.False(t, c.IsStarter("time", 1)) + require.False(t, c.IsStarter("", 0)) + + rt.SetStarterClassifier(stubStarter{name: "time", inc: 3}) + require.True(t, rt.StarterClassifier().IsStarter("time", 3)) + require.False(t, rt.StarterClassifier().IsStarter("time", 4), "a different incarnation is not the starter") + rt.SetStarterClassifier(nil) + require.False(t, rt.StarterClassifier().IsStarter("time", 3), "nil restores the default") +} + +// One outcome per call reaches the counter window and the lifetime scope; a +// starter success is excluded from succeeded_non_starter. +func TestRecordUpstreamOutcome_CountsAndScope(t *testing.T) { + rt := newOutcomeRuntime(t, t.TempDir(), true) + defer rt.Close() + rt.SetTelemetry("v0.0.0-test", "personal") + rt.SetStarterClassifier(stubStarter{name: "time", inc: 1}) + db := rt.TelemetryService().ActivationDB() + + rt.RecordUpstreamOutcome("time", 1, true) + got := rt.TelemetryRegistry().Snapshot().UpstreamOutcomes + require.Equal(t, "1-10", got.Succeeded) + require.Equal(t, "0", got.SucceededNonStarter, "the starter's success is not non-starter traffic") + scope, err := telemetry.LoadSuccessScope(db) + require.NoError(t, err) + require.Equal(t, telemetry.SuccessScopeStarterOnly, scope) + + rt.RecordUpstreamOutcome("time", 2, true) // a user's own re-add: another incarnation + got = rt.TelemetryRegistry().Snapshot().UpstreamOutcomes + require.Equal(t, "1-10", got.SucceededNonStarter) + scope, err = telemetry.LoadSuccessScope(db) + require.NoError(t, err) + require.Equal(t, telemetry.SuccessScopeNonStarter, scope) + + rt.RecordUpstreamOutcome("github", 1, false) + require.Equal(t, "1-10", rt.TelemetryRegistry().Snapshot().UpstreamOutcomes.Unusable) + scope, err = telemetry.LoadSuccessScope(db) + require.NoError(t, err) + require.Equal(t, telemetry.SuccessScopeNonStarter, scope, "an unusable result never moves the scope") +} + +// FR-038 / T080: the scope is recorded with telemetry disabled. +func TestRecordUpstreamOutcome_ScopeRecordedWithTelemetryOff(t *testing.T) { + rt := newOutcomeRuntime(t, t.TempDir(), false) + defer rt.Close() + rt.SetTelemetry("v0.0.0-test", "personal") + rt.RecordUpstreamOutcome("github", 1, true) + scope, err := telemetry.LoadSuccessScope(rt.TelemetryService().ActivationDB()) + require.NoError(t, err) + require.Equal(t, telemetry.SuccessScopeNonStarter, scope) +} + +// Before telemetry is wired the call is a no-op (no panic). +func TestRecordUpstreamOutcome_NoTelemetryService(t *testing.T) { + rt := newOutcomeRuntime(t, t.TempDir(), true) + defer rt.Close() + rt.RecordUpstreamOutcome("github", 1, true) + var nilRT *Runtime + nilRT.RecordUpstreamOutcome("github", 1, true) +} + +// SetTelemetry wires the install anchor into day_two and the first window's +// coverage from the store's state at open (FR-034, FR-036). +func TestSetTelemetry_WiresDayTwoAndCoverage(t *testing.T) { + t.Run("fresh install", func(t *testing.T) { + // The real startup order on an empty data directory: New records the + // anchor right after the store opens, SetTelemetry reads it once. + rt := newOutcomeRuntime(t, t.TempDir(), true) + defer rt.Close() + require.True(t, rt.StorageManager().WasEmptyAtOpen()) + _, ok, err := rt.StorageManager().InstallAnchor() + require.NoError(t, err) + require.True(t, ok, "runtime.New records the anchor on an empty store") + rt.SetTelemetry("v0.0.0-test", "personal") + + p := rt.TelemetryService().BuildPayload() + require.NotNil(t, p.DayTwo) + require.Equal(t, "fresh", p.DayTwo.InstallOrigin) + require.Equal(t, "d0_6", p.DayTwo.InstallAge) + require.Equal(t, "none", p.DayTwo.SuccessScopeEver) + out := rt.TelemetryRegistry().Snapshot().UpstreamOutcomes + require.Equal(t, telemetry.OutcomeCoverageFull, out.Coverage) + require.Equal(t, "d0_6", out.WindowAge) + }) + t.Run("existing install, first start of this build", func(t *testing.T) { + dir := t.TempDir() + // An older build's store: data, no anchor, no marker. + older, err := storage.NewManager(dir, zap.NewNop().Sugar()) + require.NoError(t, err) + require.NoError(t, older.GetDB().Update(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(storage.UpstreamsBucket)).Put([]byte("github"), []byte(`{"name":"github"}`)) + })) + require.NoError(t, older.Close()) + + rt := newOutcomeRuntime(t, dir, true) + defer rt.Close() + require.False(t, rt.StorageManager().WasEmptyAtOpen()) + _, ok, err := rt.StorageManager().InstallAnchor() + require.NoError(t, err) + require.False(t, ok, "an upgraded store never gets an anchor") + rt.SetTelemetry("v0.0.0-test", "personal") + + p := rt.TelemetryService().BuildPayload() + require.NotNil(t, p.DayTwo) + require.Equal(t, "existing", p.DayTwo.InstallOrigin) + require.Empty(t, p.DayTwo.InstallAge) + out := rt.TelemetryRegistry().Snapshot().UpstreamOutcomes + require.Equal(t, telemetry.OutcomeCoveragePartial, out.Coverage) + require.Empty(t, out.WindowAge) + }) + t.Run("server edition", func(t *testing.T) { + rt := newOutcomeRuntime(t, t.TempDir(), true) + defer rt.Close() + rt.SetTelemetry("v0.0.0-test", "server") + require.Nil(t, rt.TelemetryService().BuildPayload().DayTwo) + require.Empty(t, rt.TelemetryRegistry().Snapshot().UpstreamOutcomes.WindowAge) + }) +} + +// FR-035: replay stays outside both the dispatch and the outcome counts, as +// it is today. Replay is an operator re-run of a recorded call, not an agent's +// logical call, so ReplayToolCallWithOptions must reach no telemetry counter. +func TestReplayToolCall_RecordsNoUpstreamOutcome(t *testing.T) { + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, "runtime.go", nil, 0) + require.NoError(t, err) + var body *ast.BlockStmt + ast.Inspect(file, func(n ast.Node) bool { + fn, ok := n.(*ast.FuncDecl) + if !ok || fn.Name.Name != "ReplayToolCallWithOptions" || fn.Body == nil { + return true + } + body = fn.Body + return false + }) + require.NotNil(t, body, "ReplayToolCallWithOptions not found in runtime.go") + forbidden := map[string]bool{ + "RecordUpstreamOutcome": true, + "RecordUpstreamOutcomeOn": true, + "RecordUpstreamTool": true, + "RecordUpstreamToolOn": true, + "RecordSuccessScope": true, + "TelemetryRegistry": true, + } + ast.Inspect(body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && forbidden[sel.Sel.Name] { + t.Errorf("ReplayToolCallWithOptions calls %s: replay must record no dispatch or outcome", sel.Sel.Name) + } + return true + }) +} diff --git a/internal/server/install_anchor_startup_test.go b/internal/server/install_anchor_startup_test.go new file mode 100644 index 000000000..ab5bab5e2 --- /dev/null +++ b/internal/server/install_anchor_startup_test.go @@ -0,0 +1,69 @@ +package server + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// Spec 126 FR-033 (T003 f, T004): server construction records the install +// anchor on a store that was empty at open, with telemetry DISABLED, before +// telemetry is wired; a later start keeps it; and the schema-17 day_two block +// reads it. +func TestServerStartup_RecordsInstallAnchorWithTelemetryDisabled(t *testing.T) { + restoreScannerWiring(t) + dir, err := os.MkdirTemp("", "install-anchor-*") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + + off := false + newCfg := func() (*config.Config, string) { + cfg := config.DefaultConfig() + cfg.DataDir = dir + cfg.Listen = "127.0.0.1:0" + cfg.APIKey = "install-anchor-key" + cfg.Telemetry = &config.TelemetryConfig{Enabled: &off} + path := filepath.Join(dir, "mcp_config.json") + require.NoError(t, config.SaveConfig(cfg, path)) + return cfg, path + } + + cfg, path := newCfg() + before := time.Now().UTC() + srv, err := NewServerWithConfigPath(cfg, path, zap.NewNop()) + require.NoError(t, err) + anchor, ok, err := srv.runtime.StorageManager().InstallAnchor() + require.NoError(t, err) + require.True(t, ok, "a new data directory records the anchor at startup, telemetry off") + require.False(t, anchor.Before(before.Add(-time.Second))) + + // The first heartbeat of the first process: day_two and the first + // counter window (what the first send drains) both say fresh / d0_6. + p := srv.runtime.TelemetryService().BuildPayload() + require.NotNil(t, p.DayTwo) + require.Equal(t, "fresh", p.DayTwo.InstallOrigin) + require.Equal(t, "d0_6", p.DayTwo.InstallAge) + window := srv.runtime.TelemetryRegistry().Snapshot().UpstreamOutcomes + require.Equal(t, "d0_6", window.WindowAge) + require.Equal(t, "full", window.Coverage) + require.NoError(t, srv.Shutdown()) + time.Sleep(50 * time.Millisecond) + + cfg2, path2 := newCfg() + srv2, err := NewServerWithConfigPath(cfg2, path2, zap.NewNop()) + require.NoError(t, err) + t.Cleanup(func() { + _ = srv2.Shutdown() + time.Sleep(50 * time.Millisecond) + }) + again, ok, err := srv2.runtime.StorageManager().InstallAnchor() + require.NoError(t, err) + require.True(t, ok) + require.True(t, again.Equal(anchor), "a later start never changes the anchor") +} diff --git a/internal/server/mcp.go b/internal/server/mcp.go index c5e60721b..0c77e784f 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -3769,6 +3769,8 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. dispatchCtx = p.withReviewDirtyRecheck(dispatchCtx, serverName) result, err := p.dispatchOnEpoch(dispatchCtx, certified, toolName, args) p.noteUpstreamDispatched(dispatchCtx) // one attempt per request that reached the transport + outcome := p.beginUpstreamOutcome(dispatchCtx, serverName, callInc) + defer outcome.record() // Spec 126 FR-035: one outcome on every exit below callerr.Observe(ctx, result, err) fwdOut := fwdSink.Outbound() duration := time.Since(startTime) @@ -4093,6 +4095,7 @@ func (p *MCPProxyServer) handleCallToolVariant(ctx context.Context, request mcp. // policy gates (sanitisation, output validation) above. if activityStatus == "success" { p.recordRealToolCallSuccess() + outcome.markUsable(forwarded, nil) } return forwarded, nil diff --git a/internal/server/mcp_code_execution.go b/internal/server/mcp_code_execution.go index 3f76f727b..f158bfffb 100644 --- a/internal/server/mcp_code_execution.go +++ b/internal/server/mcp_code_execution.go @@ -1070,6 +1070,8 @@ func (u *upstreamToolCaller) callTool(ctx context.Context, serverName, toolName result, err = client.CallTool(dispatchCtx, toolName, args) } u.proxy.noteUpstreamDispatched(dispatchCtx) // each JS sub-call counts its own requests; nil-safe + outcome := u.proxy.beginUpstreamOutcome(dispatchCtx, serverName, callInc) + defer outcome.record() // Spec 126 FR-035: one outcome on every exit below; nil-safe callerr.Observe(ctx, result, err) // Release QA F1: this path has no not-connected check before the call, // and the managed client's "client not connected" error classifies as a @@ -1126,6 +1128,7 @@ func (u *upstreamToolCaller) callTool(ctx context.Context, serverName, toolName } // Activation: only after the output policy above let the result through. u.proxy.noteUpstreamSuccess(result, err) + outcome.markUsable(result, err) duration := time.Since(startTime) // Record the tool call with timing and result. Issue #935: code_execution diff --git a/internal/server/mcp_routing.go b/internal/server/mcp_routing.go index fdf95a80e..451f21360 100644 --- a/internal/server/mcp_routing.go +++ b/internal/server/mcp_routing.go @@ -823,12 +823,18 @@ func (p *MCPProxyServer) makeDirectModeHandler(entry *directCatalogEntry) mcpser dispatchCtx, fwdSink := headerfwd.WithSink(ctx) dispatchCtx = callerr.BeginDispatch(dispatchCtx) // Spec 113-c FR-042 dispatchCtx = p.withReviewDirtyRecheck(dispatchCtx, serverName) + // Spec 126 FR-037: the incarnation the call is dispatched against, read + // BEFORE the dispatch so a remove + re-add while the call is in flight + // cannot reclassify its outcome against the replacement. + callInc := p.toolCallIncarnation(serverName) if epoch, ok := p.liveConnectionEpoch(serverName); ok { result, err = p.upstreamManager.CallToolOnEpoch(dispatchCtx, qualifiedName, args, epoch) } else { result, err = p.upstreamManager.CallTool(dispatchCtx, qualifiedName, args) } p.noteUpstreamDispatched(dispatchCtx) // one attempt per request that reached the transport + outcome := p.beginUpstreamOutcome(dispatchCtx, serverName, callInc) + defer outcome.record() // Spec 126 FR-035: one outcome on every exit below callerr.Observe(ctx, result, err) fwdOut := fwdSink.Outbound() @@ -994,6 +1000,7 @@ func (p *MCPProxyServer) makeDirectModeHandler(entry *directCatalogEntry) mcpser // Activation: same success contract as call_tool_* (usable result only). if activityStatus == "success" { p.recordRealToolCallSuccess() + outcome.markUsable(forwarded, nil) } return forwarded, nil diff --git a/internal/server/mcp_upstream_telemetry.go b/internal/server/mcp_upstream_telemetry.go index bdb6dfb7a..190bdc853 100644 --- a/internal/server/mcp_upstream_telemetry.go +++ b/internal/server/mcp_upstream_telemetry.go @@ -3,6 +3,7 @@ package server import ( "context" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry" "github.com/smart-mcp-proxy/mcpproxy-go/internal/transport" ) @@ -49,3 +50,70 @@ func (p *MCPProxyServer) noteUpstreamSuccess(result interface{}, err error) { } p.recordRealToolCallSuccess() } + +// upstreamOutcome is the schema-17 completion outcome of ONE logical upstream +// call (Spec 126 FR-035): one per call that dispatched at least one request, +// whichever exit the call takes. The dispatch paths begin it right after +// noteUpstreamDispatched and defer record() at once, so every later return — +// upstream errors, an isError answer, the output-sanitisation and +// output-validation blocks, the moved-generation and review-dirty refusals — +// records exactly one outcome. Only the success point calls markUsable, after +// the output policy checks, at the same point first_real_tool_call_ever is +// stamped. Dispatch counts requests (a session-recovery repeat counts twice); +// this counts the logical call once. +type upstreamOutcome struct { + p *MCPProxyServer + server string + incarnation int64 + dispatched bool + usable bool + recorded bool +} + +// beginUpstreamOutcome reads whether the logical call dispatched anything from +// the call recorder on dispatchCtx (the context handed to the upstream call). +// Zero dispatches — refused by the managed client, shed by the limiter, +// cancelled in the admission queue — means no outcome at all. +func (p *MCPProxyServer) beginUpstreamOutcome(dispatchCtx context.Context, serverName string, incarnation int64) *upstreamOutcome { + return &upstreamOutcome{ + p: p, + server: serverName, + incarnation: incarnation, + dispatched: transport.CallRecorderFrom(dispatchCtx).Snapshot().Dispatches > 0, + } +} + +// markUsable marks the outcome usable when the result is: no error, a result, +// and no isError:true answer. Callers invoke it after their output policy +// checks, exactly where noteUpstreamSuccess / recordRealToolCallSuccess run. +func (o *upstreamOutcome) markUsable(result interface{}, err error) { + if o == nil || err != nil || result == nil || upstreamAnsweredWithError(result) { + return + } + o.usable = true +} + +// record reports the outcome once; later calls are no-ops. Deferred by the +// dispatch paths. +func (o *upstreamOutcome) record() { + if o == nil || o.recorded || !o.dispatched || o.p == nil { + return + } + o.recorded = true + o.p.noteUpstreamOutcome(o.server, o.incarnation, o.usable) +} + +// noteUpstreamOutcome hands one outcome to the runtime, which applies the +// starter classifier (FR-037), counts it in the reset-on-accept window and +// advances the persisted success_scope_ever (FR-038). Unit tests that observe +// a bare registry (telemetryRegOverride) get the count without a classifier. +func (p *MCPProxyServer) noteUpstreamOutcome(serverName string, incarnation int64, usable bool) { + if p == nil { + return + } + if p.telemetryRegOverride == nil && p.mainServer != nil && p.mainServer.runtime != nil { + p.mainServer.runtime.RecordUpstreamOutcome(serverName, incarnation, usable) + return + } + telemetry.RecordUpstreamOutcomeOn(p.telemetryRegistry(), usable, false) +} diff --git a/internal/server/socket_e2e_test.go b/internal/server/socket_e2e_test.go index b7e0928e4..702ec9c15 100644 --- a/internal/server/socket_e2e_test.go +++ b/internal/server/socket_e2e_test.go @@ -76,8 +76,14 @@ func TestE2E_TrayToCore_UnixSocket(t *testing.T) { // Start server in background ctx, cancel := context.WithCancel(context.Background()) - // Note: Not using defer cancel() to avoid race condition panic during shutdown - _ = cancel + // Shut the server down before the deferred socketE2EMutex unlock (defers + // run last-in first-out), so its upstream manager's network-recovery + // watcher does not outlive the test (TestMain leak guard). Shutdown runs + // first, so the context-cancel shutdown path finds it done and skips. + defer func() { + _ = srv.Shutdown() + cancel() + }() serverReady := make(chan error, 1) go func() { @@ -214,13 +220,10 @@ func TestE2E_TrayToCore_UnixSocket(t *testing.T) { assert.Contains(t, line, "SSE connection established") }) - // Cleanup - // Note: Server shutdown is handled by avoiding cancel() call above - // The test framework will clean up when the test exits. _ = serverReady // Socket file will be cleaned up when tmpDir is removed by test framework or system cleanup - t.Log("Test completed successfully - server shutdown handled by test framework") + t.Log("Test completed successfully") } // TestEndToEnd_DualListener_Concurrent tests concurrent requests over both TCP and socket @@ -262,8 +265,14 @@ func TestE2E_DualListener_Concurrent(t *testing.T) { require.NoError(t, err) ctx, cancel := context.WithCancel(context.Background()) - // Note: Not using defer cancel() to avoid race condition panic during shutdown - _ = cancel + // Shut the server down before the deferred socketE2EMutex unlock (defers + // run last-in first-out), so its upstream manager's network-recovery + // watcher does not outlive the test (TestMain leak guard). Shutdown runs + // first, so the context-cancel shutdown path finds it done and skips. + defer func() { + _ = srv.Shutdown() + cancel() + }() go func() { _ = srv.Start(ctx) @@ -390,8 +399,14 @@ func TestE2E_SocketPermissions(t *testing.T) { require.NoError(t, err) ctx, cancel := context.WithCancel(context.Background()) - // Note: Not using defer cancel() to avoid race condition panic during shutdown - _ = cancel + // Shut the server down before the deferred socketE2EMutex unlock (defers + // run last-in first-out), so its upstream manager's network-recovery + // watcher does not outlive the test (TestMain leak guard). Shutdown runs + // first, so the context-cancel shutdown path finds it done and skips. + defer func() { + _ = srv.Shutdown() + cancel() + }() go func() { _ = srv.Start(ctx) diff --git a/internal/server/upstream_outcome_paths_test.go b/internal/server/upstream_outcome_paths_test.go new file mode 100644 index 000000000..c5cb7c646 --- /dev/null +++ b/internal/server/upstream_outcome_paths_test.go @@ -0,0 +1,267 @@ +package server + +import ( + "context" + "errors" + "fmt" + "go/ast" + "go/parser" + "go/token" + "testing" + + "github.com/mark3labs/mcp-go/mcp" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/outputvalidation" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime/stateview" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/security" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/transport" +) + +// Spec 126 FR-035 / FR-037 (T081): exactly one completion outcome per logical +// upstream call that dispatched at least one request, on every dispatch path +// (call_tool_* wrapper, direct routing, each code_execution sub-call). The +// oracle is the registry's raw outcome totals (the wire carries buckets). + +type outcomeStarter struct { + name string + inc int64 +} + +func (s outcomeStarter) IsStarter(name string, inc int64) bool { + return name == s.name && inc == s.inc +} + +type outcomeWant struct{ succeeded, unusable, nonStarter int64 } + +func outcomeTotals(f *directRoutingFixture) outcomeWant { + s, u, n := f.proxy.telemetryRegistry().UpstreamOutcomeTotals() + return outcomeWant{s, u, n} +} + +func TestUpstreamOutcome_OnePerLogicalCallOnEveryPath(t *testing.T) { + type tc struct { + name string + up telUpstream + refused bool // caller lacks the destructive tier: refused before dispatch + blockOutput bool // output sanitisation in block mode withholds the result + validateOutput bool // output-schema validation (strict) withholds the result + starter bool // a stub classifier marks the server as the starter + want outcomeWant + wantScope telemetry.SuccessScope + onlyPaths map[telPath]bool + } + cases := []tc{ + {name: "usable result", up: upOK, want: outcomeWant{1, 0, 1}, wantScope: telemetry.SuccessScopeNonStarter}, + {name: "upstream isError", up: upIsError, want: outcomeWant{0, 1, 0}}, + {name: "transport error", up: upTransport, want: outcomeWant{0, 1, 0}}, + {name: "refused before dispatch", up: upOK, refused: true, want: outcomeWant{0, 0, 0}}, + {name: "withheld by output sanitisation", up: upSecret, blockOutput: true, want: outcomeWant{0, 1, 0}}, + {name: "withheld by output validation", up: upOK, validateOutput: true, want: outcomeWant{0, 1, 0}, + onlyPaths: map[telPath]bool{telWrapper: true}}, + {name: "starter success", up: upOK, starter: true, want: outcomeWant{1, 0, 0}, wantScope: telemetry.SuccessScopeStarterOnly}, + } + for _, path := range []telPath{telWrapper, telDirect, telJS} { + for _, c := range cases { + if c.onlyPaths != nil && !c.onlyPaths[path] { + continue + } + c, path := c, path + t.Run(fmt.Sprintf("%s/%s", path, c.name), func(t *testing.T) { + pinTelemetryEnvEnabledForServer(t) + f := newDirectRoutingFixture(t, directServerSpec{server: "fixture", + tools: []toolSpec{readSpec("probe"), destructiveSpec("wipe")}}) + f.rt.SetTelemetry("v0.70.0", "personal") + require.NotNil(t, f.rt.TelemetryService()) + + up := f.ups["fixture"] + for _, name := range []string{"probe", "wipe"} { + up.mcpSrv.AddTool(mcp.Tool{Name: name, InputSchema: mcp.ToolInputSchema{Type: "object"}}, + func(_ context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + up.record(req.Params.Name) + switch c.up { + case upIsError: + return mcp.NewToolResultError("synthetic upstream rejection"), nil + case upTransport: + return nil, errors.New("synthetic transport failure") + case upSecret: + return mcp.NewToolResultText("leaked " + awsKeyFixture), nil + } + return mcp.NewToolResultText("ok"), nil + }) + } + if c.blockOutput { + oc := config.DefaultOutputSanitisationConfig() + oc.ResponseAction = "block" + f.proxy.config.OutputSanitisation = oc + f.proxy.sanitisationDetector = security.NewDetector(config.DefaultSensitiveDataDetectionConfig()) + } + if c.validateOutput { + f.proxy.config.OutputValidation = &config.OutputValidationConfig{Mode: "strict", MissingStructuredContent: "block"} + f.proxy.outputValidator = outputvalidation.New( + f.proxy.config.OutputValidation.EffectiveMaxBytes(), + f.proxy.config.OutputValidation.EffectiveMaxDepth(), + zap.NewNop()) + // The tool declares an output schema; the upstream answers + // prose only, which strict mode withholds. + f.rt.Supervisor().StateView().UpdateServer("fixture", func(s *stateview.ServerStatus) { + for i := range s.Tools { + if s.Tools[i].Name == "probe" { + s.Tools[i].OutputSchemaJSON = `{"type":"object","properties":{"url":{"type":"string"}}}` + } + } + }) + } + if c.starter { + inc, ok := f.rt.ServerIncarnation("fixture") + require.True(t, ok) + f.rt.SetStarterClassifier(outcomeStarter{name: "fixture", inc: inc}) + } + + tool, variant := "probe", contracts.ToolVariantRead + perms := []string{auth.PermRead, auth.PermWrite, auth.PermDestructive} + if c.refused { + tool, variant = "wipe", contracts.ToolVariantDestructive + perms = []string{auth.PermRead} + } + ctx := agentCtx([]string{"fixture"}, perms, "") + + switch path { + case telWrapper: + req := mcp.CallToolRequest{} + req.Params.Name = variant + req.Params.Arguments = map[string]interface{}{"name": "fixture:" + tool, "args": map[string]interface{}{}} + res, err := f.proxy.handleCallToolVariant(ctx, req, variant) + require.NoError(t, err) + require.NotNil(t, res) + case telDirect: + f.call(t, ctx, "fixture", tool) + case telJS: + runSandboxCallTool(t, f.proxy, ctx, "fixture", tool) + } + + wantUpstream := int64(1) + if c.refused { + wantUpstream = 0 + } + require.Equal(t, wantUpstream, up.count.Load(), "upstream invocations") + require.Equal(t, c.want, outcomeTotals(f), "outcome totals {succeeded unusable non_starter}") + scope, err := telemetry.LoadSuccessScope(f.rt.TelemetryService().ActivationDB()) + require.NoError(t, err) + require.Equal(t, c.wantScope, scope, "success_scope_ever") + }) + } + } +} + +// Outcomes count logical calls; dispatch counts requests. A session-recovery +// repeat hands the request to the transport twice: two dispatches, one +// outcome. A logical call with zero dispatches records none. +func TestUpstreamOutcome_DispatchCountVersusLogicalCall(t *testing.T) { + pinTelemetryEnvEnabledForServer(t) + f := newDirectRoutingFixture(t, directServerSpec{server: "fixture", tools: []toolSpec{readSpec("probe")}}) + f.rt.SetTelemetry("v0.70.0", "personal") + + // A session-recovery repeat: the recorder saw two hand-offs. + ctx, _ := transport.WithCallRecorder(context.Background()) + transport.MarkDispatched(ctx) + transport.MarkDispatched(ctx) + f.proxy.noteUpstreamDispatched(ctx) + o := f.proxy.beginUpstreamOutcome(ctx, "fixture", 1) + o.markUsable(mcp.NewToolResultText("ok"), nil) + o.record() + o.record() // idempotent: a second record (e.g. an explicit call plus the defer) adds nothing + require.Equal(t, outcomeWant{1, 0, 1}, outcomeTotals(f)) + require.Equal(t, "1-10", f.proxy.telemetryRegistry().Snapshot().UpstreamToolCallCountBucket) + + // Zero dispatches (refused by the managed client, shed, cancelled in the + // admission queue): no outcome. + none, _ := transport.WithCallRecorder(context.Background()) + z := f.proxy.beginUpstreamOutcome(none, "fixture", 1) + z.record() + require.Equal(t, outcomeWant{1, 0, 1}, outcomeTotals(f)) + + // Not marked usable: unusable. + again, _ := transport.WithCallRecorder(context.Background()) + transport.MarkDispatched(again) + u := f.proxy.beginUpstreamOutcome(again, "fixture", 1) + u.markUsable(mcp.NewToolResultError("upstream said no"), nil) + u.record() + require.Equal(t, outcomeWant{1, 1, 1}, outcomeTotals(f), "an isError result is not usable") +} + +// Every exit after the dispatch is covered: in each of the three dispatch +// functions the outcome is begun and its record deferred immediately after +// noteUpstreamDispatched, before any statement that can return. A new early +// return added later therefore still records exactly one outcome. +func TestUpstreamOutcome_DeferredRightAfterDispatchOnEveryPath(t *testing.T) { + // The call_tool_* wrapper (handleCallToolVariant), direct routing + // (makeDirectModeHandler) and code_execution sub-calls + // (upstreamToolCaller.callTool). + cases := []struct{ file string }{{"mcp.go"}, {"mcp_routing.go"}, {"mcp_code_execution.go"}} + for _, c := range cases { + t.Run(c.file, func(t *testing.T) { + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, c.file, nil, 0) + require.NoError(t, err) + var found bool + ast.Inspect(file, func(n ast.Node) bool { + var stmts []ast.Stmt + switch b := n.(type) { + case *ast.BlockStmt: + stmts = b.List + default: + return true + } + for i, st := range stmts { + if !isDirectCall(st, "noteUpstreamDispatched") { + continue + } + found = true + require.Greater(t, len(stmts), i+2, "%s: statements must follow noteUpstreamDispatched", c.file) + assign, ok := stmts[i+1].(*ast.AssignStmt) + require.True(t, ok && callsMethod(assign, "beginUpstreamOutcome"), + "%s:%d: the statement right after noteUpstreamDispatched must begin the outcome", c.file, fset.Position(stmts[i+1].Pos()).Line) + def, ok := stmts[i+2].(*ast.DeferStmt) + require.True(t, ok && callsMethod(def, "record"), + "%s:%d: the outcome's record must be deferred right after it begins", c.file, fset.Position(stmts[i+2].Pos()).Line) + } + return true + }) + require.True(t, found, "%s: no noteUpstreamDispatched call found", c.file) + }) + } +} + +// isDirectCall reports whether st is itself the statement `x.name(...)` (not a +// statement that merely contains such a call somewhere inside it). +func isDirectCall(st ast.Stmt, name string) bool { + es, ok := st.(*ast.ExprStmt) + if !ok { + return false + } + call, ok := es.X.(*ast.CallExpr) + if !ok { + return false + } + sel, ok := call.Fun.(*ast.SelectorExpr) + return ok && sel.Sel.Name == name +} + +func callsMethod(n ast.Node, name string) bool { + hit := false + ast.Inspect(n, func(m ast.Node) bool { + if call, ok := m.(*ast.CallExpr); ok { + if sel, ok := call.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == name { + hit = true + } + } + return !hit + }) + return hit +} diff --git a/internal/storage/bbolt.go b/internal/storage/bbolt.go index a5a749978..76bc282b1 100644 --- a/internal/storage/bbolt.go +++ b/internal/storage/bbolt.go @@ -42,6 +42,10 @@ type BoltDB struct { // oauthKey seals and opens oauth_tokens values (Spec 123); nil when // encryption is off. Set once at open, never changed. oauthKey *tokenseal.Key + // wasEmptyAtOpen is true when config.db held no prior data when this + // process opened it (absent, 0 bytes, or no record in any bucket). Decided once in + // NewBoltDB before initBuckets creates anything (Spec 126 FR-033). + wasEmptyAtOpen bool } // noSync opens databases with bbolt's NoSync. Only tests set it, through @@ -57,10 +61,18 @@ var noSync atomic.Bool // production code. func DisableSyncForTesting() { noSync.Store(true) } +// testHookBeforeOpen, when set by a test, runs right before bbolt.Open: the +// window in which another process can populate the store while this one waits +// for the lock. Always nil in production. +var testHookBeforeOpen func(dbPath string) + // NewBoltDB creates a new BoltDB instance func NewBoltDB(dataDir string, logger *zap.SugaredLogger, opts ...Option) (*BoltDB, error) { o := resolveOpenOptions(opts) dbPath := filepath.Join(dataDir, "config.db") + if testHookBeforeOpen != nil { + testHookBeforeOpen(dbPath) + } // Try to open with timeout, if it fails, immediately return database locked error. // The database holds OAuth tokens and DCR client secrets as plain JSON @@ -94,6 +106,12 @@ func NewBoltDB(dataDir string, logger *zap.SugaredLogger, opts ...Option) (*Bolt db: db, logger: logger, oauthKey: o.oauthKey, + // Spec 126 FR-033: "no prior data" is decided from the database itself, + // under its lock and before initBuckets writes anything. A stat taken + // before bbolt.Open could be stale: another process may populate the + // store while this one waits up to 10 s for the lock. A file that + // bbolt.Open just created holds no records, so it reads as empty. + wasEmptyAtOpen: !storeHasRecords(db), } // Initialize buckets and schema diff --git a/internal/storage/install_anchor.go b/internal/storage/install_anchor.go new file mode 100644 index 000000000..22283fd4c --- /dev/null +++ b/internal/storage/install_anchor.go @@ -0,0 +1,171 @@ +package storage + +import ( + stderrors "errors" + "fmt" + "time" + + "go.etcd.io/bbolt" +) + +// InstallAnchorBucket / InstallAnchorKey hold the install anchor (Spec 126 +// FR-033): the UTC time of the first core start over a data store that held no +// prior data. It lives in its own bucket, never inside OnboardingState: older +// binaries round-trip the whole OnboardingState record and would erase a field +// they do not know on a downgrade. Only EnsureInstallAnchor writes it; it is +// written once, never rewritten, and recorded whatever the telemetry opt-out +// setting (only sending is gated). The value is an RFC 3339 UTC timestamp and +// never leaves the machine: the heartbeat carries only day buckets derived +// from it. +const ( + InstallAnchorBucket = "install_anchor" + InstallAnchorKey = "first_run_at" +) + +// errStoreHasRecords ends the walk in storeHasRecords at the first record; it +// never escapes the View. +var errStoreHasRecords = stderrors.New("store has records") + +// storeHasRecords reports whether the opened database holds at least one +// record (a key) in any bucket, nested buckets included. Buckets that exist but +// are empty — for example created by a standalone CLI command run before the +// first serve — are not data, and neither is the meta schema-version key that +// every open writes into a new store (initBuckets). A read failure counts as +// "has records" (fail closed: an unreadable store is never a new install). +func storeHasRecords(db *bbolt.DB) bool { + err := db.View(func(tx *bbolt.Tx) error { + return tx.ForEach(func(name []byte, b *bbolt.Bucket) error { + return bucketHasRecords(b, string(name) == MetaBucket) + }) + }) + if err == nil { + return false + } + return true // errStoreHasRecords, or a read failure (fail closed) +} + +// bucketHasRecords returns errStoreHasRecords when b, or a bucket nested in +// it, holds a key. isMeta skips the schema-version key of the meta bucket. +func bucketHasRecords(b *bbolt.Bucket, isMeta bool) error { + return b.ForEach(func(k, v []byte) error { + if v == nil { // nested bucket + nested := b.Bucket(k) + if nested == nil { + return errStoreHasRecords + } + return bucketHasRecords(nested, false) + } + if isMeta && string(k) == SchemaVersionKey { + return nil + } + return errStoreHasRecords + }) +} + +// WasEmptyAtOpen reports whether config.db held no prior data when this +// process opened it: the file was absent, 0 bytes long, or held no record in +// any bucket (empty buckets and the meta schema-version key do not count). +// It is decided once, in NewBoltDB, before any bucket is created. +func (b *BoltDB) WasEmptyAtOpen() bool { + return b.wasEmptyAtOpen +} + +// EnsureInstallAnchor records now (as UTC) as the install anchor when the +// store was empty at open and holds no anchor yet, and returns the anchor the +// store holds afterwards. An existing store without an anchor stays without +// one (ok=false): an install upgraded from a build without the field is never +// counted as new. An anchor, once written, is never rewritten — a second call, +// or a later start, returns the first one. Concurrent callers are serialized by +// the bbolt write transaction and all see the same anchor. +func (b *BoltDB) EnsureInstallAnchor(now time.Time) (time.Time, bool, error) { + if !b.wasEmptyAtOpen { + return b.InstallAnchor() + } + var anchor time.Time + err := b.db.Update(func(tx *bbolt.Tx) error { + bucket, err := tx.CreateBucketIfNotExists([]byte(InstallAnchorBucket)) + if err != nil { + return err + } + if raw := bucket.Get([]byte(InstallAnchorKey)); raw != nil { + anchor, err = decodeInstallAnchor(raw) + return err + } + anchor = now.UTC() + return bucket.Put([]byte(InstallAnchorKey), []byte(anchor.Format(time.RFC3339Nano))) + }) + if err != nil { + return time.Time{}, false, err + } + return anchor, true, nil +} + +// InstallAnchor returns the recorded install anchor. ok is false when the +// store has none (an existing install). A stored value that does not parse is +// an error, never a missing anchor. +func (b *BoltDB) InstallAnchor() (time.Time, bool, error) { + var ( + anchor time.Time + ok bool + ) + err := b.db.View(func(tx *bbolt.Tx) error { + bucket := tx.Bucket([]byte(InstallAnchorBucket)) + if bucket == nil { + return nil + } + raw := bucket.Get([]byte(InstallAnchorKey)) + if raw == nil { + return nil + } + t, err := decodeInstallAnchor(raw) + if err != nil { + return err + } + anchor, ok = t, true + return nil + }) + if err != nil { + return time.Time{}, false, err + } + return anchor, ok, nil +} + +func decodeInstallAnchor(raw []byte) (time.Time, error) { + t, err := time.Parse(time.RFC3339Nano, string(raw)) + if err != nil { + return time.Time{}, fmt.Errorf("install anchor: %w", err) + } + return t.UTC(), nil +} + +// WasEmptyAtOpen reports whether config.db held no prior data when this +// process opened it (Spec 126 FR-033, FR-036). +func (m *Manager) WasEmptyAtOpen() bool { + m.mu.RLock() + defer m.mu.RUnlock() + if m.db == nil { + return false + } + return m.db.WasEmptyAtOpen() +} + +// EnsureInstallAnchor records the install anchor when the store was empty at +// open (Spec 126 FR-033). See BoltDB.EnsureInstallAnchor. +func (m *Manager) EnsureInstallAnchor(now time.Time) (time.Time, bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + if m.db == nil { + return time.Time{}, false, fmt.Errorf("storage not open") + } + return m.db.EnsureInstallAnchor(now) +} + +// InstallAnchor returns the recorded install anchor, if any. +func (m *Manager) InstallAnchor() (time.Time, bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + if m.db == nil { + return time.Time{}, false, fmt.Errorf("storage not open") + } + return m.db.InstallAnchor() +} diff --git a/internal/storage/install_anchor_test.go b/internal/storage/install_anchor_test.go new file mode 100644 index 000000000..cfaef3936 --- /dev/null +++ b/internal/storage/install_anchor_test.go @@ -0,0 +1,302 @@ +package storage + +import ( + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "go.etcd.io/bbolt" + "go.uber.org/zap" +) + +// Spec 126 FR-033 (T003): the install anchor is written once, only when the +// data store held no prior data when this process opened it. + +func openAnchorTestManager(t *testing.T, dir string) *Manager { + t.Helper() + m, err := NewManager(dir, zap.NewNop().Sugar()) + require.NoError(t, err) + return m +} + +// (a) A store opened on a new file records the anchor once EnsureInstallAnchor runs. +func TestInstallAnchor_NewFileRecordsAnchor(t *testing.T) { + dir := t.TempDir() + m := openAnchorTestManager(t, dir) + defer m.Close() + + require.True(t, m.WasEmptyAtOpen(), "a store opened on an absent file was empty at open") + _, ok, err := m.InstallAnchor() + require.NoError(t, err) + require.False(t, ok, "no anchor before EnsureInstallAnchor") + + now := time.Date(2026, 11, 18, 9, 30, 0, 0, time.FixedZone("UTC+2", 2*3600)) + got, ok, err := m.EnsureInstallAnchor(now) + require.NoError(t, err) + require.True(t, ok) + require.True(t, got.Equal(now)) + require.Equal(t, time.UTC, got.Location(), "the anchor is a UTC time") + + read, ok, err := m.InstallAnchor() + require.NoError(t, err) + require.True(t, ok) + require.True(t, read.Equal(now)) +} + +// (b) A store opened on an existing file with data and no anchor stays +// without one (an upgrade from a build without the anchor). +func TestInstallAnchor_ExistingStoreWithoutAnchorStaysWithout(t *testing.T) { + dir := t.TempDir() + // An older build: it created the buckets and wrote data, but no anchor. + m := openAnchorTestManager(t, dir) + require.NoError(t, m.GetDB().Update(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(MetaBucket)).Put([]byte("some_older_key"), []byte("x")) + })) + require.NoError(t, m.Close()) + + m2 := openAnchorTestManager(t, dir) + defer m2.Close() + require.False(t, m2.WasEmptyAtOpen(), "a store with buckets is not empty") + _, ok, err := m2.EnsureInstallAnchor(time.Now()) + require.NoError(t, err) + require.False(t, ok, "an existing store without an anchor must stay without one") + _, ok, err = m2.InstallAnchor() + require.NoError(t, err) + require.False(t, ok) +} + +// (c) An existing empty file (0 bytes, a valid bbolt file with no buckets, or +// one whose buckets hold no record) counts as new. +func TestInstallAnchor_EmptyFileCountsAsNew(t *testing.T) { + t.Run("zero bytes", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.db"), nil, 0o600)) + m := openAnchorTestManager(t, dir) + defer m.Close() + require.True(t, m.WasEmptyAtOpen()) + _, ok, err := m.EnsureInstallAnchor(time.Now()) + require.NoError(t, err) + require.True(t, ok) + }) + t.Run("no buckets", func(t *testing.T) { + dir := t.TempDir() + raw, err := bbolt.Open(filepath.Join(dir, "config.db"), 0o600, nil) + require.NoError(t, err) + require.NoError(t, raw.Close()) + fi, err := os.Stat(filepath.Join(dir, "config.db")) + require.NoError(t, err) + require.Greater(t, fi.Size(), int64(0), "a bucketless bbolt file still has pages") + + m := openAnchorTestManager(t, dir) + defer m.Close() + require.True(t, m.WasEmptyAtOpen()) + _, ok, err := m.EnsureInstallAnchor(time.Now()) + require.NoError(t, err) + require.True(t, ok) + }) + t.Run("only the buckets and schema version a real open writes", func(t *testing.T) { + // A standalone CLI command run before the first serve opens the store + // through the real NewBoltDB: it creates every bucket and writes + // meta/schema_version (initBuckets), nothing else. + dir := t.TempDir() + cli, err := NewBoltDB(dir, zap.NewNop().Sugar()) + require.NoError(t, err) + require.True(t, cli.WasEmptyAtOpen()) + require.NoError(t, cli.Close()) + + m := openAnchorTestManager(t, dir) + defer m.Close() + require.True(t, m.WasEmptyAtOpen(), "buckets without records, and meta/schema_version, still count as empty") + _, ok, err := m.EnsureInstallAnchor(time.Now()) + require.NoError(t, err) + require.True(t, ok) + }) + t.Run("a record in a nested bucket is data", func(t *testing.T) { + dir := t.TempDir() + m := openAnchorTestManager(t, dir) + require.NoError(t, m.GetDB().Update(func(tx *bbolt.Tx) error { + nb, err := tx.Bucket([]byte(UpstreamsBucket)).CreateBucketIfNotExists([]byte("nested")) + if err != nil { + return err + } + return nb.Put([]byte("k"), []byte("v")) + })) + require.NoError(t, m.Close()) + m2 := openAnchorTestManager(t, dir) + defer m2.Close() + require.False(t, m2.WasEmptyAtOpen()) + }) +} + +// Only EnsureInstallAnchor writes the anchor. An upgraded store with no +// onboarding record goes through the onboarding missing-record branch on every +// MCP initialize, connect and mark; none of that may turn it into "fresh". +func TestInstallAnchor_UpgradedStoreStaysWithoutAnchorAfterOnboardingWrites(t *testing.T) { + dir := t.TempDir() + old := openAnchorTestManager(t, dir) + require.NoError(t, old.GetDB().Update(func(tx *bbolt.Tx) error { + return tx.Bucket([]byte(UpstreamsBucket)).Put([]byte("github"), []byte(`{"name":"github"}`)) + })) + require.NoError(t, old.Close()) + + m := openAnchorTestManager(t, dir) + defer m.Close() + require.False(t, m.WasEmptyAtOpen()) + _, ok, err := m.EnsureInstallAnchor(time.Now()) // startup + require.NoError(t, err) + require.False(t, ok) + + st, err := m.GetOnboardingState() // no record yet + require.NoError(t, err) + _ = st + // MCP initialize, then a client connect: both reach the missing-record + // branch of UpdateOnboardingState. + for i := 0; i < 2; i++ { + require.NoError(t, m.UpdateOnboardingState(func(s *OnboardingState) error { + s.Engaged = true + return nil + })) + } + _, ok, err = m.EnsureInstallAnchor(time.Now()) + require.NoError(t, err) + require.False(t, ok, "onboarding writes must never create an anchor") + _, ok, err = m.InstallAnchor() + require.NoError(t, err) + require.False(t, ok) +} + +// The anchor lives in its own bucket, outside the OnboardingState record that +// older binaries round-trip whole. +func TestInstallAnchor_StoredInItsOwnBucket(t *testing.T) { + dir := t.TempDir() + m := openAnchorTestManager(t, dir) + defer m.Close() + _, ok, err := m.EnsureInstallAnchor(time.Now()) + require.NoError(t, err) + require.True(t, ok) + require.NoError(t, m.GetDB().View(func(tx *bbolt.Tx) error { + b := tx.Bucket([]byte(InstallAnchorBucket)) + require.NotNil(t, b) + require.NotNil(t, b.Get([]byte(InstallAnchorKey))) + require.Nil(t, tx.Bucket([]byte(OnboardingBucket)).Get([]byte(OnboardingStateKey)), "no onboarding record is written") + return nil + })) +} + +// (d) A second start never changes the anchor, and neither does a second call. +func TestInstallAnchor_NeverRewritten(t *testing.T) { + dir := t.TempDir() + first := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) + m := openAnchorTestManager(t, dir) + _, ok, err := m.EnsureInstallAnchor(first) + require.NoError(t, err) + require.True(t, ok) + again, ok, err := m.EnsureInstallAnchor(first.Add(48 * time.Hour)) + require.NoError(t, err) + require.True(t, ok) + require.True(t, again.Equal(first), "a second call in the same process keeps the first anchor") + require.NoError(t, m.Close()) + + m2 := openAnchorTestManager(t, dir) + defer m2.Close() + require.False(t, m2.WasEmptyAtOpen()) + got, ok, err := m2.EnsureInstallAnchor(first.Add(240 * time.Hour)) + require.NoError(t, err) + require.True(t, ok) + require.True(t, got.Equal(first), "a later start keeps the anchor") +} + +// (e) Concurrent callers produce one anchor (run under -race). +func TestInstallAnchor_ConcurrentCallersProduceOneAnchor(t *testing.T) { + dir := t.TempDir() + m := openAnchorTestManager(t, dir) + defer m.Close() + + base := time.Date(2026, 11, 18, 0, 0, 0, 0, time.UTC) + const n = 16 + results := make([]time.Time, n) + oks := make([]bool, n) + errs := make([]error, n) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + results[i], oks[i], errs[i] = m.EnsureInstallAnchor(base.Add(time.Duration(i) * time.Minute)) + }(i) + } + wg.Wait() + for i := 0; i < n; i++ { + require.NoError(t, errs[i]) + require.True(t, oks[i]) + require.True(t, results[i].Equal(results[0]), "every caller sees the one anchor") + } + stored, ok, err := m.InstallAnchor() + require.NoError(t, err) + require.True(t, ok) + require.True(t, stored.Equal(results[0])) +} + +// A corrupt anchor value is reported as an error, never as a fresh anchor, and +// EnsureInstallAnchor does not overwrite it. +func TestInstallAnchor_CorruptValueIsNotRewritten(t *testing.T) { + dir := t.TempDir() + m := openAnchorTestManager(t, dir) + defer m.Close() + require.NoError(t, m.GetDB().Update(func(tx *bbolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte(InstallAnchorBucket)) + if err != nil { + return err + } + return b.Put([]byte(InstallAnchorKey), []byte("not-a-time")) + })) + _, _, err := m.EnsureInstallAnchor(time.Now()) + require.Error(t, err) + _, _, err = m.InstallAnchor() + require.Error(t, err) + require.NoError(t, m.GetDB().View(func(tx *bbolt.Tx) error { + require.Equal(t, "not-a-time", string(tx.Bucket([]byte(InstallAnchorBucket)).Get([]byte(InstallAnchorKey)))) + return nil + })) +} + +// A store populated by another process while this one waits for the lock is +// not a new install: emptiness is decided from the locked database, never +// from a stat taken before bbolt.Open (review finding, Spec 126 FR-033). +func TestNewBoltDB_StorePopulatedBeforeLockIsNotEmpty(t *testing.T) { + dir := t.TempDir() + testHookBeforeOpen = func(dbPath string) { + other, err := bbolt.Open(dbPath, 0600, nil) + if err != nil { + t.Fatalf("other process open: %v", err) + } + if err := other.Update(func(tx *bbolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte("upstreams")) + if err != nil { + return err + } + return b.Put([]byte("github"), []byte(`{"name":"github"}`)) + }); err != nil { + t.Fatalf("other process write: %v", err) + } + if err := other.Close(); err != nil { + t.Fatalf("other process close: %v", err) + } + } + t.Cleanup(func() { testHookBeforeOpen = nil }) + + db, err := NewBoltDB(dir, zap.NewNop().Sugar()) + if err != nil { + t.Fatalf("NewBoltDB: %v", err) + } + defer db.Close() + if db.WasEmptyAtOpen() { + t.Fatal("a store populated before the lock was taken must not read as empty") + } + if _, wrote, err := db.EnsureInstallAnchor(time.Now()); err != nil || wrote { + t.Fatalf("EnsureInstallAnchor on an existing store: wrote=%v err=%v, want no anchor", wrote, err) + } +} diff --git a/internal/telemetry/anonymity.go b/internal/telemetry/anonymity.go index 6fcf9311f..ea49c7cd7 100644 --- a/internal/telemetry/anonymity.go +++ b/internal/telemetry/anonymity.go @@ -106,6 +106,11 @@ type anonymityScanEnvelope struct { // → non-negative counts. Same not-a-pointer reasoning as TPAScanner. Preflight json.RawMessage `json:"preflight"` + // Spec 126 (schema v17) closed objects: the completion window and the + // day_two block. Same not-a-pointer reasoning as TPAScanner. + UpstreamOutcomes json.RawMessage `json:"upstream_outcomes"` + DayTwo json.RawMessage `json:"day_two"` + // Schema v9 structural check: the trust-tier histogram must be keyed // exclusively by the fixed auto|scan|manual enum with non-negative integer // counts — a producer-side regression that let a server name in as a map @@ -461,6 +466,144 @@ func scanTrustModeDistribution(raw json.RawMessage) *AnonymityViolation { return nil } +// dayTwoFieldViolation builds the violation for a schema-v17 closed object +// (upstream_outcomes, day_two) that broke its shape. field is always one of +// the fixed key names below, never a key or value read from the payload. +func dayTwoFieldViolation(field, reason string) *AnonymityViolation { + return &AnonymityViolation{ + Rule: "day_two_field_invalid", + Pattern: field, + Reason: fmt.Sprintf("schema-17 field %s %s", field, reason), + } +} + +// v17BucketEnum is the bucketUpstream vocabulary. +var v17BucketEnum = []string{"0", "1-10", "11-100", "101-1000", "1000+"} + +// upstreamOutcomesSchema / dayTwoSchema are the closed key sets and enums of +// the two schema-v17 objects (specs/126-day-two-activation/contracts/ +// telemetry-day-two.schema.json, schema-17 part). Keys of later schema +// versions are added here with the PR that produces them. +var ( + upstreamOutcomesSchema = map[string][]string{ + "succeeded": v17BucketEnum, + "unusable": v17BucketEnum, + "succeeded_non_starter": v17BucketEnum, + "coverage": {OutcomeCoverageFull, OutcomeCoveragePartial}, + "window_age": {InstallAgeD0to6, InstallAgeD7to13, InstallAgeD14Plus}, + } + upstreamOutcomesRequired = []string{"succeeded", "unusable", "succeeded_non_starter", "coverage"} + + dayTwoSchema = map[string][]string{ + "install_origin": {InstallOriginFresh, InstallOriginExisting}, + "install_age": {InstallAgeD0to6, InstallAgeD7to13, InstallAgeD14Plus}, + "success_scope_ever": {SuccessScopeNone.String(), SuccessScopeStarterOnly.String(), SuccessScopeNonStarter.String()}, + } + dayTwoRequired = []string{"install_origin", "success_scope_ever"} +) + +// scanClosedEnumObject asserts raw is a JSON object whose keys all belong to +// schema, whose required keys are present, and whose values are bare JSON +// strings from the key's closed enum. A number, boolean, null, nested object, +// list, timestamp or any free-text string is rejected. The violation never +// echoes a key or value from the payload: field names come from schema. +func scanClosedEnumObject(raw json.RawMessage, object string, schema map[string][]string, required []string) (map[string]string, *AnonymityViolation) { + var obj map[string]json.RawMessage + if err := json.Unmarshal(raw, &obj); err != nil || obj == nil { + return nil, dayTwoFieldViolation(object, "must be an object") + } + for key := range obj { + if _, ok := schema[key]; !ok { + return nil, dayTwoFieldViolation(object, "carries a key outside the closed key set") + } + } + for _, key := range required { + if _, ok := obj[key]; !ok { + return nil, dayTwoFieldViolation(object+"."+key, "is required") + } + } + values := make(map[string]string, len(obj)) + for key, enum := range schema { + v, ok := obj[key] + if !ok { + continue + } + field := object + "." + key + trimmed := bytes.TrimSpace(v) + if len(trimmed) == 0 || trimmed[0] != '"' { + return nil, dayTwoFieldViolation(field, "must be a string from its closed enum") + } + var str string + if err := json.Unmarshal(trimmed, &str); err != nil { + return nil, dayTwoFieldViolation(field, "must be a string from its closed enum") + } + inEnum := false + for _, e := range enum { + if str == e { + inEnum = true + break + } + } + if !inEnum { + return nil, dayTwoFieldViolation(field, "must be a value of its closed enum") + } + values[key] = str + } + return values, nil +} + +// scanUpstreamOutcomes asserts the schema-v17 upstream_outcomes object (if +// present) is the closed completion window: three bucket labels and a +// coverage flag, nothing else. Modelled on scanTrustModeDistribution. +func scanUpstreamOutcomes(raw json.RawMessage) *AnonymityViolation { + if len(raw) == 0 { + return nil + } + _, v := scanClosedEnumObject(raw, "upstream_outcomes", upstreamOutcomesSchema, upstreamOutcomesRequired) + return v +} + +// scanDayTwo asserts the schema-v17 day_two object (if present) carries only +// its closed enums, and that install_age is present exactly when +// install_origin is "fresh". +func scanDayTwo(raw json.RawMessage) *AnonymityViolation { + if len(raw) == 0 { + return nil + } + values, v := scanClosedEnumObject(raw, "day_two", dayTwoSchema, dayTwoRequired) + if v != nil { + return v + } + _, hasAge := values["install_age"] + if fresh := values["install_origin"] == InstallOriginFresh; fresh != hasAge { + return dayTwoFieldViolation("day_two.install_age", "must be present exactly when install_origin is fresh") + } + return nil +} + +// scanWindowAgeOrigin enforces the one cross-object rule of schema 17: +// upstream_outcomes.window_age is sent only for a fresh install, so it must be +// absent whenever day_two.install_origin is "existing" (the receiver rejects +// that combination). Both objects have already passed their own scans. +func scanWindowAgeOrigin(rawOutcomes, rawDayTwo json.RawMessage) *AnonymityViolation { + if len(rawOutcomes) == 0 || len(rawDayTwo) == 0 { + return nil + } + var outcomes struct { + WindowAge *string `json:"window_age"` + } + var dayTwo struct { + InstallOrigin string `json:"install_origin"` + } + if json.Unmarshal(rawOutcomes, &outcomes) != nil || json.Unmarshal(rawDayTwo, &dayTwo) != nil { + return dayTwoFieldViolation("upstream_outcomes.window_age", "could not be checked against day_two") + } + if outcomes.WindowAge != nil && dayTwo.InstallOrigin == InstallOriginExisting { + return dayTwoFieldViolation("upstream_outcomes.window_age", "must be absent when install_origin is existing") + } + return nil +} + // diagFieldViolation builds the violation for a diagnostics counter field that // broke its documented shape (cataloged code keys, non-negative counts). func diagFieldViolation(field, reason string) *AnonymityViolation { @@ -745,6 +888,18 @@ func ScanForPII(payloadJSON []byte) error { return v } + // Rule 9: schema-v17 upstream_outcomes and day_two (Spec 126 FR-029) are + // closed objects of closed string enums. + if v := scanUpstreamOutcomes(env.UpstreamOutcomes); v != nil { + return v + } + if v := scanDayTwo(env.DayTwo); v != nil { + return v + } + if v := scanWindowAgeOrigin(env.UpstreamOutcomes, env.DayTwo); v != nil { + return v + } + return nil } diff --git a/internal/telemetry/anonymity_day_two_test.go b/internal/telemetry/anonymity_day_two_test.go new file mode 100644 index 000000000..60a1ce453 --- /dev/null +++ b/internal/telemetry/anonymity_day_two_test.go @@ -0,0 +1,113 @@ +package telemetry + +import ( + "errors" + "strings" + "testing" +) + +// Spec 126 FR-029 (T013): ScanForPII treats upstream_outcomes and day_two as +// closed objects: closed key sets, closed enums, string buckets only, no +// nested maps, no timestamps, and a violation never echoes the offending key. + +const ( + validOutcomes = `{"succeeded":"1-10","unusable":"0","succeeded_non_starter":"1-10","coverage":"full"}` + validDayTwo = `{"install_origin":"fresh","install_age":"d0_6","success_scope_ever":"non_starter"}` +) + +func v17Payload(outcomes, dayTwo string) []byte { + b := `{"anonymous_id":"abc","schema_version":17` + if outcomes != "" { + b += `,"upstream_outcomes":` + outcomes + } + if dayTwo != "" { + b += `,"day_two":` + dayTwo + } + return []byte(b + `}`) +} + +func TestScanForPII_AcceptsValidDayTwo(t *testing.T) { + accepted := [][]byte{ + v17Payload(validOutcomes, validDayTwo), + v17Payload(validOutcomes, `{"install_origin":"existing","success_scope_ever":"none"}`), + v17Payload(`{"succeeded":"1000+","unusable":"101-1000","succeeded_non_starter":"11-100","coverage":"partial"}`, ""), + v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"full","window_age":"d7_13"}`, ""), + v17Payload("", `{"install_origin":"fresh","install_age":"d14_plus","success_scope_ever":"starter_only"}`), + v17Payload("", `{"install_origin":"fresh","install_age":"d7_13","success_scope_ever":"none"}`), + v17Payload("", ""), + } + for _, p := range accepted { + if err := ScanForPII(p); err != nil { + t.Errorf("valid payload rejected: %s: %v", p, err) + } + } +} + +func TestScanForPII_RejectsInvalidUpstreamOutcomesDayTwo(t *testing.T) { + cases := []struct { + name string + payload []byte + // secret is a string that must never appear in the violation. + secret string + }{ + // unknown keys + {"outcomes unknown key", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"full","github_calls":"0"}`, ""), "github_calls"}, + {"day_two unknown key", v17Payload("", `{"install_origin":"fresh","install_age":"d0_6","success_scope_ever":"none","acme-internal":"x"}`), "acme-internal"}, + // out-of-enum values, every field + {"succeeded out of enum", v17Payload(`{"succeeded":"5","unusable":"0","succeeded_non_starter":"0","coverage":"full"}`, ""), ""}, + {"unusable out of enum", v17Payload(`{"succeeded":"0","unusable":"lots","succeeded_non_starter":"0","coverage":"full"}`, ""), ""}, + {"succeeded_non_starter out of enum", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"","coverage":"full"}`, ""), ""}, + {"window_age out of enum", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"full","window_age":"d3"}`, ""), ""}, + {"window_age timestamp", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"full","window_age":"2026-11-18T09:30:00Z"}`, ""), "2026-11-18T09:30:00Z"}, + {"coverage out of enum", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"none"}`, ""), ""}, + {"install_origin out of enum", v17Payload("", `{"install_origin":"upgraded","success_scope_ever":"none"}`), ""}, + {"install_age out of enum", v17Payload("", `{"install_origin":"fresh","install_age":"d3","success_scope_ever":"none"}`), ""}, + {"success_scope_ever out of enum", v17Payload("", `{"install_origin":"fresh","install_age":"d0_6","success_scope_ever":"all"}`), ""}, + // install_age present only when fresh; required keys present + {"install_age on existing", v17Payload("", `{"install_origin":"existing","install_age":"d0_6","success_scope_ever":"none"}`), ""}, + {"install_age missing on fresh", v17Payload("", `{"install_origin":"fresh","success_scope_ever":"none"}`), ""}, + {"outcomes missing key", v17Payload(`{"succeeded":"0","unusable":"0","coverage":"full"}`, ""), ""}, + {"day_two missing scope", v17Payload("", `{"install_origin":"existing"}`), ""}, + // non-string bucket + {"numeric bucket", v17Payload(`{"succeeded":3,"unusable":"0","succeeded_non_starter":"0","coverage":"full"}`, ""), ""}, + {"boolean origin", v17Payload("", `{"install_origin":true,"success_scope_ever":"none"}`), ""}, + {"null bucket", v17Payload(`{"succeeded":null,"unusable":"0","succeeded_non_starter":"0","coverage":"full"}`, ""), ""}, + // nested maps + {"nested map in outcomes", v17Payload(`{"succeeded":{"github":"1-10"},"unusable":"0","succeeded_non_starter":"0","coverage":"full"}`, ""), "github"}, + {"nested map in day_two", v17Payload("", `{"install_origin":"fresh","install_age":{"d0_6":true},"success_scope_ever":"none"}`), ""}, + {"outcomes is a list", v17Payload(`["0"]`, ""), ""}, + {"outcomes is null", v17Payload(`null`, ""), ""}, + {"day_two is null", v17Payload("", `null`), ""}, + {"day_two is a string", v17Payload("", `"fresh"`), ""}, + // timestamps + {"timestamp in day_two", v17Payload("", `{"install_origin":"fresh","install_age":"2026-11-18T09:30:00Z","success_scope_ever":"none"}`), "2026-11-18T09:30:00Z"}, + {"timestamp in outcomes", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"2026-11-18T09:30:00Z"}`, ""), "2026-11-18T09:30:00Z"}, + // server-name-like strings + {"server name as value", v17Payload("", `{"install_origin":"fresh","install_age":"d0_6","success_scope_ever":"github-mcp"}`), "github-mcp"}, + // window_age only for a fresh install + {"window_age on an existing install", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"full","window_age":"d0_6"}`, `{"install_origin":"existing","success_scope_ever":"none"}`), ""}, + {"server name as key", v17Payload(`{"succeeded":"0","unusable":"0","succeeded_non_starter":"0","coverage":"full","my-server":"1-10"}`, ""), "my-server"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := ScanForPII(c.payload) + if err == nil { + t.Fatalf("payload accepted: %s", c.payload) + } + var v *AnonymityViolation + if !errors.As(err, &v) { + t.Fatalf("want *AnonymityViolation, got %T: %v", err, err) + } + if v.Rule != "day_two_field_invalid" { + t.Fatalf("rule = %q, want day_two_field_invalid", v.Rule) + } + if c.secret != "" { + for _, s := range []string{v.Pattern, v.Reason, err.Error()} { + if strings.Contains(s, c.secret) { + t.Fatalf("violation echoes the offending content %q: %q", c.secret, s) + } + } + } + }) + } +} diff --git a/internal/telemetry/anonymity_test.go b/internal/telemetry/anonymity_test.go index b7c28d490..7e0dfba2d 100644 --- a/internal/telemetry/anonymity_test.go +++ b/internal/telemetry/anonymity_test.go @@ -342,13 +342,13 @@ func TestScanForPII_TPARefreshCountersAcceptedAsNonNegativeInts(t *testing.T) { withoutBlockedValues(t) for _, key := range tpaRefreshCounterKeys { for _, val := range []string{"0", "1", "9007199254740991"} { - js := `{"anonymous_id":"abc","schema_version":16,"tpa_scanner":{"` + key + `":` + val + `}}` + js := `{"anonymous_id":"abc","schema_version":17,"tpa_scanner":{"` + key + `":` + val + `}}` if err := ScanForPII([]byte(js)); err != nil { t.Errorf("%s=%s rejected: %v", key, val, err) } } } - all := `{"anonymous_id":"abc","schema_version":16,"tpa_scanner":{` + + all := `{"anonymous_id":"abc","schema_version":17,"tpa_scanner":{` + `"scans_completed":1,"bundle_refresh_cycles":3,"bundle_refresh_activations":1,` + `"bundle_refresh_rejections":1,"bundle_refresh_unavailable":1,"bundle_reprotect_hits":2,` + `"bundle_source":"fetch","bundle_signature_verified":true,"bundle_version":"other"}}` @@ -364,7 +364,7 @@ func TestScanForPII_TPARefreshCountersRejectNonIntegers(t *testing.T) { withoutBlockedValues(t) for _, key := range tpaRefreshCounterKeys { for _, val := range []string{`"3"`, `"https://example.test/x"`, `-1`, `1.5`, `2.0`, `null`, `true`, `{}`, `[]`} { - js := `{"anonymous_id":"abc","schema_version":16,"tpa_scanner":{"` + key + `":` + val + `}}` + js := `{"anonymous_id":"abc","schema_version":17,"tpa_scanner":{"` + key + `":` + val + `}}` err := ScanForPII([]byte(js)) if err == nil { t.Errorf("%s=%s accepted, want an anonymity violation", key, val) diff --git a/internal/telemetry/current_error_codes_test.go b/internal/telemetry/current_error_codes_test.go index 4b6f497e7..ac94b1d12 100644 --- a/internal/telemetry/current_error_codes_test.go +++ b/internal/telemetry/current_error_codes_test.go @@ -265,7 +265,7 @@ func TestPayloadV11_CurrentErrorCodesReachTheWire(t *testing.T) { js := string(data) for _, want := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"MCPX_OAUTH_LOGIN_REQUIRED":2`, `"MCPX_HTTP_DNS_FAILED":1`, `"current_error_codes"`, diff --git a/internal/telemetry/day_two.go b/internal/telemetry/day_two.go new file mode 100644 index 000000000..40a863db3 --- /dev/null +++ b/internal/telemetry/day_two.go @@ -0,0 +1,136 @@ +package telemetry + +import ( + "time" + + "go.uber.org/zap" +) + +// Schema v17 (Spec 126 FR-034, FR-038): the day_two block, personal edition +// only. STATE read fresh at every heartbeat build, never part of the +// reset-on-accept counter window. It carries closed enums only: the install +// anchor itself (a timestamp) never leaves the machine. + +// DayTwoPayload is the wire form of day_two. +type DayTwoPayload struct { + // InstallOrigin is "fresh" when the store holds an install anchor, and + // "existing" otherwise (an install upgraded from a build without one). + InstallOrigin string `json:"install_origin"` + // InstallAge is the UTC calendar-date distance from the anchor's date to + // the build date, bucketed; present only when InstallOrigin is "fresh". + InstallAge string `json:"install_age,omitempty"` + // SuccessScopeEver is the persisted, forward-only success scope. + SuccessScopeEver string `json:"success_scope_ever"` +} + +// day_two enum values. +const ( + InstallOriginFresh = "fresh" + InstallOriginExisting = "existing" + + InstallAgeD0to6 = "d0_6" + InstallAgeD7to13 = "d7_13" + InstallAgeD14Plus = "d14_plus" +) + +// editionServer is the edition string of the server-edition build +// (cmd/mcpproxy/edition_teams.go). day_two is omitted there. +const editionServer = "server" + +// utcDate truncates t to midnight of its UTC calendar date. +func utcDate(t time.Time) time.Time { + u := t.UTC() + return time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC) +} + +// InstallAgeBucket returns the install_age bucket for a heartbeat built at +// now: the difference in UTC calendar dates between the anchor's UTC date and +// now's UTC date (so the value is constant within one UTC date). 0–6 is d0_6, +// 7–13 d7_13, 14 and more d14_plus. A negative difference (clock skew, an +// anchor in the future) counts as d0_6. +func InstallAgeBucket(anchor, now time.Time) string { + // UTC has no DST, so every date is exactly 24h; rounding absorbs nothing + // but guards against a future change of the truncation. + days := int(utcDate(now).Sub(utcDate(anchor)).Round(time.Hour).Hours()) / 24 + switch { + case days < 7: + return InstallAgeD0to6 + case days < 14: + return InstallAgeD7to13 + default: + return InstallAgeD14Plus + } +} + +// BuildDayTwo assembles the day_two block from the install anchor (hasAnchor +// false for an existing install) and the lifetime success scope. +func BuildDayTwo(anchor time.Time, hasAnchor bool, scope SuccessScope, now time.Time) *DayTwoPayload { + dt := &DayTwoPayload{ + InstallOrigin: InstallOriginExisting, + SuccessScopeEver: scope.String(), + } + if hasAnchor { + dt.InstallOrigin = InstallOriginFresh + dt.InstallAge = InstallAgeBucket(anchor, now) + } + return dt +} + +// SetInstallAnchorProvider wires the install-anchor reader (Spec 126 FR-033): +// it returns the anchor, whether the store holds one, and a read error. The +// runtime installs it over the storage manager. Without it, or on the server +// edition, the heartbeat omits day_two. Call it before InitOutcomeWindow and +// Start. +func (s *Service) SetInstallAnchorProvider(fn func() (time.Time, bool, error)) { + s.installAnchorMu.Lock() + defer s.installAnchorMu.Unlock() + s.installAnchorProvider = fn + s.installAnchorRead = false +} + +// installAnchor reads the install anchor ONCE per process and returns that +// same answer to every caller: day_two (install_origin, install_age) and +// window_age. The anchor is written at startup before telemetry is wired and +// never rewritten, so one read is exact, and one shared value means the two +// objects can never disagree on "fresh". A disagreement would be fatal: the +// receiver answers 400 to window_age next to install_origin "existing", a +// non-2xx keeps the window pending, and the same rejected window would be +// re-sent forever. A read error is cached too: both objects then omit their +// anchor-derived fields for the whole process. wired is false when no +// provider is installed. +func (s *Service) installAnchor() (anchor time.Time, exists bool, err error, wired bool) { + s.installAnchorMu.Lock() + defer s.installAnchorMu.Unlock() + if s.installAnchorProvider == nil { + return time.Time{}, false, nil, false + } + if !s.installAnchorRead { + s.installAnchorValue, s.installAnchorExists, s.installAnchorErr = s.installAnchorProvider() + s.installAnchorRead = true + } + return s.installAnchorValue, s.installAnchorExists, s.installAnchorErr, true +} + +// buildDayTwo returns the day_two block for this heartbeat, or nil when it +// must be omitted: the server edition, no anchor provider or activation store +// wired, or a read error. A read error omits the block for this heartbeat +// rather than guessing "existing" or "none"; absence reads as "not measured". +func (s *Service) buildDayTwo(now time.Time) *DayTwoPayload { + if s.edition == editionServer || s.activationDB == nil { + return nil + } + anchor, ok, err, wired := s.installAnchor() + if !wired { + return nil + } + if err != nil { + s.logger.Debug("telemetry: install anchor unreadable; omitting day_two", zap.Error(err)) + return nil + } + scope, err := LoadSuccessScope(s.activationDB) + if err != nil { + s.logger.Debug("telemetry: success scope unreadable; omitting day_two", zap.Error(err)) + return nil + } + return BuildDayTwo(anchor, ok, scope, now) +} diff --git a/internal/telemetry/install_age_test.go b/internal/telemetry/install_age_test.go new file mode 100644 index 000000000..b0ccf76f3 --- /dev/null +++ b/internal/telemetry/install_age_test.go @@ -0,0 +1,124 @@ +package telemetry + +import ( + "context" + "errors" + "net/http" + "testing" + "time" +) + +// Spec 126 FR-034 (T083): install origin and age. +// +// install_age is the difference in UTC CALENDAR DATES between the anchor's +// UTC date and the UTC date the heartbeat is built on, so it is constant +// within one UTC date (spec update ce1c5c91c). + +func TestInstallAgeBucket_CalendarDateBoundaries(t *testing.T) { + anchor := time.Date(2026, 11, 1, 23, 50, 0, 0, time.UTC) // day D, 23:50 UTC + day := func(offset, h, m int) time.Time { + return time.Date(2026, 11, 1+offset, h, m, 0, 0, time.UTC) + } + cases := []struct { + name string + now time.Time + want string + }{ + {"same instant", anchor, "d0_6"}, + {"D+1 00:10, 20 minutes later", day(1, 0, 10), "d0_6"}, + {"D+6 23:59", day(6, 23, 59), "d0_6"}, + {"D+7 00:10, less than 7x24h later", day(7, 0, 10), "d7_13"}, + {"D+13 23:59", day(13, 23, 59), "d7_13"}, + {"D+14 00:00", day(14, 0, 0), "d14_plus"}, + {"D+400", day(400, 12, 0), "d14_plus"}, + {"future anchor (clock skew)", day(-3, 12, 0), "d0_6"}, + } + for _, c := range cases { + if got := InstallAgeBucket(anchor, c.now); got != c.want { + t.Errorf("%s: InstallAgeBucket = %q, want %q", c.name, got, c.want) + } + } +} + +// The date is the UTC date, whatever zone the times are expressed in. +func TestInstallAgeBucket_UsesUTCDates(t *testing.T) { + east := time.FixedZone("UTC+10", 10*3600) + anchor := time.Date(2026, 11, 2, 9, 50, 0, 0, east) // 2026-11-01 23:50 UTC + now := time.Date(2026, 11, 8, 10, 10, 0, 0, east) // 2026-11-08 00:10 UTC + if got := InstallAgeBucket(anchor, now); got != "d7_13" { + t.Fatalf("InstallAgeBucket = %q, want d7_13 (UTC dates 11-01 -> 11-08)", got) + } +} + +func TestBuildDayTwo_OriginAndAge(t *testing.T) { + anchor := time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC) + now := anchor.Add(8 * 24 * time.Hour) + + fresh := BuildDayTwo(anchor, true, SuccessScopeNonStarter, now) + if fresh == nil || fresh.InstallOrigin != "fresh" || fresh.InstallAge != "d7_13" || fresh.SuccessScopeEver != "non_starter" { + t.Fatalf("fresh install: got %+v", fresh) + } + + existing := BuildDayTwo(time.Time{}, false, SuccessScopeNone, now) + if existing == nil || existing.InstallOrigin != "existing" || existing.InstallAge != "" || existing.SuccessScopeEver != "none" { + t.Fatalf("existing install: got %+v (install_age must be absent)", existing) + } +} + +// day_two is personal-edition only. A server-edition heartbeat omits it even +// when the anchor provider is wired; upstream_outcomes stays. +func TestDayTwo_PersonalOnly(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + anchor := time.Now().UTC().Add(-time.Hour) + + for _, edition := range []string{"personal", "server"} { + t.Run(edition, func(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + svc := newOutcomeService(t, srv.URL, edition) + svc.SetActivationStore(NewActivationStore(), db) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { return anchor, true, nil }) + svc.sendHeartbeat(context.Background()) + got := received() + if len(got) != 1 { + t.Fatalf("received %d heartbeats", len(got)) + } + _, hasDayTwo := got[0].raw["day_two"] + if edition == "server" && hasDayTwo { + t.Fatal("server edition must omit day_two") + } + if edition == "personal" { + if !hasDayTwo || got[0].payload.DayTwo == nil { + t.Fatal("personal edition must carry day_two") + } + if dt := got[0].payload.DayTwo; dt.InstallOrigin != "fresh" || dt.InstallAge != "d0_6" || dt.SuccessScopeEver != "none" { + t.Fatalf("day_two = %+v", dt) + } + } + if _, ok := got[0].raw["upstream_outcomes"]; !ok { + t.Fatalf("%s edition must carry upstream_outcomes", edition) + } + }) + } +} + +// A provider error omits day_two for that heartbeat rather than reporting an +// install as existing; the heartbeat itself still goes out. +func TestDayTwo_AnchorReadErrorOmitsBlock(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + svc := newOutcomeService(t, srv.URL, "personal") + svc.SetActivationStore(NewActivationStore(), db) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { return time.Time{}, false, errors.New("boom") }) + svc.sendHeartbeat(context.Background()) + got := received() + if len(got) != 1 { + t.Fatalf("received %d heartbeats", len(got)) + } + if _, ok := got[0].raw["day_two"]; ok { + t.Fatal("an unreadable anchor must omit day_two, not guess an origin") + } +} diff --git a/internal/telemetry/outcome_window.go b/internal/telemetry/outcome_window.go new file mode 100644 index 000000000..2837e9cec --- /dev/null +++ b/internal/telemetry/outcome_window.go @@ -0,0 +1,164 @@ +package telemetry + +import ( + "time" + + "go.etcd.io/bbolt" + "go.uber.org/zap" +) + +// Spec 126 FR-036: the coverage of upstream_outcomes, and (window_age) the +// install age at which each window opened. +// +// A persisted "undelivered window" marker in the activation bucket says +// whether the previous process left recorded outcomes that never reached an +// accepted send: +// +// - set (true) by the first outcome recorded after process start or after +// each Drain (a counter window's first outcome); +// - cleared (false) on an accepted send — the graceful-shutdown flush +// included — only when no outcome was recorded since the Drain whose +// snapshot was accepted. sendHeartbeatWithOneShots drains at the START +// of a send, so outcomes recorded while it (or its retries) are in flight +// are still undelivered when it is accepted; +// - absent only on a store no schema-17 build has run on yet. Every start +// writes it as false when absent, after deciding the first window. +// +// At process start the first window is "partial" when the marker is set, or +// when it is absent and install_origin is "existing" (once). A fresh origin +// with an absent marker (a crash before the start-time write) is "full", as +// are a plain restart after a delivered window and every window after an +// accepted send with nothing recorded since its drain. Both marker writes run +// under the outcome window's own small mutex (outcomeWindow in +// upstream_outcomes.go), together with the outcome increment and Drain's +// swap, so a stale clear can never overwrite a set. deliveryMu is NOT used: +// it is held across the HTTP POST, and a tool call must never wait on +// network I/O. +// +// Each window also opens at a time — registry creation (process start) or the +// last Drain — and window_age is the install age at that time, frozen into +// the drained snapshot. + +// activationKeyOutcomeWindowUndelivered is the marker's key in the activation +// bucket: one byte, 0x01 set, 0x00 cleared. +const activationKeyOutcomeWindowUndelivered = "outcome_window_undelivered" + +// loadOutcomeWindowMarker returns the marker and whether it exists. +func loadOutcomeWindowMarker(db *bbolt.DB) (set, exists bool, err error) { + err = db.View(func(tx *bbolt.Tx) error { + b := activationBucket(tx) + if b == nil { + return nil + } + raw := b.Get([]byte(activationKeyOutcomeWindowUndelivered)) + if raw == nil { + return nil + } + exists = true + set = decodeBool(raw) + return nil + }) + return set, exists, err +} + +func storeOutcomeWindowMarker(db *bbolt.DB, set bool) error { + return db.Update(func(tx *bbolt.Tx) error { + b, err := activationBucketForWrite(tx) + if err != nil { + return err + } + return b.Put([]byte(activationKeyOutcomeWindowUndelivered), encodeBool(set)) + }) +} + +// InitOutcomeWindow sets up the first counter window of this process. The +// runtime calls it once at startup, after SetActivationStore and +// SetInstallAnchorProvider (and after storage recorded the install anchor). +// storeWasEmpty is true when config.db held no prior data when this process +// opened it. +// +// It installs the window_age mapping (from the once-per-process anchor read), +// decides the first window's coverage from the persisted marker, writes the +// marker as cleared when absent, and installs the marker writer, which the +// outcome window then drives under its own mutex. Without an activation DB no +// marker can be kept, so coverage stays full. +func (s *Service) InitOutcomeWindow(storeWasEmpty bool) { + reg := s.registry + if reg == nil { + return + } + if fn := s.outcomeWindowAgeFunc(); fn != nil { + reg.SetOutcomeWindowAgeFunc(fn) + } + db := s.activationDB + if db == nil { + return + } + + set, exists, err := loadOutcomeWindowMarker(db) + switch { + case err != nil: + // Unreadable marker: the predecessor's delivery is unknown, so the + // window is not claimed to be complete (a store that was empty at + // open has no predecessor). + s.logger.Debug("telemetry: outcome window marker unreadable; first window partial", zap.Error(err)) + if !storeWasEmpty { + reg.MarkOutcomeWindowPartial() + } + case !exists: + // Absent: no schema-17 build has run on this store yet — partial + // once, but only when install_origin is "existing" (an upgrade, + // whose older build's unsent counts are unknown). With an anchor + // (install_origin "fresh") an absent marker can only mean this + // install crashed before its first start-time write: full. + if !s.installOriginFresh() { + reg.MarkOutcomeWindowPartial() + } + s.writeOutcomeMarker(false) + case set: + reg.MarkOutcomeWindowPartial() + } + + reg.SetOutcomeMarkerWriter(s.writeOutcomeMarker) +} + +// writeOutcomeMarker persists the undelivered-window marker. The outcome +// window calls it under its own mutex (see outcomeWindow); errors are logged +// only: a lost write can only misreport coverage, never block a call. +func (s *Service) writeOutcomeMarker(set bool) { + db := s.activationDB + if db == nil { + return + } + if err := storeOutcomeWindowMarker(db, set); err != nil { + s.logger.Debug("telemetry: failed to write outcome window marker", zap.Bool("set", set), zap.Error(err)) + } +} + +// onCounterWindowAccepted runs after a 2xx (the shutdown flush included): it +// clears the undelivered marker unless an outcome was recorded since the +// accepted snapshot's drain. +func (s *Service) onCounterWindowAccepted() { + s.registry.ClearOutcomeMarkerIfIdle() +} + +// installOriginFresh reports whether day_two would say install_origin +// "fresh": the one anchor read of this process found an anchor. +func (s *Service) installOriginFresh() bool { + _, ok, err, wired := s.installAnchor() + return wired && err == nil && ok +} + +// outcomeWindowAgeFunc returns the window_age mapping, or nil when window_age +// must be omitted: the server edition, no anchor provider, an existing +// install (no anchor) or an unreadable anchor. +func (s *Service) outcomeWindowAgeFunc() func(time.Time) string { + if s.edition == editionServer { + return nil + } + anchor, ok, err, wired := s.installAnchor() + if !wired || err != nil || !ok { + return nil + } + return func(opened time.Time) string { return InstallAgeBucket(anchor, opened) } +} diff --git a/internal/telemetry/outcome_window_test.go b/internal/telemetry/outcome_window_test.go new file mode 100644 index 000000000..941eba2d0 --- /dev/null +++ b/internal/telemetry/outcome_window_test.go @@ -0,0 +1,478 @@ +package telemetry + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "sync" + "testing" + "time" + + "go.etcd.io/bbolt" +) + +// Spec 126 FR-036: coverage comes from a persisted "undelivered window" +// marker, so a plain restart after a delivered window is "full". Each +// "process" below is a new Service over the same activation DB. + +func openOutcomeDB(t *testing.T) (*bbolt.DB, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "outcome.db") + db, err := bbolt.Open(path, 0o600, &bbolt.Options{Timeout: 2 * time.Second}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + return db, path +} + +// startOutcomeProcess starts one "process": storeWasEmpty is whether +// config.db held no data at open, fresh whether the store holds an install +// anchor (install_origin "fresh"). A fresh install stays fresh on every later +// start; only its first start has storeWasEmpty. +func startOutcomeProcess(t *testing.T, endpoint string, db *bbolt.DB, storeWasEmpty, fresh bool) *Service { + t.Helper() + svc := newOutcomeService(t, endpoint, "personal") + svc.SetActivationStore(NewActivationStore(), db) + anchor := time.Now().UTC().Add(-time.Hour) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { + if !fresh { + return time.Time{}, false, nil + } + return anchor, true, nil + }) + svc.InitOutcomeWindow(storeWasEmpty) + return svc +} + +func coverageOf(svc *Service) string { return svc.Registry().Snapshot().UpstreamOutcomes.Coverage } + +func markerOf(t *testing.T, db *bbolt.DB) (set, exists bool) { + t.Helper() + set, exists, err := loadOutcomeWindowMarker(db) + if err != nil { + t.Fatal(err) + } + return set, exists +} + +func TestOutcomeWindow_FreshInstallIsFull(t *testing.T) { + db, _ := openOutcomeDB(t) + svc := startOutcomeProcess(t, "http://127.0.0.1:1", db, true, true) + if got := coverageOf(svc); got != OutcomeCoverageFull { + t.Fatalf("fresh install first window: %q, want full", got) + } + if set, exists := markerOf(t, db); !exists || set { + t.Fatalf("marker after a fresh start: set=%v exists=%v, want written as cleared", set, exists) + } + // The fresh install restarts before any call: the store is no longer + // empty at open, but the marker exists and is clear, so the second start + // is full too. + second := startOutcomeProcess(t, "http://127.0.0.1:1", db, false, true) + if got := coverageOf(second); got != OutcomeCoverageFull { + t.Fatalf("second start of a fresh install with no calls: %q, want full", got) + } +} + +// FR-036 (r4): an outcome recorded while a send is in flight does not wait +// for the network, and the accept that follows can never leave the marker +// false. The request handler blocks the 2xx until an outcome recorded from +// another goroutine has returned (bounded, so a tool call stuck behind the +// HTTP POST fails the test instead of hanging it): the outcome lands after +// the drain's swap, the accept then sees it and keeps the marker set. +func TestOutcomeWindow_InFlightOutcomeNeverBlocksNorLeavesMarkerFalse(t *testing.T) { + db, _ := openOutcomeDB(t) + var p *Service + recorded := make(chan time.Duration, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + go func() { + start := time.Now() + p.Registry().RecordUpstreamOutcome(true, false) // a tool call during the POST + recorded <- time.Since(start) + }() + select { + case <-recorded: + case <-time.After(5 * time.Second): + t.Error("an outcome recorded during an in-flight send blocked on the send") + } + w.WriteHeader(http.StatusNoContent) + })) + defer srv.Close() + p = startOutcomeProcess(t, srv.URL, db, true, true) + p.Registry().RecordUpstreamOutcome(true, false) + p.sendHeartbeat(context.Background()) // drain -> handler (outcome lands) -> 2xx -> accept + if !p.Registry().HasPendingUpstreamOutcomes() { + t.Fatal("precondition: the in-flight outcome is in the next window") + } + if set, _ := markerOf(t, db); !set { + t.Fatal("the accept left the marker false while an outcome recorded after the drain is undelivered") + } +} + +// The first start of this build on an existing store has no marker yet: that +// window counts as partial, once. +func TestOutcomeWindow_FirstStartOnExistingStoreIsPartialOnce(t *testing.T) { + db, _ := openOutcomeDB(t) + first := startOutcomeProcess(t, "http://127.0.0.1:1", db, false, false) + if got := coverageOf(first); got != OutcomeCoveragePartial { + t.Fatalf("first start of this build on an existing store: %q, want partial", got) + } + // That process recorded nothing; the next start is full. + second := startOutcomeProcess(t, "http://127.0.0.1:1", db, false, false) + if got := coverageOf(second); got != OutcomeCoverageFull { + t.Fatalf("second start: %q, want full (partial counts once)", got) + } +} + +// A restart after a delivered window is full; a restart after an undelivered +// one is partial. +func TestOutcomeWindow_RestartCoverageFollowsDelivery(t *testing.T) { + srv, _, setStatus := newOutcomeCaptureServer(t) + db, _ := openOutcomeDB(t) + + p1 := startOutcomeProcess(t, srv.URL, db, true, true) + p1.Registry().RecordUpstreamOutcome(true, false) + if set, _ := markerOf(t, db); !set { + t.Fatal("the first outcome of a window must set the marker") + } + setStatus(http.StatusNoContent) + p1.sendHeartbeat(context.Background()) + if set, _ := markerOf(t, db); set { + t.Fatal("an accepted send must clear the marker") + } + p2 := startOutcomeProcess(t, srv.URL, db, false, true) + if got := coverageOf(p2); got != OutcomeCoverageFull { + t.Fatalf("restart after a delivered window: %q, want full", got) + } + + p2.Registry().RecordUpstreamOutcome(false, false) + setStatus(http.StatusInternalServerError) + p2.sendHeartbeat(context.Background()) // rejected: the window stays undelivered + p3 := startOutcomeProcess(t, srv.URL, db, false, true) + if got := coverageOf(p3); got != OutcomeCoveragePartial { + t.Fatalf("restart after an undelivered window: %q, want partial", got) + } +} + +// The send drains at its start, so an outcome recorded while it (or its +// retries) is in flight is undelivered when the retry is accepted: the send +// fails, outcomes keep arriving, the retry is accepted, the process is killed, +// and the next start must report the first window "partial". +func TestOutcomeWindow_AcceptKeepsMarkerForNextWindowOutcome(t *testing.T) { + srv, _, setStatus := newOutcomeCaptureServer(t) + db, _ := openOutcomeDB(t) + p := startOutcomeProcess(t, srv.URL, db, true, true) + p.Registry().RecordUpstreamOutcome(true, false) + p.sendHeartbeat(context.Background()) // 500: drained, pending + p.Registry().RecordUpstreamOutcome(true, false) + setStatus(http.StatusNoContent) + p.sendHeartbeat(context.Background()) // accepts the first window only + if set, _ := markerOf(t, db); !set { + t.Fatal("the next window holds an outcome: the marker must stay set") + } + next := startOutcomeProcess(t, srv.URL, db, false, true) + if got := coverageOf(next); got != OutcomeCoveragePartial { + t.Fatalf("restart with that window unsent: %q, want partial", got) + } +} + +// The graceful-shutdown flush clears the marker when it lands. +func TestOutcomeWindow_ShutdownFlushClearsMarker(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + db, _ := openOutcomeDB(t) + p := startOutcomeProcess(t, srv.URL, db, true, true) + p.Registry().RecordUpstreamOutcome(true, false) + p.flushEligible.Store(true) + p.flushFinalHeartbeat() + if n := len(received()); n != 1 { + t.Fatalf("flush sent %d heartbeats, want 1", n) + } + if set, _ := markerOf(t, db); set { + t.Fatal("a landed shutdown flush must clear the marker") + } +} + +// window_age is the install age when the window OPENED — process start or the +// last Drain, never the accepted send — frozen into the drained snapshot, so a +// retry re-sends the age it was drained with. +func TestOutcomeWindow_WindowAgeOpensAtDrainAndIsFrozen(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + db, _ := openOutcomeDB(t) + start := time.Now().UTC() + anchor := start.Add(-time.Hour) + svc := newOutcomeService(t, srv.URL, "personal") + svc.SetActivationStore(NewActivationStore(), db) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { return anchor, true, nil }) + reg := svc.Registry() + var ( + mu sync.Mutex + clock = start + ) + setClock := func(t time.Time) { + mu.Lock() + clock = t + mu.Unlock() + } + reg.now = func() time.Time { + mu.Lock() + defer mu.Unlock() + return clock + } + reg.outcomes.mu.Lock() + reg.outcomes.openedAt = start // process start + reg.outcomes.mu.Unlock() + svc.InitOutcomeWindow(true) + reg.RecordUpstreamOutcome(true, false) + + setClock(anchor.AddDate(0, 0, 8)) // the first send drains on day 8 + svc.sendHeartbeat(context.Background()) // 500: window 1 frozen, window 2 opens now + reg.RecordUpstreamOutcome(true, false) + setClock(anchor.AddDate(0, 0, 15)) // the retry is accepted on day 15 + setStatus(http.StatusNoContent) + svc.sendHeartbeat(context.Background()) // retry of window 1, accepted + svc.sendHeartbeat(context.Background()) // window 2 + + got := received() + if len(got) != 3 { + t.Fatalf("received %d heartbeats", len(got)) + } + if a := got[0].payload.UpstreamOutcomes.WindowAge; a != InstallAgeD0to6 { + t.Fatalf("window 1 opened at process start (d0_6), got %q", a) + } + if a := got[1].payload.UpstreamOutcomes.WindowAge; a != InstallAgeD0to6 { + t.Fatalf("the retry must re-send the frozen window_age d0_6, got %q", a) + } + if a := got[2].payload.UpstreamOutcomes.WindowAge; a != InstallAgeD7to13 { + t.Fatalf("window 2 opened at the drain on day 8 (d7_13), not at the accept on day 15; got %q", a) + } +} + +// window_age is absent on an existing install and on the server edition. +func TestOutcomeWindow_WindowAgeOnlyOnFreshPersonal(t *testing.T) { + cases := []struct { + name string + edition string + hasAnchor bool + want string + }{ + {"personal fresh", "personal", true, InstallAgeD0to6}, + {"personal existing", "personal", false, ""}, + {"server fresh", "server", true, ""}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + db, _ := openOutcomeDB(t) + svc := newOutcomeService(t, "http://127.0.0.1:1", c.edition) + svc.SetActivationStore(NewActivationStore(), db) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { + return time.Now().UTC(), c.hasAnchor, nil + }) + svc.InitOutcomeWindow(c.hasAnchor) + if got := svc.Registry().Drain().UpstreamOutcomes.WindowAge; got != c.want { + t.Fatalf("window_age = %q, want %q", got, c.want) + } + }) + } +} + +// FR-036 (r3): an absent marker gives "partial" once only when install_origin +// is "existing". A fresh install that crashed before its start-time marker +// write (anchor present, marker absent) starts "full". +func TestOutcomeWindow_AbsentMarkerOnFreshOriginIsFull(t *testing.T) { + db, _ := openOutcomeDB(t) + if _, exists := markerOf(t, db); exists { + t.Fatal("precondition: no marker") + } + p := startOutcomeProcess(t, "http://127.0.0.1:1", db, false, true) + if got := coverageOf(p); got != OutcomeCoverageFull { + t.Fatalf("fresh origin, absent marker: %q, want full", got) + } +} + +// FR-036 (r3): the first window opens at process start. The marker is written +// false at start, outcomes arrive before the first send, the process is +// killed: the next start reports "partial". +func TestOutcomeWindow_OutcomesBeforeFirstSendThenKillIsPartial(t *testing.T) { + db, _ := openOutcomeDB(t) + p := startOutcomeProcess(t, "http://127.0.0.1:1", db, true, true) + if set, exists := markerOf(t, db); !exists || set { + t.Fatalf("start must write the marker false: set=%v exists=%v", set, exists) + } + p.Registry().RecordUpstreamOutcome(true, false) + p.Registry().RecordUpstreamOutcome(false, false) + // killed: no send, no flush + next := startOutcomeProcess(t, "http://127.0.0.1:1", db, false, true) + if got := coverageOf(next); got != OutcomeCoveragePartial { + t.Fatalf("restart after outcomes that never left: %q, want partial", got) + } +} + +// FR-034/FR-035 (r3): the anchor is read once per process, and day_two and +// window_age use that one answer, so they can never disagree. +func TestOutcomeWindow_AnchorReadOncePerProcess(t *testing.T) { + db, _ := openOutcomeDB(t) + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + svc := newOutcomeService(t, srv.URL, "personal") + svc.SetActivationStore(NewActivationStore(), db) + var calls int + answers := []bool{true, false, false} // a provider that would flip if re-read + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { + ok := answers[calls%len(answers)] + calls++ + return time.Now().UTC(), ok, nil + }) + svc.InitOutcomeWindow(true) + for i := 0; i < 3; i++ { + svc.Registry().RecordUpstreamOutcome(true, false) + svc.sendHeartbeat(context.Background()) + } + if calls != 1 { + t.Fatalf("anchor provider called %d times, want once per process", calls) + } + for i, hb := range received() { + if hb.payload.DayTwo == nil || hb.payload.DayTwo.InstallOrigin != InstallOriginFresh { + t.Fatalf("heartbeat %d: day_two = %+v, want fresh", i, hb.payload.DayTwo) + } + if hb.payload.UpstreamOutcomes.WindowAge == "" { + t.Fatalf("heartbeat %d: a fresh install must carry window_age", i) + } + } +} + +// FR-036 (r3): the accept path's clear and the outcome path's set are +// serialised with the accept decision, so a stale "false" never overwrites a +// "true". Hammer concurrent outcomes against accepted sends; whenever the live +// window still holds outcomes at the end, the marker must be set. Run under +// -race. +func TestOutcomeWindow_MarkerNeverStaleUnderConcurrency(t *testing.T) { + srv, _, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + for round := 0; round < 20; round++ { + db, _ := openOutcomeDB(t) + p := startOutcomeProcess(t, srv.URL, db, true, true) + var wg sync.WaitGroup + for w := 0; w < 4; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 50; i++ { + p.Registry().RecordUpstreamOutcome(i%2 == 0, false) + } + }() + } + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 10; i++ { + p.sendHeartbeat(context.Background()) + } + }() + wg.Wait() + set, _ := markerOf(t, db) + if p.Registry().HasPendingUpstreamOutcomes() && !set { + t.Fatalf("round %d: outcomes are undelivered but the marker is clear", round) + } + // Deliver the rest: with nothing recorded since, the marker clears. + p.sendHeartbeat(context.Background()) + if p.Registry().HasPendingUpstreamOutcomes() { + continue + } + if set, _ := markerOf(t, db); set { + t.Fatalf("round %d: everything delivered but the marker is still set", round) + } + } +} + +// FR-036 (r3): an outcome recorded while a send is IN FLIGHT (after its drain, +// before its 2xx) belongs to the next window, so the accept must leave the +// marker set; a kill then makes the next start "partial". +func TestOutcomeWindow_OutcomeDuringInFlightSendKeepsMarker(t *testing.T) { + db, _ := openOutcomeDB(t) + var p *Service + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + p.Registry().RecordUpstreamOutcome(true, false) // the request is in flight + w.WriteHeader(http.StatusNoContent) + })) + defer srv.Close() + p = startOutcomeProcess(t, srv.URL, db, true, true) + p.Registry().RecordUpstreamOutcome(true, false) + p.sendHeartbeat(context.Background()) // drains, then the handler records, then 2xx + if !p.Registry().HasPendingUpstreamOutcomes() { + t.Fatal("precondition: the in-flight outcome is in the next window") + } + if set, _ := markerOf(t, db); !set { + t.Fatal("an outcome recorded after the accepted snapshot's drain is undelivered: the marker must stay set") + } + next := startOutcomeProcess(t, srv.URL, db, false, true) + if got := coverageOf(next); got != OutcomeCoveragePartial { + t.Fatalf("restart after the kill: %q, want partial", got) + } +} + +// FR-035 (r4): an outcome is pending usage data on its own. A window whose +// only content is an outcome (dispatch counter 0) must still be sent by the +// graceful-shutdown flush, and Reset must zero it. +func TestOutcomeWindow_OutcomeOnlyWindowIsFlushedAndReset(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + db, _ := openOutcomeDB(t) + p := startOutcomeProcess(t, srv.URL, db, true, true) + reg := p.Registry() + reg.RecordUpstreamOutcome(false, false) + if got := reg.Snapshot().UpstreamToolCallCountBucket; got != "0" { + t.Fatalf("precondition: dispatch bucket %q, want 0", got) + } + if !reg.HasPendingCounters() { + t.Fatal("an outcome alone must count as pending for the shutdown flush") + } + p.flushEligible.Store(true) + p.flushFinalHeartbeat() + got := received() + if len(got) != 1 { + t.Fatalf("the shutdown flush sent %d heartbeats, want 1", len(got)) + } + if o := got[0].payload.UpstreamOutcomes; o == nil || o.Unusable != "1-10" { + t.Fatalf("flushed window = %+v, want unusable 1-10", o) + } + if set, _ := markerOf(t, db); set { + t.Fatal("the landed flush must clear the marker") + } + + reg.RecordUpstreamOutcome(true, false) + reg.Reset() + if reg.HasPendingCounters() || reg.HasPendingUpstreamOutcomes() { + t.Fatal("Reset must zero the outcome counts") + } +} + +// FR-035 (r4): the server edition sends upstream_outcomes without window_age +// (it has no install_origin), even with an anchor provider wired. +func TestOutcomeWindow_ServerEditionSendsNoWindowAge(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + db, _ := openOutcomeDB(t) + svc := newOutcomeService(t, srv.URL, "server") + svc.SetActivationStore(NewActivationStore(), db) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { return time.Now().UTC(), true, nil }) + svc.InitOutcomeWindow(true) + svc.Registry().RecordUpstreamOutcome(true, false) + svc.sendHeartbeat(context.Background()) + got := received() + if len(got) != 1 { + t.Fatalf("received %d heartbeats", len(got)) + } + var obj map[string]json.RawMessage + if err := json.Unmarshal(got[0].raw["upstream_outcomes"], &obj); err != nil { + t.Fatal(err) + } + if _, has := obj["window_age"]; has { + t.Fatalf("server edition sent window_age: %s", got[0].raw["upstream_outcomes"]) + } + if _, has := got[0].raw["day_two"]; has { + t.Fatal("server edition sent day_two") + } +} diff --git a/internal/telemetry/payload_privacy_test.go b/internal/telemetry/payload_privacy_test.go index 89f11f1c5..0c20fc5b9 100644 --- a/internal/telemetry/payload_privacy_test.go +++ b/internal/telemetry/payload_privacy_test.go @@ -144,7 +144,7 @@ func TestPayloadHasNoForbiddenSubstrings(t *testing.T) { // Sanity check: the payload should still contain the legitimate fields, // otherwise we've over-redacted. for _, required := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"surface_requests"`, `"builtin_tool_calls"`, `"upstream_tool_call_count_bucket"`, diff --git a/internal/telemetry/payload_v17_test.go b/internal/telemetry/payload_v17_test.go new file mode 100644 index 000000000..67ab61831 --- /dev/null +++ b/internal/telemetry/payload_v17_test.go @@ -0,0 +1,213 @@ +package telemetry + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "sort" + "sync/atomic" + "testing" + "time" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// Spec 126 T012: the schema-17 payload. The key sets below are the schema-17 +// part of specs/126-day-two-activation/contracts/telemetry-day-two.schema.json. + +var ( + v17UpstreamOutcomesKeys = []string{"coverage", "succeeded", "succeeded_non_starter", "unusable"} + v17UpstreamOutcomesKeysFresh = []string{"coverage", "succeeded", "succeeded_non_starter", "unusable", "window_age"} + v17DayTwoKeysFresh = []string{"install_age", "install_origin", "success_scope_ever"} + v17DayTwoKeysExisting = []string{"install_origin", "success_scope_ever"} +) + +func v17Keys(t *testing.T, raw json.RawMessage) []string { + t.Helper() + var obj map[string]json.RawMessage + if err := json.Unmarshal(raw, &obj); err != nil || obj == nil { + t.Fatalf("not an object: %s (%v)", raw, err) + } + keys := make([]string, 0, len(obj)) + for k := range obj { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func v17EqualStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestPayloadV17(t *testing.T) { + if SchemaVersion != 17 { + t.Fatalf("SchemaVersion = %d, want 17 (Spec 126 PR-A)", SchemaVersion) + } + + cases := []struct { + name string + edition string + hasAnchor bool + wantDayTwo []string // nil: day_two must be absent + wantOutKeys []string + wantOrigin string + wantPartial bool + }{ + {name: "personal fresh install", edition: "personal", hasAnchor: true, wantDayTwo: v17DayTwoKeysFresh, wantOutKeys: v17UpstreamOutcomesKeysFresh, wantOrigin: "fresh"}, + {name: "personal existing install", edition: "personal", hasAnchor: false, wantDayTwo: v17DayTwoKeysExisting, wantOutKeys: v17UpstreamOutcomesKeys, wantOrigin: "existing", wantPartial: true}, + {name: "server edition", edition: "server", hasAnchor: true, wantDayTwo: nil, wantOutKeys: v17UpstreamOutcomesKeys}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + svc := newOutcomeService(t, srv.URL, c.edition) + svc.SetActivationStore(NewActivationStore(), db) + anchor := time.Now().UTC().Add(-2 * time.Hour) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { + if !c.hasAnchor { + return time.Time{}, false, nil + } + return anchor, true, nil + }) + // A fresh install's store was empty at open; the existing install + // starts this build for the first time (no marker yet: partial). + svc.InitOutcomeWindow(c.hasAnchor) + svc.Registry().RecordUpstreamOutcome(true, false) + if err := RecordSuccessScope(db, false); err != nil { + t.Fatal(err) + } + + svc.sendHeartbeat(context.Background()) + got := received() + if len(got) != 1 { + t.Fatalf("received %d heartbeats", len(got)) + } + raw := got[0].raw + if string(raw["schema_version"]) != "17" { + t.Fatalf("schema_version = %s, want 17", raw["schema_version"]) + } + if keys := v17Keys(t, raw["upstream_outcomes"]); !v17EqualStrings(keys, c.wantOutKeys) { + t.Fatalf("upstream_outcomes keys = %v, want %v", keys, c.wantOutKeys) + } + wantCoverage := OutcomeCoverageFull + if c.wantPartial { + wantCoverage = OutcomeCoveragePartial + } + if o := got[0].payload.UpstreamOutcomes; o.Succeeded != "1-10" || o.SucceededNonStarter != "1-10" || o.Unusable != "0" || o.Coverage != wantCoverage { + t.Fatalf("upstream_outcomes = %+v", o) + } + + rawDayTwo, has := raw["day_two"] + if c.wantDayTwo == nil { + if has { + t.Fatalf("day_two must be absent: %s", rawDayTwo) + } + return + } + if !has { + t.Fatal("day_two missing") + } + if keys := v17Keys(t, rawDayTwo); !v17EqualStrings(keys, c.wantDayTwo) { + t.Fatalf("day_two keys = %v, want %v", keys, c.wantDayTwo) + } + dt := got[0].payload.DayTwo + if dt.InstallOrigin != c.wantOrigin || dt.SuccessScopeEver != "non_starter" { + t.Fatalf("day_two = %+v", dt) + } + if c.hasAnchor && dt.InstallAge != "d0_6" { + t.Fatalf("install_age = %q, want d0_6", dt.InstallAge) + } + + // Every built payload must pass the anonymity scanner. + body, err := json.Marshal(got[0].payload) + if err != nil { + t.Fatal(err) + } + if err := ScanForPII(body); err != nil { + t.Fatalf("schema-17 payload rejected by ScanForPII: %v", err) + } + // quickstart L4: one sample payload. + t.Logf("schema-17 sample (%s): upstream_outcomes=%s day_two=%s", c.name, raw["upstream_outcomes"], rawDayTwo) + }) + } +} + +// Opt-out sends nothing: no heartbeat, and the day_two provider is never +// consulted. +func TestPayloadV17_OptOutSendsNothing(t *testing.T) { + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusNoContent) + })) + defer server.Close() + cfg := &config.Config{Telemetry: &config.TelemetryConfig{ + Enabled: boolPtr(true), AnonymousID: "anon-xyz", Endpoint: server.URL, + }} + svc := New(cfg, "", "v1.2.3", "personal", zap.NewNop()) + var calls atomic.Int32 + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { + calls.Add(1) + return time.Now(), true, nil + }) + svc.Registry().RecordUpstreamOutcome(true, false) + svc.optedOut.Store(true) + + svc.sendHeartbeat(context.Background()) + + if hits.Load() != 0 { + t.Fatalf("heartbeat transmitted after opt-out: %d", hits.Load()) + } + if calls.Load() != 0 { + t.Fatalf("install-anchor provider consulted %d times after opt-out", calls.Load()) + } +} + +// An install with origin "existing" sends no window_age (the receiver rejects +// that combination), even after a window opened at an accepted send. +func TestPayloadV17_ExistingInstallSendsNoWindowAge(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + srv, captured, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + svc := newOutcomeService(t, srv.URL, "personal") + svc.SetActivationStore(NewActivationStore(), db) + svc.SetInstallAnchorProvider(func() (time.Time, bool, error) { return time.Time{}, false, nil }) + svc.InitOutcomeWindow(false) + svc.Registry().RecordUpstreamOutcome(true, false) + svc.sendHeartbeat(context.Background()) // the first window + svc.Registry().RecordUpstreamOutcome(true, false) + svc.sendHeartbeat(context.Background()) // a window opened at an accepted send + + got := captured() + if len(got) != 2 { + t.Fatalf("received %d heartbeats", len(got)) + } + for i, hb := range got { + if hb.payload.DayTwo == nil || hb.payload.DayTwo.InstallOrigin != InstallOriginExisting { + t.Fatalf("heartbeat %d: day_two = %+v, want existing", i, hb.payload.DayTwo) + } + var obj map[string]json.RawMessage + if err := json.Unmarshal(hb.raw["upstream_outcomes"], &obj); err != nil { + t.Fatal(err) + } + if _, has := obj["window_age"]; has { + t.Fatalf("heartbeat %d: an existing install sent window_age: %s", i, hb.raw["upstream_outcomes"]) + } + } +} diff --git a/internal/telemetry/payload_v2_test.go b/internal/telemetry/payload_v2_test.go index 501ecd6b6..a3627551d 100644 --- a/internal/telemetry/payload_v2_test.go +++ b/internal/telemetry/payload_v2_test.go @@ -88,8 +88,8 @@ func TestHeartbeatPayloadV2Marshal(t *testing.T) { payload := svc.BuildPayload() - if payload.SchemaVersion != 16 { - t.Errorf("schema_version = %d, want 16", payload.SchemaVersion) + if payload.SchemaVersion != 17 { + t.Errorf("schema_version = %d, want 17", payload.SchemaVersion) } if payload.AnonymousID != "fixed-id" { t.Errorf("anonymous_id = %q", payload.AnonymousID) @@ -135,7 +135,7 @@ func TestHeartbeatPayloadV2Marshal(t *testing.T) { } js := string(data) for _, key := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"surface_requests"`, `"builtin_tool_calls"`, `"upstream_tool_call_count_bucket":"11-100"`, diff --git a/internal/telemetry/payload_v7_test.go b/internal/telemetry/payload_v7_test.go index e13ba2e1b..8fc388163 100644 --- a/internal/telemetry/payload_v7_test.go +++ b/internal/telemetry/payload_v7_test.go @@ -17,8 +17,8 @@ func TestSchemaVersionIsAtLeastV7(t *testing.T) { if SchemaVersion < 7 { t.Fatalf("SchemaVersion = %d, want >= 7 (Spec 080 FR-014)", SchemaVersion) } - if SchemaVersion != 16 { - t.Fatalf("SchemaVersion = %d, want 16 (v16 TPA bundle refresh counters)", SchemaVersion) + if SchemaVersion != 17 { + t.Fatalf("SchemaVersion = %d, want 17 (v17 completion counters; the v16 TPA refresh counters ride every later version)", SchemaVersion) } } @@ -78,7 +78,7 @@ func TestPayloadV7_FullyPopulatedPassesScanner(t *testing.T) { } for _, required := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"wizard_shown":true`, `"wizard_connect_step":"completed_external"`, `"web_ui_opened":3`, @@ -109,8 +109,8 @@ func TestPayloadV7_ZeroNewFieldsShapeCompatibleWithV6(t *testing.T) { } js := string(data) - if !strings.Contains(js, `"schema_version":16`) { - t.Errorf("expected schema_version:16 even on a zero-valued payload, got:\n%s", js) + if !strings.Contains(js, `"schema_version":17`) { + t.Errorf("expected schema_version:17 even on a zero-valued payload, got:\n%s", js) } for _, forbidden := range []string{ `"wizard_shown"`, diff --git a/internal/telemetry/registry.go b/internal/telemetry/registry.go index 3a2a62550..79823ad5f 100644 --- a/internal/telemetry/registry.go +++ b/internal/telemetry/registry.go @@ -5,6 +5,7 @@ import ( "strings" "sync" "sync/atomic" + "time" ) // Surface identifies which client surface originated a request. @@ -156,6 +157,14 @@ type CounterRegistry struct { tpaBundleRefreshRejections int64 tpaBundleRefreshUnavailable int64 tpaBundleReprotectHits int64 + + // Schema v17 (Spec 126 FR-035, FR-036): the completion window. It has + // its own small mutex (see outcomeWindow in upstream_outcomes.go), never + // held across network I/O, and is read before mu is taken. + outcomes outcomeWindow + + // now is the registry clock (time.Now; tests replace it). + now func() time.Time } // NewCounterRegistry creates an empty registry. All counters start at zero. @@ -166,6 +175,8 @@ func NewCounterRegistry() *CounterRegistry { errorCategories: make(map[ErrorCategory]int64), doctorChecks: make(map[string]*DoctorCounts), tpaFindings: make(map[string]int64), + now: time.Now, + outcomes: outcomeWindow{openedAt: time.Now().UTC()}, } } @@ -460,6 +471,10 @@ type RegistrySnapshot struct { TPABundleRefreshRejections int64 `json:"tpa_bundle_refresh_rejections"` TPABundleRefreshUnavailable int64 `json:"tpa_bundle_refresh_unavailable"` TPABundleReprotectHits int64 `json:"tpa_bundle_reprotect_hits"` + + // Schema v17 (Spec 126 FR-035, FR-036): the completion window, bucketed, + // with the window's own coverage flag and opening age. + UpstreamOutcomes UpstreamOutcomes `json:"upstream_outcomes"` } // TPAScannerStats projects the schema-v8 scanner counters out of the snapshot, @@ -517,6 +532,8 @@ func (r *CounterRegistry) Snapshot() RegistrySnapshot { snap.SurfaceCounts[s.String()] = r.surfaceCounts[s].Load() } + outcomes := r.outcomes.view() + r.mu.RLock() defer r.mu.RUnlock() @@ -548,6 +565,7 @@ func (r *CounterRegistry) Snapshot() RegistrySnapshot { snap.TPABundleRefreshRejections = r.tpaBundleRefreshRejections snap.TPABundleRefreshUnavailable = r.tpaBundleRefreshUnavailable snap.TPABundleReprotectHits = r.tpaBundleReprotectHits + snap.UpstreamOutcomes = outcomes for k, v := range r.tpaFindings { snap.TPAFindings[k] = v } @@ -577,6 +595,9 @@ func (r *CounterRegistry) Drain() RegistrySnapshot { } upstream := r.upstreamTotal.Swap(0) snap.UpstreamToolCallCountBucket = bucketUpstream(upstream) + // Schema v17: swap the completion window atomically under its own + // mutex; the next window opens now (window_age). + snap.UpstreamOutcomes = r.outcomes.drain(r.now().UTC()) r.mu.Lock() defer r.mu.Unlock() @@ -653,6 +674,12 @@ func (r *CounterRegistry) HasPendingCounters() bool { if r.upstreamTotal.Load() > 0 { return true } + // Schema v17: an outcome alone is unsent usage data (a window can hold + // outcomes with a zero dispatch count only in theory, but the shutdown + // flush must never skip one). + if r.outcomes.pending() { + return true + } r.mu.RLock() defer r.mu.RUnlock() @@ -692,6 +719,7 @@ func (r *CounterRegistry) Reset() { r.surfaceCounts[i].Store(0) } r.upstreamTotal.Store(0) + r.outcomes.reset(r.now().UTC()) r.mu.Lock() defer r.mu.Unlock() diff --git a/internal/telemetry/success_scope.go b/internal/telemetry/success_scope.go new file mode 100644 index 000000000..4ad966c6d --- /dev/null +++ b/internal/telemetry/success_scope.go @@ -0,0 +1,103 @@ +package telemetry + +import ( + "fmt" + + "go.etcd.io/bbolt" +) + +// activationKeySuccessScopeEver holds the lifetime success scope (Spec 126 +// FR-038) in the activation bucket as one ordinal byte: 0 none, 1 +// starter_only, 2 non_starter. +const activationKeySuccessScopeEver = "success_scope_ever" + +// SuccessScope is the lifetime scope of usable upstream results +// (day_two.success_scope_ever). It only moves forward: +// none -> starter_only -> non_starter. +type SuccessScope uint8 + +// The ordinals are persisted; never renumber them. +const ( + SuccessScopeNone SuccessScope = 0 + SuccessScopeStarterOnly SuccessScope = 1 + SuccessScopeNonStarter SuccessScope = 2 +) + +// String returns the wire value. +func (s SuccessScope) String() string { + switch s { + case SuccessScopeNone: + return "none" + case SuccessScopeStarterOnly: + return "starter_only" + case SuccessScopeNonStarter: + return "non_starter" + default: + return "invalid" + } +} + +func decodeSuccessScope(raw []byte) (SuccessScope, error) { + if raw == nil { + return SuccessScopeNone, nil + } + if len(raw) != 1 || SuccessScope(raw[0]) > SuccessScopeNonStarter { + return SuccessScopeNone, fmt.Errorf("activation: invalid %s value", activationKeySuccessScopeEver) + } + return SuccessScope(raw[0]), nil +} + +// LoadSuccessScope reads the lifetime success scope. A missing bucket or key +// is SuccessScopeNone; a stored value outside the ordinal range is an error. +func LoadSuccessScope(db *bbolt.DB) (SuccessScope, error) { + if db == nil { + return SuccessScopeNone, fmt.Errorf("nil db") + } + scope := SuccessScopeNone + err := db.View(func(tx *bbolt.Tx) error { + b := activationBucket(tx) + if b == nil { + return nil + } + var err error + scope, err = decodeSuccessScope(b.Get([]byte(activationKeySuccessScopeEver))) + return err + }) + return scope, err +} + +// RecordSuccessScope advances the lifetime scope for one usable upstream +// result: starter_only for a starter success, non_starter for any other. It +// never moves the scope back. It is local state, recorded whatever the +// telemetry opt-out setting (only sending is gated). A read-only check runs +// first so the common case (scope already reached) costs no write. +func RecordSuccessScope(db *bbolt.DB, starter bool) error { + if db == nil { + return fmt.Errorf("nil db") + } + target := SuccessScopeNonStarter + if starter { + target = SuccessScopeStarterOnly + } + current, err := LoadSuccessScope(db) + if err != nil { + return err + } + if current >= target { + return nil + } + return db.Update(func(tx *bbolt.Tx) error { + b, err := activationBucketForWrite(tx) + if err != nil { + return err + } + cur, err := decodeSuccessScope(b.Get([]byte(activationKeySuccessScopeEver))) + if err != nil { + return err + } + if cur >= target { + return nil + } + return b.Put([]byte(activationKeySuccessScopeEver), []byte{byte(target)}) + }) +} diff --git a/internal/telemetry/success_scope_test.go b/internal/telemetry/success_scope_test.go new file mode 100644 index 000000000..c2dd86185 --- /dev/null +++ b/internal/telemetry/success_scope_test.go @@ -0,0 +1,121 @@ +package telemetry + +import ( + "path/filepath" + "testing" + "time" + + "go.etcd.io/bbolt" +) + +// Spec 126 FR-038 (T080): success_scope_ever moves forward only, in the order +// none -> starter_only -> non_starter, and is persisted. + +func TestSuccessScope_WireValues(t *testing.T) { + for scope, want := range map[SuccessScope]string{ + SuccessScopeNone: "none", + SuccessScopeStarterOnly: "starter_only", + SuccessScopeNonStarter: "non_starter", + } { + if got := scope.String(); got != want { + t.Errorf("%d.String() = %q, want %q", scope, got, want) + } + } +} + +func TestSuccessScope_MovesForwardOnly(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + + mustScope := func(want SuccessScope) { + t.Helper() + got, err := LoadSuccessScope(db) + if err != nil { + t.Fatalf("LoadSuccessScope: %v", err) + } + if got != want { + t.Fatalf("scope = %s, want %s", got, want) + } + } + + mustScope(SuccessScopeNone) + if err := RecordSuccessScope(db, true); err != nil { + t.Fatal(err) + } + mustScope(SuccessScopeStarterOnly) + if err := RecordSuccessScope(db, true); err != nil { + t.Fatal(err) + } + mustScope(SuccessScopeStarterOnly) + if err := RecordSuccessScope(db, false); err != nil { + t.Fatal(err) + } + mustScope(SuccessScopeNonStarter) + // Nothing moves it back. + if err := RecordSuccessScope(db, true); err != nil { + t.Fatal(err) + } + mustScope(SuccessScopeNonStarter) +} + +// A non-starter success on a fresh store goes straight to non_starter. +func TestSuccessScope_NonStarterFirst(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + if err := RecordSuccessScope(db, false); err != nil { + t.Fatal(err) + } + if err := RecordSuccessScope(db, true); err != nil { + t.Fatal(err) + } + got, err := LoadSuccessScope(db) + if err != nil || got != SuccessScopeNonStarter { + t.Fatalf("scope = %s, %v; want non_starter", got, err) + } +} + +// The value is persisted and survives a reopen of the store. +func TestSuccessScope_SurvivesReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "scope.db") + db, err := bbolt.Open(path, 0o600, &bbolt.Options{Timeout: 2 * time.Second}) + if err != nil { + t.Fatal(err) + } + if err := RecordSuccessScope(db, true); err != nil { + t.Fatal(err) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + db, err = bbolt.Open(path, 0o600, &bbolt.Options{Timeout: 2 * time.Second}) + if err != nil { + t.Fatal(err) + } + defer db.Close() + got, err := LoadSuccessScope(db) + if err != nil || got != SuccessScopeStarterOnly { + t.Fatalf("after reopen: scope = %s, %v; want starter_only", got, err) + } +} + +// A stored value outside the ordinal range is an error, never a guess, and a +// later success does not overwrite it. +func TestSuccessScope_CorruptValueIsAnError(t *testing.T) { + db, cleanup := newTestActivationDB(t) + defer cleanup() + if err := db.Update(func(tx *bbolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte(ActivationBucketName)) + if err != nil { + return err + } + return b.Put([]byte(activationKeySuccessScopeEver), []byte{7}) + }); err != nil { + t.Fatal(err) + } + if _, err := LoadSuccessScope(db); err == nil { + t.Fatal("a corrupt scope must be reported") + } + if err := RecordSuccessScope(db, false); err == nil { + t.Fatal("recording over a corrupt scope must fail rather than overwrite it") + } +} diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go index 63636d653..96b391883 100644 --- a/internal/telemetry/telemetry.go +++ b/internal/telemetry/telemetry.go @@ -191,7 +191,31 @@ import ( // bundle_version "other" and no sequence). Like every counter they ride the // telemetry opt-out. tpa_scanner is emitted when only these counters are // non-zero. The age-of-bundle join of SC-006 is a receiver-side computation. -const SchemaVersion = 16 +// +// v17 (Spec 126 PR-A, instrumentation only) keeps DISPATCH and COMPLETION +// apart. upstream_tool_call_count_bucket keeps its v14 meaning (requests handed +// to the transport; a session-recovery repeat counts twice). The new +// upstream_outcomes object counts LOGICAL calls that dispatched at least one +// request: succeeded (a usable result: no error, no isError:true, not withheld +// by an output policy — the first_real_tool_call_ever predicate), unusable +// (dispatched, no usable result) and succeeded_non_starter (succeeded minus +// the starter server; every success until the starter ships), each a +// bucketUpstream label, plus coverage ("partial" for the first window of a +// process whose predecessor left recorded outcomes undelivered, per a +// persisted marker, and once on the first schema-17 start over an existing +// config.db; "full" otherwise, a plain restart after a delivered window +// included) and window_age (the install age when the window opened, fresh +// personal installs only). It is a reset-on-accept counter window like the +// others, frozen with heartbeat_id until a 2xx, and sent by both editions. The +// personal edition also sends day_two: install_origin ("fresh" when config.db +// holds the install anchor, written once when the store was empty at first +// open; "existing" otherwise), install_age (d0_6|d7_13|d14_plus, UTC calendar +// dates since the anchor, only when fresh) and success_scope_ever +// (none|starter_only|non_starter, persisted, forward-only). day_two is state, +// not part of the counter window. Closed enums only; no timestamp, name or +// identifier is added. A field counts only on heartbeats whose schema_version +// introduced it: absence before v17 means "not measured", never zero. +const SchemaVersion = 17 // HeartbeatPayload is the anonymous telemetry payload sent periodically. // Spec 042 expanded the payload with Tier 2 fields; v1 fields are preserved. @@ -432,6 +456,20 @@ type HeartbeatPayload struct { // email, group or IdP subject. The wire key deliberately avoids the // substring "user" (see the SchemaVersion comment). UserCountBucket string `json:"member_count_bucket,omitempty"` + + // Schema v17 (Spec 126 FR-035, FR-036): the per-window COMPLETION counts, + // next to the dispatch count above (upstream_tool_call_count_bucket). + // Dispatch counts requests handed to the transport; these count logical + // calls that dispatched at least one request, by outcome. Reset-on-accept, + // part of the drained counter window keyed by heartbeat_id, so a retry of + // an undelivered window re-sends it byte-identical. Both editions. + UpstreamOutcomes *UpstreamOutcomes `json:"upstream_outcomes,omitempty"` + + // Schema v17 (Spec 126 FR-034, FR-038): install origin, install age bucket + // and lifetime success scope. STATE, read fresh at every build and never + // part of the counter window. Personal edition only; nil (omitted) on the + // server edition and when the install-anchor provider is not wired. + DayTwo *DayTwoPayload `json:"day_two,omitempty"` } // OnboardingSnapshot is the data the telemetry service needs to populate @@ -554,6 +592,17 @@ type Service struct { // onboarding fields are simply omitted from the heartbeat. onboardingProvider func() *OnboardingSnapshot + // installAnchorProvider (Spec 126 FR-033/FR-034) reads the install anchor; + // installAnchorOnce caches its ONE answer per process (see + // installAnchor in day_two.go). + installAnchorMu sync.Mutex + installAnchorRead bool + installAnchorValue time.Time + installAnchorExists bool + installAnchorErr error + // from config.db; nil until the runtime wires it. See day_two.go. + installAnchorProvider func() (time.Time, bool, error) + // Spec 101 FR-021: optional provider for the active TPA bundle's // provenance tuple (source, signature_verified, schema line, sequence). // nil-safe: when unset, or when it returns nil, no bundle keys are sent. @@ -1264,6 +1313,9 @@ func (s *Service) sendHeartbeatWithOneShots(ctx context.Context, consumeOneShots if resp.StatusCode/100 == 2 { s.pendingCounterSnapshot = nil s.rotateHeartbeatWindowID() + // Spec 126 FR-036: clear the undelivered-window marker unless an + // outcome was recorded after the accepted snapshot was drained. + s.onCounterWindowAccepted() s.advanceUpgradeFunnel() } } @@ -1602,6 +1654,11 @@ func (s *Service) buildHeartbeatWithOneShots(consumeOneShots bool) HeartbeatPayl } } + // Schema v17 (Spec 126 FR-034, FR-038): day_two, personal edition only. + // State, not a counter: built fresh here and never part of the drained + // counter window. + payload.DayTwo = s.buildDayTwo(time.Now().UTC()) + // Spec 044 (T051): LaunchSource. One-shot "installer" override consumes // the installer_heartbeat_pending flag set at process startup when // MCPPROXY_LAUNCHED_BY=installer was observed. Otherwise the runtime @@ -1720,6 +1777,10 @@ func applyRegistrySnapshot(payload *HeartbeatPayload, snap RegistrySnapshot) { // Schema v8: security-scanner counters. nil (and therefore omitted) when // the install never completed or failed a scan in the window. payload.TPAScanner = snap.TPAScannerStats() + // Schema v17: the completion window rides the same frozen snapshot, so a + // retry of an undelivered heartbeat_id re-sends it byte-identical. + outcomes := snap.UpstreamOutcomes + payload.UpstreamOutcomes = &outcomes // Bundle state is per-heartbeat state, not a reset-on-accept counter: the // counter view above just replaced TPAScanner, so merge it back in. applyTPABundle(payload) diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.go index af08a607b..d9834d989 100644 --- a/internal/telemetry/telemetry_test.go +++ b/internal/telemetry/telemetry_test.go @@ -312,16 +312,16 @@ func TestEnsureAnonymousID(t *testing.T) { // once the Spec 080 funnel/churn fields ship. This is a tripwire against // accidental downgrades. func TestSchemaVersionV7(t *testing.T) { - if SchemaVersion != 16 { - t.Fatalf("SchemaVersion = %d, want 16", SchemaVersion) + if SchemaVersion != 17 { + t.Fatalf("SchemaVersion = %d, want 17", SchemaVersion) } cfg := &config.Config{} svc := New(cfg, "", "v1.0.0", "personal", zap.NewNop()) svc.SetRuntimeStats(&mockRuntimeStats{}) payload := svc.BuildPayload() - if payload.SchemaVersion != 16 { - t.Errorf("payload.SchemaVersion = %d, want 16", payload.SchemaVersion) + if payload.SchemaVersion != 17 { + t.Errorf("payload.SchemaVersion = %d, want 17", payload.SchemaVersion) } } diff --git a/internal/telemetry/tpa_bundle_refresh_test.go b/internal/telemetry/tpa_bundle_refresh_test.go index 08c6a2e63..3b9600b7b 100644 --- a/internal/telemetry/tpa_bundle_refresh_test.go +++ b/internal/telemetry/tpa_bundle_refresh_test.go @@ -16,11 +16,11 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" ) -// TestSchemaVersionIs16 pins the Spec 087 / Spec 101 US3 bump: the five refresh -// counters ride schema 16. -func TestSchemaVersionIs16(t *testing.T) { - if SchemaVersion != 16 { - t.Fatalf("SchemaVersion = %d, want 16 (v16 TPA bundle refresh counters)", SchemaVersion) +// TestSchemaVersionIs17 pins the current schema (Spec 126 PR-A). The five refresh +// counters of the Spec 087 / Spec 101 US3 bump rode schema 16 first. +func TestSchemaVersionIs17(t *testing.T) { + if SchemaVersion != 17 { + t.Fatalf("SchemaVersion = %d, want 17 (v17 completion counters; the v16 TPA refresh counters ride every later version)", SchemaVersion) } } @@ -170,7 +170,7 @@ func TestTPABundleRefreshCounters_AloneEmitTPAScanner(t *testing.T) { } js := string(data) for _, want := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"tpa_scanner":{`, `"bundle_refresh_cycles":4`, `"bundle_refresh_activations":1`, diff --git a/internal/telemetry/tpa_bundle_test.go b/internal/telemetry/tpa_bundle_test.go index 1a44217e2..d5c345771 100644 --- a/internal/telemetry/tpa_bundle_test.go +++ b/internal/telemetry/tpa_bundle_test.go @@ -17,7 +17,7 @@ import ( // bundleObj wraps the given tpa_scanner members into a minimal payload. func bundleObj(members string) []byte { - return []byte(`{"anonymous_id":"abc","schema_version":16,"tpa_scanner":{` + members + `}}`) + return []byte(`{"anonymous_id":"abc","schema_version":17,"tpa_scanner":{` + members + `}}`) } func u64(v uint64) *uint64 { return &v } @@ -154,7 +154,7 @@ func TestTPABundleProvider_ZeroCountersStillCarriesObject(t *testing.T) { } js := string(data) for _, want := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"tpa_scanner":{`, `"scans_completed":0`, `"bundle_source":"embedded"`, diff --git a/internal/telemetry/tpa_funnel_v9_test.go b/internal/telemetry/tpa_funnel_v9_test.go index 37bca2d39..94172df7f 100644 --- a/internal/telemetry/tpa_funnel_v9_test.go +++ b/internal/telemetry/tpa_funnel_v9_test.go @@ -260,7 +260,7 @@ func TestPayloadV9_TrustModeDistributionAndFunnelCounters(t *testing.T) { } js := string(data) for _, required := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"trust_mode_distribution":`, `"tool_change_gate_scans":2`, `"prompt_scans":1`, diff --git a/internal/telemetry/tpa_scanner_test.go b/internal/telemetry/tpa_scanner_test.go index 2f82b71dd..fc27f5518 100644 --- a/internal/telemetry/tpa_scanner_test.go +++ b/internal/telemetry/tpa_scanner_test.go @@ -264,7 +264,7 @@ func TestPayloadV8_TPAScannerIncludedAndAnonymous(t *testing.T) { js := string(data) for _, required := range []string{ - `"schema_version":16`, + `"schema_version":17`, `"tpa_scanner":`, `"scans_completed":2`, `"scans_failed":1`, diff --git a/internal/telemetry/upstream_outcomes.go b/internal/telemetry/upstream_outcomes.go new file mode 100644 index 000000000..1102f0498 --- /dev/null +++ b/internal/telemetry/upstream_outcomes.go @@ -0,0 +1,241 @@ +package telemetry + +import ( + "sync" + "time" +) + +// Schema v17 (Spec 126 FR-035, FR-036): per-window COMPLETION counters. +// +// upstream_tool_call_count_bucket (schema 14) counts DISPATCHES: requests the +// core client handed to the transport, so a session-recovery repeat counts +// twice. upstream_outcomes counts LOGICAL calls that dispatched at least one +// request, by outcome: +// +// - succeeded: a usable result (no error, no isError:true, not withheld by an +// output policy) — the predicate of activation.first_real_tool_call_ever; +// - unusable: dispatched, but ended without a usable result; +// - succeeded_non_starter: the subset of succeeded that is not on the +// starter server (FR-037). +// +// A call refused before dispatch records no outcome. The counts share the +// registry's reset-on-accept window: Drain detaches them together with every +// other counter, so the window keyed by heartbeat_id is frozen until a 2xx and +// a retry re-sends it byte-identical (the receiver answers 409 otherwise). + +// UpstreamOutcomes is the wire form of the completion window. Every count is a +// bucketUpstream label; Coverage is OutcomeCoverageFull or +// OutcomeCoveragePartial; WindowAge is the install age (an InstallAge* value) +// when the window OPENED, present only when install_origin is "fresh" (never +// on the server edition). Every field is frozen into the drained snapshot. +type UpstreamOutcomes struct { + Succeeded string `json:"succeeded"` + Unusable string `json:"unusable"` + SucceededNonStarter string `json:"succeeded_non_starter"` + Coverage string `json:"coverage"` + WindowAge string `json:"window_age,omitempty"` +} + +// Coverage values of upstream_outcomes (FR-036). +const ( + // OutcomeCoverageFull: the counts cover the whole time since the previous + // accepted send (or, on a fresh install, since the store was created). + OutcomeCoverageFull = "full" + // OutcomeCoveragePartial: the first window of a process whose predecessor + // left recorded outcomes undelivered (the persisted marker was still set), + // or the first schema-17 start of an install whose origin is "existing", + // where no marker exists yet. Those unsent counts are lost. + OutcomeCoveragePartial = "partial" +) + +// outcomeWindow is the live completion window and the undelivered-window +// marker it drives (FR-036). One small mutex guards the outcome increment, +// the "outcome since the last drain" state (counts > 0), Drain's swap and +// reset of the counts, and both marker writes, so: +// +// - the marker is set (true) in the same critical section as, and before, +// the first outcome after process start or after a Drain; +// - the post-2xx clear (false) is written only when no outcome was counted +// since the Drain whose snapshot was accepted, decided and written in one +// critical section. +// +// No interleaving can therefore leave the marker false while an undelivered +// outcome exists. The mutex is NEVER held across network I/O: Drain runs at +// the start of a send and the clear after its 2xx, each taking the mutex only +// for the swap or the write. A marker write is a local bbolt commit, once per +// window, and is the only disk I/O under it. The accept decision itself is +// made under the service's deliveryMu; only the post-2xx clear takes this +// mutex, and nothing on the tool-call path ever waits on deliveryMu. +type outcomeWindow struct { + mu sync.Mutex + succeeded int64 + unusable int64 + succeededNonStarter int64 + // partial marks the CURRENT window's coverage (cleared by a Drain). + partial bool + // openedAt is when the current window opened: registry creation + // (process start) or the last Drain. ageFn maps it to window_age; nil + // omits window_age. + openedAt time.Time + ageFn func(opened time.Time) string + // markerWrite persists the undelivered-window marker; nil until the + // telemetry service installs it (InitOutcomeWindow). + markerWrite func(set bool) +} + +func (w *outcomeWindow) pendingLocked() bool { + return w.succeeded > 0 || w.unusable > 0 || w.succeededNonStarter > 0 +} + +func (w *outcomeWindow) pending() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.pendingLocked() +} + +func (w *outcomeWindow) viewLocked() UpstreamOutcomes { + coverage := OutcomeCoverageFull + if w.partial { + coverage = OutcomeCoveragePartial + } + windowAge := "" + if w.ageFn != nil { + windowAge = w.ageFn(w.openedAt) + } + return UpstreamOutcomes{ + Succeeded: bucketUpstream(w.succeeded), + Unusable: bucketUpstream(w.unusable), + SucceededNonStarter: bucketUpstream(w.succeededNonStarter), + Coverage: coverage, + WindowAge: windowAge, + } +} + +func (w *outcomeWindow) view() UpstreamOutcomes { + w.mu.Lock() + defer w.mu.Unlock() + return w.viewLocked() +} + +// drain detaches the window (frozen, coverage and window_age included) and +// opens the next one at now. +func (w *outcomeWindow) drain(now time.Time) UpstreamOutcomes { + w.mu.Lock() + defer w.mu.Unlock() + out := w.viewLocked() + w.succeeded, w.unusable, w.succeededNonStarter = 0, 0, 0 + w.partial = false + w.openedAt = now + return out +} + +// reset zeroes the window like drain, discarding it. +func (w *outcomeWindow) reset(now time.Time) { + _ = w.drain(now) +} + +// RecordUpstreamOutcome counts one logical upstream call that dispatched at +// least one request. succeeded is true for a usable result; starter is true +// when the starter classifier marks the call's server as the starter. The +// server name never reaches the registry. The first outcome of a window (the +// first since process start or the last Drain) sets the undelivered-window +// marker in the same critical section. +func (r *CounterRegistry) RecordUpstreamOutcome(succeeded, starter bool) { + w := &r.outcomes + w.mu.Lock() + defer w.mu.Unlock() + // The marker is set BEFORE the increment, inside the same critical + // section, so there is never an undelivered outcome with the marker + // still false. + if !w.pendingLocked() && w.markerWrite != nil { + w.markerWrite(true) + } + if succeeded { + w.succeeded++ + if !starter { + w.succeededNonStarter++ + } + } else { + w.unusable++ + } +} + +// RecordUpstreamOutcomeOn calls reg.RecordUpstreamOutcome if reg is non-nil. +func RecordUpstreamOutcomeOn(reg *CounterRegistry, succeeded, starter bool) { + if reg == nil { + return + } + reg.RecordUpstreamOutcome(succeeded, starter) +} + +// MarkOutcomeWindowPartial marks the CURRENT window's upstream_outcomes as +// partial. Service.InitOutcomeWindow calls it once at startup when the +// predecessor left an undelivered window. The flag travels with the window: +// Drain moves it into the detached snapshot (kept unchanged across retries) +// and the next window starts full. +func (r *CounterRegistry) MarkOutcomeWindowPartial() { + r.outcomes.mu.Lock() + r.outcomes.partial = true + r.outcomes.mu.Unlock() +} + +// SetOutcomeWindowAgeFunc installs the window_age mapping: the install age +// bucket of the time a window opened (registry creation, i.e. process start, +// or the last Drain). fn must be pure and cheap (it runs under the window +// mutex); nil omits window_age. Drain freezes the value into the detached +// snapshot, so a retry carries the age its window opened at. +func (r *CounterRegistry) SetOutcomeWindowAgeFunc(fn func(opened time.Time) string) { + r.outcomes.mu.Lock() + r.outcomes.ageFn = fn + r.outcomes.mu.Unlock() +} + +// SetOutcomeMarkerWriter installs the persistence of the undelivered-window +// marker. When the live window already holds outcomes (recorded before the +// writer existed) the marker is set at once. +func (r *CounterRegistry) SetOutcomeMarkerWriter(write func(set bool)) { + w := &r.outcomes + w.mu.Lock() + defer w.mu.Unlock() + w.markerWrite = write + if write != nil && w.pendingLocked() { + write(true) + } +} + +// ClearOutcomeMarkerIfIdle runs after an accepted send (the shutdown flush +// included): it clears the marker unless an outcome was counted since the +// Drain whose snapshot was just accepted. Those outcomes are still +// undelivered, and the marker their first outcome set must stay set. +func (r *CounterRegistry) ClearOutcomeMarkerIfIdle() { + if r == nil { + return + } + w := &r.outcomes + w.mu.Lock() + defer w.mu.Unlock() + if w.markerWrite != nil && !w.pendingLocked() { + w.markerWrite(false) + } +} + +// HasPendingUpstreamOutcomes reports whether the current (undrained) window +// holds any outcome. +func (r *CounterRegistry) HasPendingUpstreamOutcomes() bool { + if r == nil { + return false + } + return r.outcomes.pending() +} + +// UpstreamOutcomeTotals returns the raw counts of the current (undrained) +// window. Never transmitted (the wire carries buckets only); for tests and +// internal observability, like AnonymityViolationsTotal. +func (r *CounterRegistry) UpstreamOutcomeTotals() (succeeded, unusable, succeededNonStarter int64) { + if r == nil { + return 0, 0, 0 + } + r.outcomes.mu.Lock() + defer r.outcomes.mu.Unlock() + return r.outcomes.succeeded, r.outcomes.unusable, r.outcomes.succeededNonStarter +} diff --git a/internal/telemetry/upstream_outcomes_test.go b/internal/telemetry/upstream_outcomes_test.go new file mode 100644 index 000000000..03a4bb4e6 --- /dev/null +++ b/internal/telemetry/upstream_outcomes_test.go @@ -0,0 +1,240 @@ +package telemetry + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +// Spec 126 FR-035 / FR-036 (T079): the per-window completion counters. + +// The three counts are bucketed exactly like upstream_tool_call_count_bucket. +func TestUpstreamOutcomes_BucketsMatchDispatchBucket(t *testing.T) { + for _, n := range []int{0, 1, 10, 11, 100, 101, 1000, 1001} { + r := NewCounterRegistry() + for i := 0; i < n; i++ { + r.RecordUpstreamOutcome(true, false) + r.RecordUpstreamOutcome(false, false) + } + got := r.Snapshot().UpstreamOutcomes + want := bucketUpstream(int64(n)) + if got.Succeeded != want || got.Unusable != want || got.SucceededNonStarter != want { + t.Fatalf("n=%d: got %+v, want every count %q", n, got, want) + } + if got.Coverage != OutcomeCoverageFull { + t.Fatalf("n=%d: coverage = %q, want full", n, got.Coverage) + } + } +} + +// A success on the starter counts in succeeded but not succeeded_non_starter; +// an unusable result never counts as a success, starter or not. +func TestUpstreamOutcomes_StarterSuccessExcludedFromNonStarter(t *testing.T) { + r := NewCounterRegistry() + r.RecordUpstreamOutcome(true, true) + r.RecordUpstreamOutcome(true, true) + r.RecordUpstreamOutcome(false, true) + got := r.Snapshot().UpstreamOutcomes + if got.Succeeded != "1-10" || got.SucceededNonStarter != "0" || got.Unusable != "1-10" { + t.Fatalf("starter-only window: got %+v", got) + } + + r.RecordUpstreamOutcome(true, false) + if got := r.Snapshot().UpstreamOutcomes; got.SucceededNonStarter != "1-10" { + t.Fatalf("a non-starter success must count: got %+v", got) + } +} + +// RecordUpstreamOutcomeOn is nil-safe. +func TestUpstreamOutcomes_NilRegistry(t *testing.T) { + RecordUpstreamOutcomeOn(nil, true, false) + var r *CounterRegistry + if r.HasPendingCounters() { + t.Fatal("nil registry has no pending counters") + } +} + +// An outcome alone is pending usage data for the shutdown flush. +func TestUpstreamOutcomes_ArePendingCounters(t *testing.T) { + r := NewCounterRegistry() + if r.HasPendingCounters() { + t.Fatal("fresh registry has nothing pending") + } + r.RecordUpstreamOutcome(false, false) + if !r.HasPendingCounters() { + t.Fatal("an unusable outcome is pending until an accepted send") + } + r.Reset() + if r.HasPendingCounters() { + t.Fatal("Reset zeroes the outcome counts") + } +} + +// Coverage is "full" for a fresh registry (a fresh install's first window), +// "partial" for the first window of a process over an existing store, and +// "full" again from the window after the first accepted send. Drain carries +// the flag into the detached window, so the next window starts full. +func TestUpstreamOutcomes_CoverageFlag(t *testing.T) { + fresh := NewCounterRegistry() + if got := fresh.Drain().UpstreamOutcomes.Coverage; got != OutcomeCoverageFull { + t.Fatalf("fresh install first window: coverage = %q, want full", got) + } + + existing := NewCounterRegistry() + existing.MarkOutcomeWindowPartial() + if got := existing.Snapshot().UpstreamOutcomes.Coverage; got != OutcomeCoveragePartial { + t.Fatalf("snapshot of the first window over an existing store: coverage = %q, want partial", got) + } + first := existing.Drain() + if first.UpstreamOutcomes.Coverage != OutcomeCoveragePartial { + t.Fatalf("first window over an existing store: coverage = %q, want partial", first.UpstreamOutcomes.Coverage) + } + if got := existing.Drain().UpstreamOutcomes.Coverage; got != OutcomeCoverageFull { + t.Fatalf("the window after the first: coverage = %q, want full", got) + } +} + +type capturedHeartbeat struct { + raw map[string]json.RawMessage + payload HeartbeatPayload +} + +func newOutcomeCaptureServer(t *testing.T) (*httptest.Server, func() []capturedHeartbeat, func(int)) { + t.Helper() + var ( + mu sync.Mutex + got []capturedHeartbeat + status = http.StatusInternalServerError + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var c capturedHeartbeat + if err := json.Unmarshal(body, &c.raw); err != nil { + http.Error(w, "bad", http.StatusBadRequest) + return + } + _ = json.Unmarshal(body, &c.payload) + mu.Lock() + got = append(got, c) + st := status + mu.Unlock() + w.WriteHeader(st) + })) + t.Cleanup(srv.Close) + return srv, func() []capturedHeartbeat { + mu.Lock() + defer mu.Unlock() + return append([]capturedHeartbeat(nil), got...) + }, func(s int) { + mu.Lock() + status = s + mu.Unlock() + } +} + +func newOutcomeService(t *testing.T, endpoint, edition string) *Service { + t.Helper() + t.Setenv("CI", "") + t.Setenv("DO_NOT_TRACK", "") + t.Setenv("MCPPROXY_TELEMETRY", "") + svc := New(&config.Config{ + Telemetry: &config.TelemetryConfig{ + AnonymousID: "550e8400-e29b-41d4-a716-446655440000", + Endpoint: endpoint, + }, + RoutingMode: "retrieve_tools", + }, "", "v1.0.0", edition, zap.NewNop()) + svc.SetRuntimeStats(&mockRuntimeStats{}) + return svc +} + +// The counts drain only on an accepted send: a rejected send keeps the +// window, and its retry re-sends byte-identical upstream_outcomes (coverage +// included) under the same heartbeat_id, even when calls happened in between. +// Those calls go to the next window. The receiver stores one immutable +// heartbeat_events row per heartbeat_id and answers 409 to a retry whose +// counter payload differs, so this is a wire contract. +func TestUpstreamOutcomes_DrainOnlyOnAcceptedSend_RetryIsByteIdentical(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + svc := newOutcomeService(t, srv.URL, "personal") + reg := svc.Registry() + reg.MarkOutcomeWindowPartial() // first window of a process over an existing store + + for i := 0; i < 3; i++ { + reg.RecordUpstreamOutcome(true, false) + } + reg.RecordUpstreamOutcome(false, false) + + svc.sendHeartbeat(context.Background()) // 500: the window stays pending + + // Calls between the rejected send and its retry belong to the next window. + for i := 0; i < 20; i++ { + reg.RecordUpstreamOutcome(false, false) + } + reg.RecordUpstreamOutcome(true, true) + + setStatus(http.StatusNoContent) + svc.sendHeartbeat(context.Background()) // 204: the retry is accepted + svc.sendHeartbeat(context.Background()) // the next window + + got := received() + if len(got) != 3 { + t.Fatalf("received %d heartbeats, want 3", len(got)) + } + first, retry, next := got[0], got[1], got[2] + if first.payload.HeartbeatID != retry.payload.HeartbeatID { + t.Fatalf("retry changed heartbeat_id") + } + if !bytes.Equal(first.raw["upstream_outcomes"], retry.raw["upstream_outcomes"]) { + t.Fatalf("retry upstream_outcomes differ:\nfirst %s\nretry %s", first.raw["upstream_outcomes"], retry.raw["upstream_outcomes"]) + } + want := UpstreamOutcomes{Succeeded: "1-10", Unusable: "1-10", SucceededNonStarter: "1-10", Coverage: OutcomeCoveragePartial} + if first.payload.UpstreamOutcomes == nil || *first.payload.UpstreamOutcomes != want { + t.Fatalf("first window = %+v, want %+v", first.payload.UpstreamOutcomes, want) + } + wantNext := UpstreamOutcomes{Succeeded: "1-10", Unusable: "11-100", SucceededNonStarter: "0", Coverage: OutcomeCoverageFull} + if next.payload.UpstreamOutcomes == nil || *next.payload.UpstreamOutcomes != wantNext { + t.Fatalf("next window = %+v, want %+v (the in-between calls, full coverage after the accepted send)", next.payload.UpstreamOutcomes, wantNext) + } + if next.payload.HeartbeatID == retry.payload.HeartbeatID { + t.Fatal("accepted window did not rotate heartbeat_id") + } +} + +// Both editions send upstream_outcomes, and an idle window still carries it +// (all counts "0"), so absence always means "not measured". +func TestUpstreamOutcomes_SentByBothEditions(t *testing.T) { + for _, edition := range []string{"personal", "server"} { + t.Run(edition, func(t *testing.T) { + srv, received, setStatus := newOutcomeCaptureServer(t) + setStatus(http.StatusNoContent) + svc := newOutcomeService(t, srv.URL, edition) + svc.sendHeartbeat(context.Background()) + got := received() + if len(got) != 1 { + t.Fatalf("received %d heartbeats, want 1", len(got)) + } + raw, ok := got[0].raw["upstream_outcomes"] + if !ok { + t.Fatalf("%s edition heartbeat has no upstream_outcomes", edition) + } + var o UpstreamOutcomes + if err := json.Unmarshal(raw, &o); err != nil { + t.Fatal(err) + } + want := UpstreamOutcomes{Succeeded: "0", Unusable: "0", SucceededNonStarter: "0", Coverage: OutcomeCoverageFull} + if o != want { + t.Fatalf("idle window = %+v, want %+v", o, want) + } + }) + } +}