diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index 674e5877a8..e7a308eb15 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -347,7 +347,11 @@ describe("DesktopPreReadyPlatform", () => { }); assert.deepEqual(events, ["pre-ready", "clerk"]); assert.equal(registerSchemesMock.mock.calls.length, 1); - assert.equal(appendSwitchMock.mock.calls.length, 0); + // SCIENT-FORK:START — outside Linux, the only switch turns off soft-navigation detection. + assert.deepEqual(appendSwitchMock.mock.calls, [ + ["disable-features", "SoftNavigationDetection"], + ]); + // SCIENT-FORK:END assert.equal(setDesktopNameMock.mock.calls.length, 0); }), ); diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index 4dd897528c..84549fd48c 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -23,6 +23,9 @@ import { enableAutomaticSpellingLanguages } from "../scient/spelling/macSpelling // SCIENT-FORK:START — development builds can trust a local test site's certificate. import { developmentTrustedCertificates } from "../scient/browser/developmentCertificates.ts"; // SCIENT-FORK:END +// SCIENT-FORK:START — soft-navigation detection can crash a renderer. +import { disableFeaturesWithSoftNavigation } from "../scient/chromium/softNavigation.ts"; +// SCIENT-FORK:END export interface DesktopPreReadyCommandLineReader { readonly hasSwitch: (switchName: string) => boolean; @@ -203,6 +206,15 @@ export const make = Effect.gen(function* () { } } + // SCIENT-FORK:START — soft-navigation detection can crash a renderer, on every platform. + // Runs after the Linux merge: Chromium keeps only the last --disable-features value. + const disableFeatures = disableFeaturesWithSoftNavigation( + readCommandLineSwitchValue(Electron.app.commandLine, "disable-features"), + ); + if (disableFeatures !== null) + Electron.app.commandLine.appendSwitch("disable-features", disableFeatures); + // SCIENT-FORK:END + return { linux, linuxPasswordStoreCommandLine }; }); }).pipe(Effect.withSpan("desktop.electron.configureBeforeReady")); diff --git a/apps/desktop/src/scient/chromium/softNavigation.test.ts b/apps/desktop/src/scient/chromium/softNavigation.test.ts new file mode 100644 index 0000000000..2abd8b3693 --- /dev/null +++ b/apps/desktop/src/scient/chromium/softNavigation.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { disableFeaturesWithSoftNavigation } from "./softNavigation.ts"; + +describe("disableFeaturesWithSoftNavigation", () => { + it("adds the feature and keeps features already disabled", () => { + expect(disableFeaturesWithSoftNavigation(null)).toBe("SoftNavigationDetection"); + expect(disableFeaturesWithSoftNavigation("WaylandWpColorManagerV1")).toBe( + "WaylandWpColorManagerV1,SoftNavigationDetection", + ); + expect(disableFeaturesWithSoftNavigation("A,SoftNavigationDetection")).toBeNull(); + }); +}); diff --git a/apps/desktop/src/scient/chromium/softNavigation.ts b/apps/desktop/src/scient/chromium/softNavigation.ts new file mode 100644 index 0000000000..7c140fb3f3 --- /dev/null +++ b/apps/desktop/src/scient/chromium/softNavigation.ts @@ -0,0 +1,20 @@ +/** + * Chromium 152 stops a renderer when a route-changing input event predates the page's load + * (`CHECK_GT` in `SoftNavigationHeuristics`); macOS passes posted events' timestamps through + * unchecked. Scient reads no soft-navigation timing, so detection is off. + */ +const SOFT_NAVIGATION_FEATURE = "SoftNavigationDetection"; + +/** + * The `--disable-features` value that also turns off soft-navigation detection, keeping the + * features already listed (Chromium keeps only the last value of the switch), or null when it is + * already listed. + */ +export function disableFeaturesWithSoftNavigation(current: string | null): string | null { + const names = (current ?? "") + .split(",") + .map((name) => name.trim()) + .filter((name) => name.length > 0); + if (names.some((name) => name.split("<")[0] === SOFT_NAVIGATION_FEATURE)) return null; + return [...names, SOFT_NAVIGATION_FEATURE].join(","); +} diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 8b257baf2c..66c42f3a3b 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -761,6 +761,8 @@ describe("DesktopWindow", () => { type: "scientAppHealth", component: "renderer", failureClass: "resource-exhaustion", + exitReason: "oom", + exitCode: 137, }, ]); }).pipe(Effect.provide(layer)); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index b796b2f590..8dd87fa373 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -1038,6 +1038,9 @@ export const make = Effect.gen(function* () { type: "scientAppHealth", component: "renderer", failureClass: details.reason === "oom" ? "resource-exhaustion" : "process-crash", + // `recoverable` admitted only these reasons. + exitReason: details.reason as "crashed" | "oom" | "killed" | "abnormal-exit", + exitCode: details.exitCode, }) .pipe(Effect.ignoreCause()), ); diff --git a/apps/server/src/orchestration-v2/Adapters/NativeSessionAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/NativeSessionAdapterV2.ts index 6c53f5fc5e..6d8a07861e 100644 --- a/apps/server/src/orchestration-v2/Adapters/NativeSessionAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/NativeSessionAdapterV2.ts @@ -283,6 +283,8 @@ export interface NativeSession { input: ProviderAdapter.ProviderAdapterV2TurnInput, nativeTurnId: string, ) => Effect.Effect; + /** Sent as the prompt of a manual continuation by a protocol that cannot continue without one. */ + readonly continuationPrompt?: string; readonly steer?: ( input: ProviderAdapter.ProviderAdapterV2SteerInput, validateOwner?: () => Effect.Effect, @@ -1962,6 +1964,7 @@ export function makeNativeSessionAdapterV2( // SCIENT-FORK:END const steer = native.steer; const compact = native.compact; + const continuationPrompt = native.continuationPrompt; const startTurn = Effect.fn("NativeSessionAdapterV2.startTurn")( function* ( request: ProviderAdapter.ProviderAdapterV2TurnInput, @@ -2210,6 +2213,17 @@ export function makeNativeSessionAdapterV2( ), ), startTurn: (request) => startTurn(request, native.send), + ...(continuationPrompt === undefined + ? {} + : { + resumeTurn: (request: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => { + const turn = ProviderAdapter.resumeTurnInput(request); + return startTurn( + { ...turn, message: { ...turn.message, text: continuationPrompt } }, + native.send, + ); + }, + }), ...(compact === undefined ? {} : { diff --git a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts index cb3ae08778..ecabd676bc 100644 --- a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.test.ts @@ -1063,6 +1063,63 @@ it.layer(TestLayer)("OmpAdapterV2", (it) => { }), ), ); + it.effect("continues a turn that ended early by prompting, since the RPC has no resume", () => + Effect.scoped( + Effect.gen(function* () { + const peer = scriptedOmpRpc({ + models: [{ provider: "test", id: "selected", input: ["text"], contextWindow: null }], + initial: { provider: "test", id: "selected" }, + }); + const h = yield* harness(false, { + makeProcess: peer.makeProcess, + target: scientAgentTarget, + }); + const { message, ...turn } = h.input; + if (h.runtime.resumeTurn === undefined) + return yield* Effect.die("Scient Agent offers no manual continuation"); + yield* h.runtime.resumeTurn({ ...turn, messageId: message.messageId }); + yield* peer.finish(); + const terminal = yield* h.takeUntil((event) => event.type === "turn.terminal"); + assert.deepInclude(terminal, { status: "completed" }); + assert.deepEqual( + peer.state.prompts.map((prompt) => [prompt.frame.type, prompt.frame.message]), + [["prompt", "Continue where you left off."]], + ); + }), + ), + ); + it.effect("asks for the model catalog again once when a turn's discovery times out", () => + Effect.scoped( + Effect.gen(function* () { + const silenced = yield* Deferred.make(); + let silenceNextDiscovery = false; + const discovery = (frame: { readonly type: string }) => { + if (frame.type !== "get_available_models" || !silenceNextDiscovery) return false; + silenceNextDiscovery = false; + return true; + }; + const h = yield* modelHarness({ + silentReply: discovery, + holdReply: (frame) => + frame.type === "get_available_models" && silenceNextDiscovery + ? Deferred.succeed(silenced, undefined).pipe(Effect.asVoid) + : Effect.void, + }); + silenceNextDiscovery = true; + const starting = yield* h.start(1, "vendor/a", "high").pipe(Effect.forkScoped); + yield* Deferred.await(silenced); + yield* TestClock.adjust("30 seconds"); + yield* Fiber.join(starting).pipe(Effect.timeout("2 seconds"), TestClock.withLive); + yield* h.peer.finish(); + const terminal = yield* h.terminal(); + assert.deepInclude(terminal, { status: "completed" }); + assert.equal( + h.peer.state.log.filter((entry) => entry.startsWith("get_available_models")).length, + 2, + ); + }), + ), + ); it.effect.each([ { caseTitle: "carries the usage-limit reset time Scient Agent reports", diff --git a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts index 00a7d815a5..94c4eda20c 100644 --- a/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/OmpAdapterV2.ts @@ -488,6 +488,14 @@ export const makeOmpAdapterV2 = Effect.fn("makeOmpAdapterV2")(function* ( catalogCurrent = true; return available; }); + // A turn that needs the catalog asks again once after a timeout; the late first reply is ignored. + const refreshCatalogForTurn = () => + refreshCatalog().pipe( + Effect.retry({ + times: 1, + while: (cause) => cause._tag === "OmpRpcCommandError" && cause.code === "timeout", + }), + ); const home = expandHomePath( options.homePath?.trim() || @@ -1648,7 +1656,7 @@ export const makeOmpAdapterV2 = Effect.fn("makeOmpAdapterV2")(function* ( model.input !== undefined, ) ) - yield* refreshCatalog().pipe( + yield* refreshCatalogForTurn().pipe( Effect.mapError( () => new NativeSessionOperationError({ @@ -1968,7 +1976,7 @@ export const makeOmpAdapterV2 = Effect.fn("makeOmpAdapterV2")(function* ( breaksSession: false, }); if (level !== undefined) { - const available = yield* refreshCatalog(); + const available = yield* refreshCatalogForTurn(); const selectedModel = available.models.find( (candidate) => candidate.provider === model.provider && candidate.id === model.modelId, @@ -2246,6 +2254,8 @@ export const makeOmpAdapterV2 = Effect.fn("makeOmpAdapterV2")(function* ( // SCIENT-FORK: a spoken conversation through Scient Agent's ChatGPT sign-in. ...(target.driverKind === "scient" ? { liveVoice: liveVoice.runtime } : {}), interrupt: interrupt().pipe(Effect.mapError(safeFailure)), + // The RPC has no message-less continue, so Continue after a limit or Stop asks for one. + continuationPrompt: "Continue where you left off.", resume, rewindBefore: Effect.fn("OmpAdapterV2.rewindBefore")( function* (entryId: string) { diff --git a/apps/server/src/provider/omp/OmpSessionRuntime.test.ts b/apps/server/src/provider/omp/OmpSessionRuntime.test.ts index 130e983cdc..f9f2897644 100644 --- a/apps/server/src/provider/omp/OmpSessionRuntime.test.ts +++ b/apps/server/src/provider/omp/OmpSessionRuntime.test.ts @@ -913,6 +913,102 @@ describe("Oh My Pi session runtime outcomes", () => { ); } + it.effect("a later run that recovers in the same turn outweighs the prompt's failed run", () => + Effect.gen(function* () { + const h = yield* wireHarness(); + yield* h.runtime.begin("recovered"); + yield* h.runtime.accepted("prompt-recovered", true); + // The prompt's run gives up; a background result wakes the agent before the turn settles. + yield* h.wire.send( + { type: "agent_start" }, + assistantEnd({ stopReason: "error", errorMessage: "Couldn't reach chatgpt.com" }), + { type: "auto_retry_end", success: false, attempt: 10, finalError: "Retry budget spent" }, + { type: "agent_end", messages: [], isTerminal: true, yielded: true }, + { + type: "prompt_result", + id: "prompt-recovered", + agentInvoked: true, + status: "error", + error: { message: "Couldn't reach chatgpt.com", retryable: true, kinds: ["transient"] }, + sessionSettled: false, + }, + { type: "agent_start" }, + assistantEnd({ stopReason: "stop", content: [{ type: "text", text: "done" }] }), + { type: "agent_end", messages: [], isTerminal: true, yielded: true }, + ); + const outcome = yield* h.outcome; + yield* Scope.close(h.scope, Exit.void); + expect(outcome).toEqual({ + type: "turn-outcome", + outcome: "completed", + requestId: "prompt-recovered", + }); + }), + ); + + it.effect("a later run that fails too keeps the prompt's usage limit and reset time", () => + Effect.gen(function* () { + const h = yield* wireHarness(); + yield* h.runtime.begin("limited"); + yield* h.runtime.accepted("prompt-limited", true); + const limited = assistantEnd({ stopReason: "error", errorMessage: "429 rate limited" }); + yield* h.wire.send( + { type: "agent_start" }, + limited, + { type: "agent_end", messages: [], isTerminal: true, yielded: true }, + { + type: "prompt_result", + id: "prompt-limited", + agentInvoked: true, + status: "error", + error: { + message: "429 rate limited", + retryable: false, + httpStatus: 429, + resetAt: Date.UTC(2026, 10, 17), + }, + sessionSettled: false, + }, + { type: "agent_start" }, + limited, + { type: "agent_end", messages: [], isTerminal: true, yielded: true }, + ); + const outcome = yield* h.outcome; + yield* Scope.close(h.scope, Exit.void); + expect(outcome).toMatchObject({ + outcome: "failed", + failureClass: "usage_limit", + resetAt: "2026-11-17T00:00:00.000Z", + }); + }), + ); + + it.effect("a later run that fails after the prompt's run succeeded fails the turn", () => + Effect.gen(function* () { + const h = yield* wireHarness(); + yield* h.runtime.begin("woken"); + yield* h.runtime.accepted("prompt-woken", true); + yield* h.wire.send( + { type: "agent_start" }, + assistantEnd({ stopReason: "stop", content: [{ type: "text", text: "started a job" }] }), + { type: "agent_end", messages: [], isTerminal: true, yielded: true }, + { + type: "prompt_result", + id: "prompt-woken", + agentInvoked: true, + status: "completed", + sessionSettled: false, + }, + { type: "agent_start" }, + assistantEnd({ stopReason: "error", errorMessage: "Couldn't reach chatgpt.com" }), + { type: "agent_end", messages: [], isTerminal: true, yielded: true }, + ); + const outcome = yield* h.outcome; + yield* Scope.close(h.scope, Exit.void); + expect(outcome).toMatchObject({ outcome: "failed", detail: "Couldn't reach chatgpt.com" }); + }), + ); + it.effect("a late prompt_result of a settled turn does not decide the next one", () => Effect.gen(function* () { const h = yield* wireHarness(); diff --git a/apps/server/src/provider/omp/OmpSessionRuntime.ts b/apps/server/src/provider/omp/OmpSessionRuntime.ts index 5b71956e6e..3d19c476e5 100644 --- a/apps/server/src/provider/omp/OmpSessionRuntime.ts +++ b/apps/server/src/provider/omp/OmpSessionRuntime.ts @@ -503,6 +503,12 @@ export const makeOmpSessionRuntime = Effect.fn("makeOmpSessionRuntime")(function let commandRejected = false; /** Evidence for the open turn's outcome; reset when a turn begins. */ let evidence: TurnEvidence = {}; + /** + * A later run of the open turn started after its prompt's own run ended, for example when a + * background result woke the agent before the turn settled. prompt_result reports only the + * prompt's own run: when the later run ends normally, the turn recovered and completes. + */ + let promptSuperseded = false; const settledPromptIds: Array = []; /** * prompt_result and AsyncCommandFailure frames that arrived while the open @@ -613,9 +619,24 @@ export const makeOmpSessionRuntime = Effect.fn("makeOmpSessionRuntime")(function ...(commandRejected ? { source: "command" as const, failureCode: "command_rejected" } : {}), }; } + // After a later run, prompt_result describes only the prompt's own run, so the latest run's + // ending decides. Only a later run that failed after a failed prompt keeps the prompt's + // structured cause (a usage limit's reset time, for example). + const laterRunFailed = + evidence.stopReason === "error" || + evidence.stopReason === "aborted" || + evidence.retryExhausted === true; + const runOnly = promptSuperseded && !(laterRunFailed && evidence.promptStatus === "error"); const verdict = classifyOmpTurnOutcome(input.target, { settlement: outcome === "unknown" ? "unconfirmed" : "terminal", - ...evidence, + ...(runOnly + ? { + stopReason: evidence.stopReason, + errorMessage: evidence.errorMessage, + retryExhausted: evidence.retryExhausted, + retryFinalError: evidence.retryFinalError, + } + : evidence), }); if (verdict.outcome === "unknown") { return { @@ -698,6 +719,7 @@ export const makeOmpSessionRuntime = Effect.fn("makeOmpSessionRuntime")(function promptReported = false; promptWaitStartedAt = undefined; evidence = {}; + promptSuperseded = false; pendingOutcomes = []; yield* applySignal({ type: "begin", @@ -1015,8 +1037,21 @@ export const makeOmpSessionRuntime = Effect.fn("makeOmpSessionRuntime")(function ) { yield* startTurn(`${input.continuationIdPrefix}:${++continuationSequence}`, true); } + const followUpRun = turnIsOpen(turn) && turn.phase === "draining"; openRunId = ++runSequence; yield* applySignal({ type: "agent-start", runId: openRunId }); + if (followUpRun && turn.runId === openRunId) { + // Only this run's ending says whether the earlier run's failure was recovered from. + promptSuperseded = true; + evidence = { + ...evidence, + stopReason: undefined, + errorMessage: undefined, + assistantEnded: false, + retryExhausted: false, + retryFinalError: undefined, + }; + } return; } if (event.type === "agent_end") { diff --git a/apps/server/src/provider/omp/OmpTurnOutcome.test.ts b/apps/server/src/provider/omp/OmpTurnOutcome.test.ts index 8274dfebee..dec38d8910 100644 --- a/apps/server/src/provider/omp/OmpTurnOutcome.test.ts +++ b/apps/server/src/provider/omp/OmpTurnOutcome.test.ts @@ -46,6 +46,21 @@ const cases: ReadonlyArray = httpStatus: 429, }, ], + [ + "a network failure is named apart from a transient provider error", + { + ...terminal, + promptStatus: "error", + promptError: "Couldn't reach chatgpt.com (getaddrinfo ENOTFOUND).", + promptErrorKinds: ["transient", "network"], + }, + { + outcome: "failed", + stopReason: "error", + errorMessage: "Couldn't reach chatgpt.com (getaddrinfo ENOTFOUND).", + failureCode: "network", + }, + ], [ "a kind names the failure without changing its class", { diff --git a/apps/server/src/provider/omp/OmpTurnOutcome.ts b/apps/server/src/provider/omp/OmpTurnOutcome.ts index 3e7dcebba9..7337504895 100644 --- a/apps/server/src/provider/omp/OmpTurnOutcome.ts +++ b/apps/server/src/provider/omp/OmpTurnOutcome.ts @@ -99,6 +99,8 @@ const OMP_FAILURE_KIND_PRIORITY = [ "empty-response", "provider-finish-error", "timeout", + // Scient Agent: no response reached the provider (DNS, refused, offline), unlike an outage. + "network", "silent-abort", "user-interrupt", "abort", diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts index faa4b0d8b3..9acf95990f 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts @@ -622,6 +622,12 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make") operation: "termination", outcome: "abnormal", failureClass: message.failureClass, + // SCIENT-FORK:START — how the process ended + ...(message.exitReason === undefined + ? {} + : { exitReason: message.exitReason }), + ...(message.exitCode === undefined ? {} : { exitCode: message.exitCode }), + // SCIENT-FORK:END }) .pipe(Effect.ignoreCause()) : Effect.void, diff --git a/apps/server/src/telemetry/AnalyticsEventObserversV2.test.ts b/apps/server/src/telemetry/AnalyticsEventObserversV2.test.ts index bc755f98ad..a437df618d 100644 --- a/apps/server/src/telemetry/AnalyticsEventObserversV2.test.ts +++ b/apps/server/src/telemetry/AnalyticsEventObserversV2.test.ts @@ -29,6 +29,7 @@ import { makeV2AnalyticsObservers, } from "./AnalyticsEventObserversV2.ts"; import { BrowserToolCallLedger } from "./ScientMcpAnalytics.ts"; +import { analyticsRunRef } from "./AnalyticsRunRef.ts"; import { EventSinkStreamError, EventSinkV2 } from "../orchestration-v2/EventSink.ts"; import { ProjectionStoreV2 } from "../orchestration-v2/ProjectionStore.ts"; import { ProviderRegistry } from "../provider/ProviderRegistry.ts"; @@ -631,6 +632,7 @@ describe("native V2 analytics", () => { properties: { provider: "codex", model: "gpt-6", + runRef: analyticsRunRef(runId), durationMs: 5000, usedTools: true, hasAttachment: false, @@ -724,8 +726,10 @@ describe("native V2 analytics", () => { properties: { provider: "codex", model: "gpt-6", + runRef: analyticsRunRef(runId), durationMs: 5000, failureClass: "provider_error", + started: true, // Codex never sets "auth-failed", so that code is dropped; its status is still a status. httpStatus: 401, retryAttempts: 2, @@ -753,8 +757,10 @@ describe("native V2 analytics", () => { properties: { provider: "scient", model: "gpt-6", + runRef: analyticsRunRef(runId), durationMs: 5000, failureClass: "provider_error", + started: true, failureCode: "context-overflow", httpStatus: 400, retryAttempts: 0, @@ -763,7 +769,39 @@ describe("native V2 analytics", () => { ]); }); - it("counts each retry cycle's attempts, including a row a provider reuses after recovering", () => { + it("reports a run that fails while its session opens, and not one stopped before starting", () => { + const created = (status: OrchestrationV2Run["status"]) => ({ + ...runEvent(status), + type: "run.created" as const, + payload: { ...rootRun, status, startedAt: null }, + }); + const failedBeforeStart = (status: OrchestrationV2Run["status"]) => ({ + ...runAt(status), + payload: { ...rootRun, status, startedAt: null }, + }); + const mapper = createV2AnalyticsEventMapper(); + mapper.event(created("queued")); + mapper.event(errorItem("open", "failed", { class: "provider_error", code: "process_exit" })); + expect(mapper.event(failedBeforeStart("failed"))).toEqual([ + { + name: "provider.turn.failed", + properties: { + provider: "codex", + model: "gpt-6", + runRef: analyticsRunRef(runId), + durationMs: undefined, + failureClass: "provider_error", + started: false, + retryAttempts: 0, + }, + }, + ]); + const stopped = createV2AnalyticsEventMapper(); + stopped.event(created("queued")); + expect(stopped.event(failedBeforeStart("cancelled"))).toEqual([]); + }); + + it("counts each retry cycle's attempts on any node, including a row a provider reuses after recovering", () => { const mapper = createV2AnalyticsEventMapper(); mapper.event(runAt("running")); const transient = { class: "transport_error" as const, code: null }; @@ -777,8 +815,10 @@ describe("native V2 analytics", () => { ["completed", 1], ] as const) mapper.event(errorItem("reused-retry", status, transient, { attempt })); - mapper.event(errorItem("second-retry", "running", transient, { attempt: 1 })); - mapper.event(errorItem("second-retry", "completed", transient, { attempt: 1 })); + // A native retry row sits on its own node, not the run's root. + const nodeId = "native-retry-node"; + mapper.event(errorItem("second-retry", "running", transient, { attempt: 1, nodeId })); + mapper.event(errorItem("second-retry", "completed", transient, { attempt: 1, nodeId })); expect(mapper.event(runAt("completed"))).toMatchObject([ { name: "provider.turn.completed", properties: { retryAttempts: 5 } }, ]); @@ -914,7 +954,13 @@ describe("native V2 analytics", () => { expect(mapper.event(runEvent(status))).toEqual([ { name: "provider.turn.stopped", - properties: { provider: "codex", model: "gpt-6", durationMs: 5000, stopClass: status }, + properties: { + provider: "codex", + model: "gpt-6", + runRef: analyticsRunRef(runId), + durationMs: 5000, + stopClass: status, + }, }, ]); } diff --git a/apps/server/src/telemetry/AnalyticsEventObserversV2.ts b/apps/server/src/telemetry/AnalyticsEventObserversV2.ts index d291066b11..00314ad9e1 100644 --- a/apps/server/src/telemetry/AnalyticsEventObserversV2.ts +++ b/apps/server/src/telemetry/AnalyticsEventObserversV2.ts @@ -15,6 +15,7 @@ import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import { ProviderRegistry } from "../provider/ProviderRegistry.ts"; import { ProviderInstanceRegistry } from "../provider/ProviderInstanceRegistry.ts"; import { AnalyticsService } from "./AnalyticsService.ts"; +import { analyticsRunRef } from "./AnalyticsRunRef.ts"; import { createProviderAccountAnalyticsMapper } from "./ProviderAccountAnalytics.ts"; import { createProviderLifecycleAnalyticsMapper } from "./ProviderLifecycleAnalytics.ts"; import { classifyCommand, shellCommandOf } from "./CommandCategories.ts"; @@ -25,7 +26,13 @@ type Observation = { readonly name: string; readonly properties: Readonly>; }; -type EventContext = { readonly driver?: ProviderDriverKind; readonly refork?: boolean }; +type EventContext = { + readonly driver?: ProviderDriverKind; + readonly refork?: boolean; + /** The provider runtime's own version, such as Scient Agent's. */ + readonly providerVersion?: string; +}; + const CAPACITY = 1_000; const MAX_COMMANDS_PER_RUN = 10_000; /** Scient's own progress rows, written as commands; they are not an agent's program. */ @@ -113,7 +120,9 @@ export function createV2AnalyticsEventMapper(browserCalls?: BrowserToolCallLedge { provider: string; model: string; - startedAt: number; + providerVersion: string | undefined; + /** Null until the run starts; a run can fail while its session is still opening. */ + startedAt: number | null; usedTools: boolean; hasAttachment: boolean; rootNodeId: string | null; @@ -200,16 +209,27 @@ export function createV2AnalyticsEventMapper(browserCalls?: BrowserToolCallLedge }, }); } - if ( - (run.status === "running" || run.status === "waiting") && - run.startedAt !== null && + const live = !["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes( + run.status, + ); + const known = runs.get(key); + if (known !== undefined) { + known.rootNodeId = run.rootNodeId; + if (known.startedAt === null && run.startedAt !== null) + known.startedAt = DateTime.toEpochMillis(run.startedAt); + } else if ( driver !== undefined && - !runs.has(key) + (entry.type === "run.created" + ? live + : (run.status === "running" || run.status === "waiting") && run.startedAt !== null) ) { + // A run seen from its creation is followed even if it never starts, so a failure to open + // its session is reported too. Older runs are followed from when they start running. remember(runs, key, { provider: driver, model: run.modelSelection.model, - startedAt: DateTime.toEpochMillis(run.startedAt), + providerVersion: context.providerVersion, + startedAt: run.startedAt === null ? null : DateTime.toEpochMillis(run.startedAt), usedTools: false, hasAttachment: false, rootNodeId: run.rootNodeId, @@ -226,14 +246,22 @@ export function createV2AnalyticsEventMapper(browserCalls?: BrowserToolCallLedge const browser = browserCalls?.take(entry.threadId, DateTime.toEpochMillis(entry.occurredAt)); const correlation = runs.get(key); runs.delete(key); - // A historical/consent-boundary terminal or failed workspace preparation - // is not evidence of an observed provider turn. + // A historical/consent-boundary terminal is not evidence of an observed provider turn. if (correlation === undefined) return []; - const elapsed = DateTime.toEpochMillis(entry.occurredAt) - correlation.startedAt; + // A run that never started only matters when it failed: stopping a queued run is not a turn. + if (correlation.startedAt === null && run.status !== "failed") return []; + const elapsed = + correlation.startedAt === null + ? undefined + : DateTime.toEpochMillis(entry.occurredAt) - correlation.startedAt; const properties = { provider: correlation.provider, model: correlation.model, - durationMs: elapsed >= 0 ? elapsed : undefined, + runRef: analyticsRunRef(key), + ...(correlation.providerVersion === undefined + ? {} + : { providerVersion: correlation.providerVersion }), + durationMs: elapsed !== undefined && elapsed >= 0 ? elapsed : undefined, ...(browser === undefined ? {} : { browserToolCalls: browser.calls, browserToolFailures: browser.failures }), @@ -273,7 +301,12 @@ export function createV2AnalyticsEventMapper(browserCalls?: BrowserToolCallLedge name: "provider.turn.failed", properties: { ...properties, - failureClass: failure?.class ?? "provider_error", + // A run that failed before starting without a provider failure (its + // workspace could not be prepared, say) is not the provider's error. + failureClass: + failure?.class ?? + (correlation.startedAt === null ? "unknown" : "provider_error"), + started: correlation.startedAt !== null, ...(failureCode === undefined ? {} : { failureCode }), ...(failure?.httpStatus === undefined ? {} @@ -305,8 +338,13 @@ export function createV2AnalyticsEventMapper(browserCalls?: BrowserToolCallLedge ].includes(item.type) ) run.usedTools = true; - if (item.type === "error" && item.nodeId === run.rootNodeId) { - if (run.errors.has(item.id) || run.errors.size < MAX_ERROR_ITEMS_PER_RUN) + if (item.type === "error") { + // The run's failure is its root node's; retries are counted wherever the run made them, + // since native retry rows sit on their own nodes. + if ( + item.nodeId === run.rootNodeId && + (run.errors.has(item.id) || run.errors.size < MAX_ERROR_ITEMS_PER_RUN) + ) run.errors.set(item.id, item); if (item.retry !== undefined) countRetry(run.retries, item); } @@ -471,8 +509,16 @@ export const launchV2AnalyticsEventObservers = Effect.gen(function* () { }), (unsubscribe) => Effect.sync(unsubscribe), ); - yield* observer.providers(yield* providers.getProviders); - yield* providers.streamChanges.pipe(Stream.runForEach(observer.providers), Effect.forkScoped); + // Each instance's runtime version, so an outcome says which agent build produced it. + const versions = new Map(); + const observeProviders = (snapshot: ReadonlyArray) => { + versions.clear(); + for (const provider of snapshot) + if (provider.version !== null) versions.set(provider.instanceId, provider.version); + return observer.providers(snapshot); + }; + yield* observeProviders(yield* providers.getProviders); + yield* providers.streamChanges.pipe(Stream.runForEach(observeProviders), Effect.forkScoped); // The subscription cursor is immutable. Never pass the fail-closed Infinity // sentinel upstream: wait for a successful boundary, including recovery from // an unavailable initial read or a superseded registration. @@ -493,6 +539,7 @@ export const launchV2AnalyticsEventObservers = Effect.gen(function* () { : entry.providerInstanceId; const instance = instanceId === undefined ? undefined : yield* instances.getInstance(instanceId); + const providerVersion = instanceId === undefined ? undefined : versions.get(instanceId); const fork = entry.type === "thread.created" ? entry.payload.conversationFork : undefined; const origin = fork?.status === "pending" @@ -504,6 +551,7 @@ export const launchV2AnalyticsEventObservers = Effect.gen(function* () { entry, { ...(instance === undefined ? {} : { driver: instance.driverKind }), + ...(providerVersion === undefined ? {} : { providerVersion }), ...(origin === null ? {} : { refork: origin.forkLineage != null }), }, expectedEpoch, diff --git a/apps/server/src/telemetry/AnalyticsRunRef.ts b/apps/server/src/telemetry/AnalyticsRunRef.ts new file mode 100644 index 0000000000..5949de9559 --- /dev/null +++ b/apps/server/src/telemetry/AnalyticsRunRef.ts @@ -0,0 +1,13 @@ +// @effect-diagnostics nodeBuiltinImport:off -- a synchronous hash inside a pure event mapper. +import * as NodeCrypto from "node:crypto"; + +/** + * Joins one run's analytics events (its outcome, its request totals) without sending its id: a + * one-way hash of a random local id, so the reports cannot be traced back to a thread. + */ +export function analyticsRunRef(runId: string): string { + return NodeCrypto.createHash("sha256") + .update(`scient-analytics-run:${runId}`) + .digest("hex") + .slice(0, 16); +} diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 83fcab9ef3..990fbe0fdd 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -154,6 +154,9 @@ describe("provider usage reporting", () => { provider: "codex", requestKind: "user", terminalStatus: "completed", + // SCIENT-FORK:START — a one-way hash joins the report to the run's outcome + runRef: expect.stringMatching(/^[0-9a-f]{16}$/u), + // SCIENT-FORK:END lifecycleObserved: true, model: "gpt-6-sol", mainModel: "gpt-6-sol", diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index 7492377ac3..39ca02c3c8 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -28,6 +28,7 @@ import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; // SCIENT-FORK:START — name every model an agent reports, and a turn's main model import { reportedModelLabel, turnModelProperties } from "./ScientModelLabels.ts"; +import { analyticsRunRef } from "./AnalyticsRunRef.ts"; // SCIENT-FORK:END // Bump when a field changes meaning, so reports can split old and new rows. @@ -354,6 +355,9 @@ export class RequestUsageLedger { requestKind: requestKind(entry.context?.origin), restartContinuation: entry.context?.restartContinuation === true ? true : undefined, terminalStatus: report.status, + // SCIENT-FORK:START — joins this report to the run's outcome event + runRef: analyticsRunRef(report.runId), + // SCIENT-FORK:END lifecycleObserved, ...selectionProperties(entry.context, label), ...turnModelProperties( diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md index 6a396d9481..91e0821a00 100644 --- a/docs/internals/product-analytics.md +++ b/docs/internals/product-analytics.md @@ -700,9 +700,22 @@ Compute runs also carry `actor` (`user` or `agent`), `entry` (`console`, `file`, anything else, since a code that only looks like an identifier may be free text a provider sent. - `httpStatus`: the provider's HTTP status, 100 to 599, on the failure itself (`OrchestrationV2ProviderFailure.httpStatus`). -- `retryAttempts`, also on `provider.turn.completed`: retry attempts the provider reported for the - turn's root, each retry cycle counted at its highest attempt. These are reported attempts, not - proven requests. Zero means none was reported. +- `retryAttempts`, also on `provider.turn.completed`: retry attempts the provider reported anywhere + in the run (native retry rows sit on their own nodes, not the run's root), each retry cycle + counted at its highest attempt. These are reported attempts, not proven requests. Zero means none + was reported. +- `started`: `false` when the run failed before its provider session started (the session would + not open, or its workspace could not be prepared). Such a run with no provider failure has + `failureClass` `unknown`. A run stopped before it started reports nothing. + +Every turn outcome (`provider.turn.completed`, `failed`, `stopped`) and `provider.request.completed` +carry `runRef`, the first 16 hex characters of a SHA-256 of the local run id, so a run's outcome +joins its request totals without sending the id. Turn outcomes also carry `providerVersion`, the +provider runtime's own release (Scient Agent's version, for example), when it is a plain release +number. `app.diagnostics` adds `oldestEventAgeBucket`, how long the delivered batch's oldest event +waited on the computer, so an outage shows as late delivery rather than missing events. A renderer +`app.health` termination adds `exitReason` (`crashed`, `oom`, `killed`, `abnormal-exit`) and +`exitCode`; on macOS exit code 5 (SIGTRAP) is a Chromium `CHECK`, not memory pressure. The failure is the run's latest failed root error item, as `latestRootProviderFailure` picks it; a retry that recovered or a subagent's error is not the turn's failure. These fields explain a diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts index 42a43d04c8..69e1f158be 100644 --- a/packages/contracts/src/resourceTelemetry.ts +++ b/packages/contracts/src/resourceTelemetry.ts @@ -302,6 +302,10 @@ export const DesktopAppHealthReport = Schema.Struct({ type: Schema.Literal("scientAppHealth"), component: Schema.Literals(["renderer", "desktop"]), failureClass: Schema.Literals(["process-crash", "resource-exhaustion", "unknown"]), + // SCIENT-FORK:START — how the process ended: exit code 5 on macOS is a Chromium CHECK (SIGTRAP). + exitReason: Schema.optionalKey(Schema.Literals(["crashed", "oom", "killed", "abnormal-exit"])), + exitCode: Schema.optionalKey(Schema.Int), + // SCIENT-FORK:END }); export type DesktopAppHealthReport = typeof DesktopAppHealthReport.Type; diff --git a/packages/provider-core/src/server/failure.scient.test.ts b/packages/provider-core/src/server/failure.scient.test.ts new file mode 100644 index 0000000000..49617546cb --- /dev/null +++ b/packages/provider-core/src/server/failure.scient.test.ts @@ -0,0 +1,25 @@ +import { assert, it } from "@effect/vitest"; +import { ProviderDriverKind, ProviderSessionId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; + +import { makeProviderFailure } from "./failure.ts"; +import * as ProviderAdapter from "./ProviderAdapter.ts"; + +it("names what failed beneath a native session-open wrapper, redacted", () => { + const sessionOpenFailure = { + _tag: "ProviderSessionOpenError", + cause: new ProviderAdapter.ProviderAdapterOpenSessionError({ + driver: ProviderDriverKind.make("scient"), + providerSessionId: ProviderSessionId.make("provider-session:private-id"), + cause: { + _tag: "NativeSessionOperationError", + message: "Bearer open-secret; RPC command get_available_models timed out after 30000 ms.", + cause: new Error("raw private-detail"), + }, + }), + }; + assert.equal( + makeProviderFailure({ cause: Cause.fail(sessionOpenFailure) }).message, + "The provider session could not be opened: Bearer [REDACTED]; RPC command get_available_models timed out after 30000 ms. Check that the provider is installed and signed in, then retry the turn.", + ); +}); diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 64e7461317..0966d1225f 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -116,10 +116,17 @@ function curatedCauseMessages(cause: unknown): { category: categoryMessage(), }; // A refused native turn left the session intact, and its adapter wrote and redacted the reason. - case "NativeSessionOperationError": + case "NativeSessionOperationError": { if ((cause as Record).breaksSession === false) return { known: stringField(cause, "message"), category: categoryMessage() }; + // Beneath the generic open wrapper, the adapter's redacted reason names what failed. + const detail = stringField(cause, "message")?.replace(/[\s.]+$/u, ""); + if (category === PROVIDER_FAILURE_CATEGORIES.ProviderAdapterOpenSessionError && detail) { + reason = detail; + return { known: categoryMessage(), category: categoryMessage() }; + } break; + } // SCIENT-FORK:END case "ContextHandoffBudgetError": return { known: new ContextHandoffBudgetError().message, category: categoryMessage() }; diff --git a/packages/scient-analytics/fixtures/contract-v11.json b/packages/scient-analytics/fixtures/contract-v11.json index 6974d229c8..d676a7873e 100644 --- a/packages/scient-analytics/fixtures/contract-v11.json +++ b/packages/scient-analytics/fixtures/contract-v11.json @@ -95,6 +95,7 @@ "queuedCountBucket": "unknown", "droppedCountBucket": "unknown", "retryCountBucket": "unknown", + "oldestEventAgeBucket": "unknown", "deliveryClass": "unknown", "appVersion": "0.6.8", "buildChannel": "stable", @@ -110,6 +111,7 @@ "queuedCountBucket": "4-10", "droppedCountBucket": "2-3", "retryCountBucket": "1", + "oldestEventAgeBucket": "unknown", "deliveryClass": "network", "appVersion": "0.6.8", "buildChannel": "stable", diff --git a/packages/scient-analytics/src/contract.test.ts b/packages/scient-analytics/src/contract.test.ts index ba1d687448..2f23ed8ac6 100644 --- a/packages/scient-analytics/src/contract.test.ts +++ b/packages/scient-analytics/src/contract.test.ts @@ -209,6 +209,20 @@ describe("Scient analytics contract", () => { failureClass: "unknown", }, }); + // The run's hash and the agent build pass; anything shaped otherwise is dropped. + const run = (runRef: string, providerVersion: string) => + normalizeInheritedEvent( + "provider.turn.failed", + { provider: "scient", runRef, providerVersion, started: false }, + context, + )?.properties; + expect(run("0123456789abcdef", "0.1.11")).toMatchObject({ + runRef: "0123456789abcdef", + providerVersion: "0.1.11", + started: false, + }); + expect(run("private-run-id", "custom build")).not.toHaveProperty("runRef"); + expect(run("private-run-id", "custom build")).not.toHaveProperty("providerVersion"); }); it("records events and fields without a Scient normalizer, as T3 does", () => { diff --git a/packages/scient-analytics/src/contract.ts b/packages/scient-analytics/src/contract.ts index eb35c330dd..1bc3d33d9c 100644 --- a/packages/scient-analytics/src/contract.ts +++ b/packages/scient-analytics/src/contract.ts @@ -312,6 +312,7 @@ const FAILURE_CLASSES = new Set([ "publish", "workspace", ]); +const PROCESS_EXIT_REASONS = new Set(["crashed", "oom", "killed", "abnormal-exit"]); const HEALTH_COMPONENTS = new Set(["desktop", "server", "renderer", "browser", "analytics"]); const HEALTH_OPERATIONS = new Set([ "startup", @@ -711,6 +712,21 @@ function optionalProperties( return properties; } +/** Which run a turn outcome belongs to (a one-way hash), and the agent build that ran it. */ +function turnRunProperties(input: Readonly>): { + runRef?: string; + providerVersion?: string; +} { + const runRef = property(input, "runRef"); + const version = property(input, "providerVersion"); + return { + ...(typeof runRef === "string" && /^[0-9a-f]{16}$/u.test(runRef) ? { runRef } : {}), + ...(typeof version === "string" && analyticsAppVersion(version) !== "unknown" + ? { providerVersion: version } + : {}), + }; +} + /** A failure code, kept only when it is one of `provider`'s known categories. */ function failureCodeProperty( provider: string, @@ -749,6 +765,17 @@ function optionalModelKeys( ); } +/** How long an event waited on this computer before it was sent. */ +function ageBucket(value: unknown): string { + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return "unknown"; + if (value < 60_000) return "under-1m"; + if (value < 600_000) return "1-10m"; + if (value < 3_600_000) return "10-60m"; + if (value < 21_600_000) return "1-6h"; + if (value < 86_400_000) return "6-24h"; + return "over-1d"; +} + function countBucket(value: unknown): string { if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return "unknown"; if (value === 0) return "0"; @@ -927,6 +954,11 @@ function normalizeEvent( outcome: normalizedEnum(property(input, "outcome"), HEALTH_OUTCOMES), failureClass: normalizedEnum(property(input, "failureClass"), FAILURE_CLASSES), durationBucket: durationBucket(property(input, "durationMs")), + // How a process ended: macOS exit code 5 (SIGTRAP) is a Chromium CHECK, not memory. + ...optionalProperties(input, { exitReason: PROCESS_EXIT_REASONS }), + ...(Number.isSafeInteger(property(input, "exitCode")) + ? { exitCode: property(input, "exitCode") as number } + : {}), }, }; case "app.diagnostics": @@ -938,6 +970,7 @@ function normalizeEvent( queuedCountBucket: countBucket(property(input, "queuedCount")), droppedCountBucket: countBucket(property(input, "droppedCount")), retryCountBucket: countBucket(property(input, "retryCount")), + oldestEventAgeBucket: ageBucket(property(input, "oldestEventAgeMs")), deliveryClass: normalizedEnum(property(input, "deliveryClass"), DELIVERY_CLASSES), }, }; @@ -1447,6 +1480,7 @@ function normalizeEvent( browserToolFailures: "count", retryAttempts: "count", }), + ...turnRunProperties(input), }, }; case "provider.turn.failed": @@ -1461,7 +1495,10 @@ function normalizeEvent( browserToolCalls: "count", browserToolFailures: "count", retryAttempts: "count", + // False when the run failed before its provider session started. + started: "boolean", }), + ...turnRunProperties(input), ...failureCodeProperty(provider, input), ...httpStatusProperty(input), failureClass: normalizedEnum(property(input, "failureClass"), TURN_FAILURE_CLASSES), @@ -1477,6 +1514,7 @@ function normalizeEvent( provider, modelKey: modelKey(property(input, "model")), ...optionalProperties(input, { browserToolCalls: "count", browserToolFailures: "count" }), + ...turnRunProperties(input), durationBucket: durationBucket(property(input, "durationMs")), stopClass: normalizedEnum(property(input, "stopClass"), TURN_STOP_CLASSES), }, diff --git a/packages/scient-analytics/src/failureCodes.ts b/packages/scient-analytics/src/failureCodes.ts index b3f02d4bd0..f85312310e 100644 --- a/packages/scient-analytics/src/failureCodes.ts +++ b/packages/scient-analytics/src/failureCodes.ts @@ -27,6 +27,7 @@ const OMP_CODES = new Set([ "empty-response", "provider-finish-error", "timeout", + "network", "silent-abort", "user-interrupt", "abort", diff --git a/packages/scient-analytics/src/runtime.test.ts b/packages/scient-analytics/src/runtime.test.ts index 6bdb28b5ed..14f9a4aec9 100644 --- a/packages/scient-analytics/src/runtime.test.ts +++ b/packages/scient-analytics/src/runtime.test.ts @@ -240,6 +240,7 @@ describe("Scient analytics background runtime", () => { queuedCountBucket: "0", retryCountBucket: "0", droppedCountBucket: "0", + oldestEventAgeBucket: "under-1m", }, }, ], diff --git a/packages/scient-analytics/src/runtime.ts b/packages/scient-analytics/src/runtime.ts index 9dccb771d8..b5b438038d 100644 --- a/packages/scient-analytics/src/runtime.ts +++ b/packages/scient-analytics/src/runtime.ts @@ -214,6 +214,7 @@ export function createAnalyticsRuntime(options: AnalyticsRuntimeOptions): Analyt queuedCount: response.queuedCount, droppedCount: response.droppedCount, retryCount: response.retryCount, + oldestEventAgeMs: response.oldestEventAgeMs, deliveryClass: response.deliveryClass, }); return; diff --git a/packages/scient-analytics/src/workerProtocol.ts b/packages/scient-analytics/src/workerProtocol.ts index f874d156df..02eb6e5947 100644 --- a/packages/scient-analytics/src/workerProtocol.ts +++ b/packages/scient-analytics/src/workerProtocol.ts @@ -44,6 +44,8 @@ export type AnalyticsWorkerResponse = readonly queuedCount: number; readonly droppedCount: number; readonly retryCount: number; + /** How long the batch's oldest event waited to be sent, in milliseconds. */ + readonly oldestEventAgeMs: number; readonly deliveryClass: "delivered" | "timeout" | "network" | "rejected"; } | { diff --git a/packages/scient-analytics/src/workerRuntime.ts b/packages/scient-analytics/src/workerRuntime.ts index 4587202111..161376eea8 100644 --- a/packages/scient-analytics/src/workerRuntime.ts +++ b/packages/scient-analytics/src/workerRuntime.ts @@ -295,11 +295,14 @@ export function startAnalyticsWorker( return; } lastDiagnosticsAt = timestamp; + const oldest = Math.min(...events.map((event) => Date.parse(event.occurred_at))); post({ type: "diagnostics", queuedCount: outbox.size(), droppedCount: outbox.takeDroppedCount(), retryCount: Math.max(...events.map((event) => event.attemptCount)), + // An outage shows as delayed delivery, not as missing events. + oldestEventAgeMs: Number.isFinite(oldest) ? Math.max(0, timestamp - oldest) : -1, deliveryClass: outcome.kind === "transport" ? outcome.deliveryClass : outcome.kind, }); };