From 1faa089302b231994e29d2396cbc1e5475f60903 Mon Sep 17 00:00:00 2001 From: Roomote Date: Thu, 5 Nov 2026 20:37:32 +0000 Subject: [PATCH 1/7] fix(telemetry): stop code-index error retry storm and hash PostHog distinct IDs (#830) - Add a per-workspace circuit breaker to the code-index file watcher: after 3 consecutive failed batches it drops further file-system events until the watcher is recreated (embedder/vector-store config change), stopping the retry loop behind the 254k-event Code Index Error spike. - Remove the two per-call captureToolUsage sites re-added by #1073 so tool usage reports only as the aggregated toolsUsed breakdown on Task Completed; drop the dead captureToolUsage/captureConversationMessage methods from TelemetryService. - Salt-hash the PostHog distinct ID (SHA-256 + fixed salt) in PostHogTelemetryClient and before posting machineId to the webview, so the raw VS Code machine ID never leaves the extension host. - Update PRIVACY.md: hashed machine-ID wording and a clarification that the Cloud sync pipeline is separate from PostHog telemetry (issue #830). --- PRIVACY.md | 18 ++- .../telemetry/src/PostHogTelemetryClient.ts | 5 +- packages/telemetry/src/TelemetryService.ts | 8 -- .../__tests__/PostHogTelemetryClient.test.ts | 45 ++++-- packages/telemetry/src/distinct-id.ts | 14 ++ packages/telemetry/src/index.ts | 1 + packages/types/src/vscode-extension-host.ts | 4 + ...tantMessage-tool-usage-attribution.spec.ts | 10 -- .../presentAssistantMessage.ts | 6 +- src/core/webview/ClineProvider.ts | 6 +- .../ClineProvider.flicker-free-cancel.spec.ts | 20 ++- .../ClineProvider.lockApiConfig.spec.ts | 32 +++-- .../ClineProvider.sticky-mode.spec.ts | 32 +++-- .../ClineProvider.sticky-profile.spec.ts | 32 +++-- src/services/code-index/constants/index.ts | 1 + .../processors/__tests__/file-watcher.spec.ts | 129 ++++++++++++++++++ .../code-index/processors/file-watcher.ts | 61 ++++++++- 17 files changed, 334 insertions(+), 90 deletions(-) create mode 100644 packages/telemetry/src/distinct-id.ts diff --git a/PRIVACY.md b/PRIVACY.md index f43760023db..ad86ff61489 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -33,13 +33,17 @@ go—and, importantly, where they don't. model), it is stored locally on your device and never sent to us or any third party, except the provider you have chosen. - **Telemetry (Usage Data)**: We collect feature usage and error data to help us - improve Zoo Code. This telemetry is powered by PostHog and includes your VS - Code machine ID, feature usage patterns, and exception reports. The VS Code - machine ID is a persistent identifier and may be considered personal data in - some jurisdictions; we use it only for product analytics and error grouping. - PostHog event data is retained for 12 months under our current project - configuration. This PostHog-based telemetry does **not** collect your code or AI - prompts. Telemetry is on by default. To turn it off, choose "Disabled" in + improve Zoo Code. This telemetry is powered by PostHog and includes a salted, + hashed (pseudonymized) form of your VS Code machine ID, feature usage + patterns, and exception reports. The raw VS Code machine ID never leaves your + device; we use the hashed identifier only for product analytics and error + grouping. PostHog event data is retained for 12 months under our current + project configuration. This PostHog-based telemetry does **not** collect your + code or AI prompts. (Separately, if you sign in to Zoo Code Cloud and enable + Cloud sync, the Cloud sync pipeline — which is distinct from this PostHog + telemetry — does transmit task messages so they can be shared or synced + through your Cloud account; that feature is controlled by its own Cloud sync + settings.) Telemetry is on by default. To turn it off, choose "Disabled" in the settings or in the notice shown on first use. The notice remains until you explicitly Accept or Decline. Telemetry also follows VS Code's own global telemetry setting: if you turn that off, Zoo Code stops sending diff --git a/packages/telemetry/src/PostHogTelemetryClient.ts b/packages/telemetry/src/PostHogTelemetryClient.ts index 77f0bd2aa53..90a31b94e76 100644 --- a/packages/telemetry/src/PostHogTelemetryClient.ts +++ b/packages/telemetry/src/PostHogTelemetryClient.ts @@ -15,6 +15,7 @@ import { } from "@roo-code/types" import { BaseTelemetryClient } from "./BaseTelemetryClient" +import { hashDistinctId } from "./distinct-id" /** * PostHogTelemetryClient handles telemetry event tracking for the Roo Code extension. @@ -23,7 +24,9 @@ import { BaseTelemetryClient } from "./BaseTelemetryClient" */ export class PostHogTelemetryClient extends BaseTelemetryClient { private client: PostHog - private distinctId: string = vscode.env.machineId + // Pseudonymous distinct ID: salted SHA-256 of the machine ID, never the raw + // value (issue #830). + private distinctId: string = hashDistinctId(vscode.env.machineId) // Git repository properties that should be filtered out private readonly gitPropertyNames = ["repositoryUrl", "repositoryName", "defaultBranch"] diff --git a/packages/telemetry/src/TelemetryService.ts b/packages/telemetry/src/TelemetryService.ts index 4b4115e9db3..2ebd632c85a 100644 --- a/packages/telemetry/src/TelemetryService.ts +++ b/packages/telemetry/src/TelemetryService.ts @@ -211,10 +211,6 @@ export class TelemetryService { }) } - public captureConversationMessage(taskId: string, source: "user" | "assistant"): void { - this.captureEvent(TelemetryEventName.TASK_CONVERSATION_MESSAGE, { taskId, source }) - } - public captureLlmCompletion( taskId: string, properties: { @@ -232,10 +228,6 @@ export class TelemetryService { this.captureEvent(TelemetryEventName.MODE_SWITCH, { taskId, newMode }) } - public captureToolUsage(taskId: string, tool: string): void { - this.captureEvent(TelemetryEventName.TOOL_USED, { taskId, tool }) - } - public captureCheckpointCreated(taskId: string): void { this.captureEvent(TelemetryEventName.CHECKPOINT_CREATED, { taskId }) } diff --git a/packages/telemetry/src/__tests__/PostHogTelemetryClient.test.ts b/packages/telemetry/src/__tests__/PostHogTelemetryClient.test.ts index 1feeb1688f7..fd9f6066ce3 100644 --- a/packages/telemetry/src/__tests__/PostHogTelemetryClient.test.ts +++ b/packages/telemetry/src/__tests__/PostHogTelemetryClient.test.ts @@ -8,6 +8,11 @@ import { PostHog } from "posthog-node" import { type TelemetryPropertiesProvider, TelemetryEventName, ApiProviderError } from "@roo-code/types" import { PostHogTelemetryClient } from "../PostHogTelemetryClient" +import { hashDistinctId } from "../distinct-id" + +// The client must use the salted hash as its PostHog distinct ID, never the raw +// VS Code machine ID (issue #830). +const hashedMachineId = hashDistinctId("test-machine-id") vi.mock("posthog-node") @@ -277,7 +282,7 @@ describe("PostHogTelemetryClient", () => { }) expect(mockPostHogClient.capture).toHaveBeenCalledWith({ - distinctId: "test-machine-id", + distinctId: hashedMachineId, event: TelemetryEventName.TASK_CREATED, properties: expect.objectContaining({ appVersion: "1.0.0", @@ -286,6 +291,22 @@ describe("PostHogTelemetryClient", () => { }) }) + it("never uses the raw VS Code machine ID as the PostHog distinct ID", async () => { + const client = new PostHogTelemetryClient() + client.updateTelemetryState(true) + + await client.capture({ + event: TelemetryEventName.TASK_CREATED, + properties: { test: "value" }, + }) + + expect(mockPostHogClient.capture).toHaveBeenCalledTimes(1) + const captureCall = mockPostHogClient.capture.mock.calls[0][0] + expect(captureCall.distinctId).toBe(hashedMachineId) + expect(captureCall.distinctId).not.toBe("test-machine-id") + expect(captureCall.distinctId).not.toContain("test-machine-id") + }) + it("should filter out git repository properties when capturing events", async () => { const client = new PostHogTelemetryClient() client.updateTelemetryState(true) @@ -313,7 +334,7 @@ describe("PostHogTelemetryClient", () => { }) expect(mockPostHogClient.capture).toHaveBeenCalledWith({ - distinctId: "test-machine-id", + distinctId: hashedMachineId, event: TelemetryEventName.TASK_CREATED, properties: expect.objectContaining({ appVersion: "1.0.0", @@ -402,7 +423,7 @@ describe("PostHogTelemetryClient", () => { expect(mockPostHogClient.captureException).toHaveBeenCalledWith( error, - "test-machine-id", + hashedMachineId, expect.objectContaining({ customProp: "value", $app_version: "1.0.0", @@ -417,7 +438,7 @@ describe("PostHogTelemetryClient", () => { const error = new Error("Test error") await client.captureException(error) - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { $app_version: undefined, }) }) @@ -485,7 +506,7 @@ describe("PostHogTelemetryClient", () => { const error = new Error("Internal server error") client.captureException(error) - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { $app_version: undefined, }) }) @@ -497,7 +518,7 @@ describe("PostHogTelemetryClient", () => { const error = Object.assign(new Error("Internal server error"), { status: 500 }) client.captureException(error) - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { $app_version: undefined, }) }) @@ -537,7 +558,7 @@ describe("PostHogTelemetryClient", () => { // The implementation overrides error.message with the extracted message from getErrorMessage expect(error.message).toBe("Upstream provider error: model overloaded") - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { $app_version: undefined, }) }) @@ -558,7 +579,7 @@ describe("PostHogTelemetryClient", () => { // The implementation overrides error.message with the extracted message from getErrorMessage expect(error.message).toBe("Upstream provider: connection timeout") - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { $app_version: undefined, }) }) @@ -576,7 +597,7 @@ describe("PostHogTelemetryClient", () => { // Verify error message remains the primary message expect(error.message).toBe("Primary error message") - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { $app_version: undefined, }) }) @@ -589,7 +610,7 @@ describe("PostHogTelemetryClient", () => { client.captureException(error) // The implementation auto-extracts properties from ApiProviderError - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { provider: "OpenRouter", modelId: "gpt-4", operation: "createMessage", @@ -606,7 +627,7 @@ describe("PostHogTelemetryClient", () => { client.captureException(error, { customProperty: "value" }) // additionalProperties take precedence over auto-extracted properties - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { provider: "OpenRouter", modelId: "gpt-4", operation: "createMessage", @@ -622,7 +643,7 @@ describe("PostHogTelemetryClient", () => { const error = new Error("Regular error") client.captureException(error, { customProperty: "value" }) - expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, "test-machine-id", { + expect(mockPostHogClient.captureException).toHaveBeenCalledWith(error, hashedMachineId, { customProperty: "value", $app_version: undefined, }) diff --git a/packages/telemetry/src/distinct-id.ts b/packages/telemetry/src/distinct-id.ts new file mode 100644 index 00000000000..2c9c16683e3 --- /dev/null +++ b/packages/telemetry/src/distinct-id.ts @@ -0,0 +1,14 @@ +import { createHash } from "crypto" + +/** + * Fixed, non-secret application salt. The raw VS Code machine ID is a stable, + * device-scoped identifier that may be considered personal data; combining it + * with this salt under SHA-256 yields a pseudonymous distinct ID that is still + * stable per device, so PostHog analytics and error grouping keep working while + * the raw identifier never leaves the extension host. + */ +const DISTINCT_ID_SALT = "zoo-code-telemetry-distinct-id-v1" + +export function hashDistinctId(machineId: string): string { + return createHash("sha256").update(`${DISTINCT_ID_SALT}:${machineId}`).digest("hex") +} diff --git a/packages/telemetry/src/index.ts b/packages/telemetry/src/index.ts index 8795ad46a2e..4f051d6c36e 100644 --- a/packages/telemetry/src/index.ts +++ b/packages/telemetry/src/index.ts @@ -1,3 +1,4 @@ export * from "./BaseTelemetryClient" +export * from "./distinct-id" export * from "./PostHogTelemetryClient" export * from "./TelemetryService" diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 2e9ea7ccb84..4e7efff57fc 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -423,6 +423,10 @@ export type ExtensionState = Pick< cwd?: string // Current working directory telemetrySetting: TelemetrySetting telemetryKey?: string + // Salted SHA-256 hash of vscode.env.machineId (see hashDistinctId in + // @roo-code/telemetry), not the raw machine ID: the webview uses this value as + // its PostHog distinct ID, so the raw identifier never crosses the webview + // boundary (issue #830). machineId?: string // Live vscode.env.isTelemetryEnabled, so the webview's own PostHog client can respect // the VS Code global telemetry toggle the same way the extension-side gate does -- diff --git a/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts b/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts index 0aee40ef817..ef58608d807 100644 --- a/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts +++ b/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts @@ -41,7 +41,6 @@ vi.mock("@roo-code/core", () => ({ vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { instance: { - captureToolUsage: vi.fn(), captureConsecutiveMistakeError: vi.fn(), captureEvent: vi.fn(), }, @@ -167,8 +166,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(1) expect(mockTask.recordToolUsage).toHaveBeenCalledWith("read_file") - expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledTimes(1) - expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledWith(mockTask.taskId, "read_file") }) it("records a valid dynamic mcp_ tool name as use_mcp_tool", async () => { @@ -186,7 +183,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot) expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool") - expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledWith(mockTask.taskId, "use_mcp_tool") }) it("records a malformed mcp_ tool name as use_mcp_tool, not the raw name", async () => { @@ -358,8 +354,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(1) expect(mockTask.recordToolUsage).toHaveBeenCalledWith("use_mcp_tool") - expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledTimes(1) - expect(TelemetryService.instance.captureToolUsage).toHaveBeenCalledWith(mockTask.taskId, "use_mcp_tool") }) it("records no attempt when the MCP server is not on the mode's allow-list", async () => { @@ -401,7 +395,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { // The server is disallowed, so the call never reaches onValidated: // no success attempt is recorded for a call that was never permitted to execute. expect(mockTask.recordToolUsage).not.toHaveBeenCalled() - expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled() }) it("rejects at dispatch when use_mcp_tool is in disabledTools, without invoking the server method", async () => { @@ -466,7 +459,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { // No success attribution on rejection; a safe static failure key instead. expect(mockTask.recordToolUsage).not.toHaveBeenCalled() - expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String)) expect(mockTask.consecutiveMistakeCount).toBe(1) // The stream must not be interrupted by a validation rejection. @@ -532,7 +524,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { expect(mockHub.callTool).not.toHaveBeenCalled() expect(mockTask.recordToolUsage).not.toHaveBeenCalled() - expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String)) expect(mockTask.consecutiveMistakeCount).toBe(1) expect(mockTask.didAlreadyUseTool).toBe(false) @@ -620,7 +611,6 @@ describe("presentAssistantMessage - tool usage attribution", () => { ) expect(mockTask.recordToolUsage).not.toHaveBeenCalled() - expect(TelemetryService.instance.captureToolUsage).not.toHaveBeenCalled() expect(mockTask.recordToolError).toHaveBeenCalledWith("use_mcp_tool", expect.any(String)) expect(mockTask.consecutiveMistakeCount).toBe(1) expect(mockTask.didAlreadyUseTool).toBe(false) diff --git a/src/core/assistant-message/presentAssistantMessage.ts b/src/core/assistant-message/presentAssistantMessage.ts index 73d48b2e7c0..9d69415782e 100644 --- a/src/core/assistant-message/presentAssistantMessage.ts +++ b/src/core/assistant-message/presentAssistantMessage.ts @@ -419,7 +419,6 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request ? undefined : () => { cline.recordToolUsage("use_mcp_tool") - TelemetryService.instance.captureToolUsage(cline.taskId, "use_mcp_tool") }, }) break @@ -802,10 +801,11 @@ async function presentAssistantMessageBlock(cline: Task, policySnapshot: Request // Validation passed: record exactly one attempt at this single // central point. Individual tool handlers must not also record - // usage, or the attempt would be double-counted. + // usage, or the attempt would be double-counted. Usage reaches + // telemetry as a per-task toolsUsed breakdown on Task Completed + // (flushTelemetryInstallment), never as one event per tool call. const recordName = toTelemetryToolName(block.name, isCustomTool, stateExperiments) cline.recordToolUsage(recordName) - TelemetryService.instance.captureToolUsage(cline.taskId, recordName) // Track legacy format usage for read_file tool (for migration monitoring). // Model ids on telemetry events are non-policy labels: a live diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 542e6bb7682..bd873bbf7d4 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -85,7 +85,7 @@ import { type TaskExecutionContext, } from "../task/providerHandoff" import { aggregateTaskCostsRecursive, type AggregatedCosts } from "./aggregateTaskCosts" -import { TelemetryService } from "@roo-code/telemetry" +import { TelemetryService, hashDistinctId } from "@roo-code/telemetry" import { CloudService, getRooCodeApiUrl } from "@roo-code/cloud" import { Package } from "../../shared/package" @@ -3315,7 +3315,9 @@ export class ClineProvider } const telemetryKey = process.env.POSTHOG_API_KEY - const machineId = vscode.env.machineId + // The webview uses this value as its PostHog distinct ID, so it must be the + // salted hash: the raw machine ID never crosses the webview boundary (issue #830). + const machineId = hashDistinctId(vscode.env.machineId) const vscodeTelemetryEnabled = vscode.env.isTelemetryEnabled const mergedAllowedCommands = this.mergeAllowedCommands(allowedCommands) const mergedDeniedCommands = this.mergeDeniedCommands(deniedCommands) diff --git a/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts b/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts index dbe6c3429a1..dde3a81b6c5 100644 --- a/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.flicker-free-cancel.spec.ts @@ -106,14 +106,20 @@ vi.mock("../../../utils/path", () => ({ })) // Mock TelemetryService -vi.mock("@roo-code/telemetry", () => ({ - TelemetryService: { - instance: { - setProvider: vi.fn(), - captureTaskCreated: vi.fn(), +vi.mock("@roo-code/telemetry", async (importOriginal) => { + const actual = await importOriginal() + return { + // Keep the real hashDistinctId: getStateToPostToWebview hashes the machine ID + // before posting it to the webview (issue #830). + ...actual, + TelemetryService: { + instance: { + setProvider: vi.fn(), + captureTaskCreated: vi.fn(), + }, }, - }, -})) + } +}) // Mock CloudService vi.mock("@roo-code/cloud", () => ({ diff --git a/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts b/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts index abced7bd61e..ec8245cddb4 100644 --- a/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.lockApiConfig.spec.ts @@ -212,20 +212,26 @@ vi.mock("fs/promises", () => ({ rmdir: vi.fn().mockResolvedValue(undefined), })) -vi.mock("@roo-code/telemetry", () => ({ - TelemetryService: { - hasInstance: vi.fn().mockReturnValue(true), - createInstance: vi.fn(), - get instance() { - return { - trackEvent: vi.fn(), - trackError: vi.fn(), - setProvider: vi.fn(), - captureModeSwitch: vi.fn(), - } +vi.mock("@roo-code/telemetry", async (importOriginal) => { + const actual = await importOriginal() + return { + // Keep the real hashDistinctId: getStateToPostToWebview hashes the machine ID + // before posting it to the webview (issue #830). + ...actual, + TelemetryService: { + hasInstance: vi.fn().mockReturnValue(true), + createInstance: vi.fn(), + get instance() { + return { + trackEvent: vi.fn(), + trackError: vi.fn(), + setProvider: vi.fn(), + captureModeSwitch: vi.fn(), + } + }, }, - }, -})) + } +}) describe("ClineProvider - Lock API Config Across Modes", () => { let provider: ClineProvider diff --git a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts index 47fcfd11f0e..f73101d4eeb 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts @@ -193,20 +193,26 @@ vi.mock("../../../utils/storage", async (importOriginal) => { } }) -vi.mock("@roo-code/telemetry", () => ({ - TelemetryService: { - hasInstance: vi.fn().mockReturnValue(true), - createInstance: vi.fn(), - get instance() { - return { - trackEvent: vi.fn(), - trackError: vi.fn(), - setProvider: vi.fn(), - captureModeSwitch: vi.fn(), - } +vi.mock("@roo-code/telemetry", async (importOriginal) => { + const actual = await importOriginal() + return { + // Keep the real hashDistinctId: getStateToPostToWebview hashes the machine ID + // before posting it to the webview (issue #830). + ...actual, + TelemetryService: { + hasInstance: vi.fn().mockReturnValue(true), + createInstance: vi.fn(), + get instance() { + return { + trackEvent: vi.fn(), + trackError: vi.fn(), + setProvider: vi.fn(), + captureModeSwitch: vi.fn(), + } + }, }, - }, -})) + } +}) describe("ClineProvider - Sticky Mode", () => { let provider: ClineProvider diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 60b5cde8fd7..53930945d9e 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -195,20 +195,26 @@ vi.mock("../../../utils/storage", async (importOriginal) => { } }) -vi.mock("@roo-code/telemetry", () => ({ - TelemetryService: { - hasInstance: vi.fn().mockReturnValue(true), - createInstance: vi.fn(), - get instance() { - return { - trackEvent: vi.fn(), - trackError: vi.fn(), - setProvider: vi.fn(), - captureModeSwitch: vi.fn(), - } +vi.mock("@roo-code/telemetry", async (importOriginal) => { + const actual = await importOriginal() + return { + // Keep the real hashDistinctId: getStateToPostToWebview hashes the machine ID + // before posting it to the webview (issue #830). + ...actual, + TelemetryService: { + hasInstance: vi.fn().mockReturnValue(true), + createInstance: vi.fn(), + get instance() { + return { + trackEvent: vi.fn(), + trackError: vi.fn(), + setProvider: vi.fn(), + captureModeSwitch: vi.fn(), + } + }, }, - }, -})) + } +}) describe("ClineProvider - Sticky Provider Profile", () => { let provider: ClineProvider diff --git a/src/services/code-index/constants/index.ts b/src/services/code-index/constants/index.ts index 6f0e0fe7e62..fe1fa8e6e1a 100644 --- a/src/services/code-index/constants/index.ts +++ b/src/services/code-index/constants/index.ts @@ -19,6 +19,7 @@ export const MAX_LIST_FILES_LIMIT_CODE_INDEX = 50_000 export const BATCH_SEGMENT_THRESHOLD = 60 // Number of code segments to batch for embeddings/upserts export const MAX_BATCH_RETRIES = 3 export const INITIAL_RETRY_DELAY_MS = 500 +export const CIRCUIT_BREAKER_BATCH_THRESHOLD = 3 // Consecutive failed batches before the file watcher's circuit breaker opens export const PARSING_CONCURRENCY = 10 export const MAX_PENDING_BATCHES = 20 // Maximum number of batches to accumulate before waiting diff --git a/src/services/code-index/processors/__tests__/file-watcher.spec.ts b/src/services/code-index/processors/__tests__/file-watcher.spec.ts index 736cca0806b..6575c698809 100644 --- a/src/services/code-index/processors/__tests__/file-watcher.spec.ts +++ b/src/services/code-index/processors/__tests__/file-watcher.spec.ts @@ -4,6 +4,7 @@ import * as vscode from "vscode" import { FileWatcher } from "../file-watcher" import { FilePreparation } from "../file-preparation" +import type { FileProcessingResult } from "../../interfaces" import { clearAllMocks } from "../../../../test-utils/reset" @@ -358,6 +359,134 @@ describe("FileWatcher", () => { }) }) + describe("per-workspace circuit breaker", () => { + /** Fire one create event, flush the debounce window, and wait for the batch to finish. */ + const runBatch = async (filePath: string) => { + const batchPromise = waitForNextBatch() + await mockOnDidCreate({ fsPath: filePath }) + await vi.advanceTimersByTimeAsync(500) + return batchPromise + } + + it("stops consuming file-system events after three consecutive failed batches", async () => { + await fileWatcher.initialize() + mockEmbedder.createEmbeddings.mockRejectedValue(new Error("embedder misconfigured")) + + // Three consecutive all-fail batches trip the breaker on the third. + for (let i = 0; i < 3; i++) { + const summary = await runBatch(`/mock/workspace/src/broken-${i}.ts`) + expect(summary.processedFiles).toHaveLength(1) + expect(summary.processedFiles[0].status).toBe("local_error") + } + expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(3) + + // Further events are dropped: no batch starts and no embedder call is made. + const started = vi.fn() + fileWatcher.onDidStartBatchProcessing(started) + await mockOnDidCreate({ fsPath: "/mock/workspace/src/after-breaker.ts" }) + await vi.advanceTimersByTimeAsync(500) + expect(started).not.toHaveBeenCalled() + expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(3) + }) + + it("resets the failure counter when a batch succeeds between failures", async () => { + await fileWatcher.initialize() + + const fail = () => mockEmbedder.createEmbeddings.mockRejectedValue(new Error("down")) + const succeed = () => mockEmbedder.createEmbeddings.mockResolvedValue({ embeddings: [[0.1, 0.2, 0.3]] }) + + // Two consecutive failures... + fail() + await runBatch("/mock/workspace/src/fail-1.ts") + await runBatch("/mock/workspace/src/fail-2.ts") + + // ...then a success resets the counter. + succeed() + await runBatch("/mock/workspace/src/ok-1.ts") + + // Only two failures since the reset: the breaker must stay closed. + fail() + await runBatch("/mock/workspace/src/fail-3.ts") + await runBatch("/mock/workspace/src/fail-4.ts") + + const started = vi.fn() + fileWatcher.onDidStartBatchProcessing(started) + const batchPromise = waitForNextBatch() + await mockOnDidCreate({ fsPath: "/mock/workspace/src/fail-5.ts" }) + await vi.advanceTimersByTimeAsync(500) + await batchPromise + expect(started).toHaveBeenCalledTimes(1) + + // That third consecutive failure opens the breaker; the next event is dropped. + await mockOnDidCreate({ fsPath: "/mock/workspace/src/after-breaker.ts" }) + await vi.advanceTimersByTimeAsync(500) + expect(started).toHaveBeenCalledTimes(1) + }) + + it("counts a batch whose upsert exhausts retries as a failed batch", async () => { + await fileWatcher.initialize() + mockVectorStore.upsertPoints.mockRejectedValue(new Error("qdrant down")) + + // Each batch exhausts MAX_BATCH_RETRIES (3 attempts) before failing. + for (let i = 0; i < 3; i++) { + const batchPromise = waitForNextBatch() + await mockOnDidCreate({ fsPath: `/mock/workspace/src/upsert-fail-${i}.ts` }) + await vi.advanceTimersByTimeAsync(10_000) + const summary = await batchPromise + expect(summary.batchError).toBeDefined() + } + expect(mockVectorStore.upsertPoints).toHaveBeenCalledTimes(9) + + // Breaker is open: further events produce no upsert attempts at all. + const upsertCalls = mockVectorStore.upsertPoints.mock.calls.length + await mockOnDidCreate({ fsPath: "/mock/workspace/src/after-breaker.ts" }) + await vi.advanceTimersByTimeAsync(10_000) + expect(mockVectorStore.upsertPoints.mock.calls.length).toBe(upsertCalls) + }) + + it("does not open the breaker when only isolated files in a batch fail", async () => { + await fileWatcher.initialize() + + const defaultReadFile = () => Buffer.from("test content") + vi.mocked(vscode.workspace.fs.readFile).mockImplementation(async (uri: vscode.Uri) => { + if (uri.fsPath.includes("bad")) { + throw new Error("EACCES: unreadable file") + } + return defaultReadFile() + }) + + try { + // Five batches in a row where exactly one of two files fails must never + // count as a consecutive failure. + for (let i = 0; i < 5; i++) { + const batchPromise = waitForNextBatch() + await mockOnDidCreate({ fsPath: `/mock/workspace/src/ok-${i}.ts` }) + await mockOnDidCreate({ fsPath: `/mock/workspace/src/bad-${i}.ts` }) + await vi.advanceTimersByTimeAsync(500) + const summary = await batchPromise + expect( + summary.processedFiles.some((result: FileProcessingResult) => result.status === "success"), + ).toBe(true) + expect( + summary.processedFiles.some((result: FileProcessingResult) => result.status === "local_error"), + ).toBe(true) + } + + // Breaker still closed: the next batch runs normally. + const started = vi.fn() + fileWatcher.onDidStartBatchProcessing(started) + const batchPromise = waitForNextBatch() + await mockOnDidCreate({ fsPath: "/mock/workspace/src/still-ok.ts" }) + await vi.advanceTimersByTimeAsync(500) + await batchPromise + expect(started).toHaveBeenCalledTimes(1) + } finally { + vi.mocked(vscode.workspace.fs.readFile).mockReset() + vi.mocked(vscode.workspace.fs.readFile).mockResolvedValue(defaultReadFile()) + } + }) + }) + describe("dispose", () => { it("should dispose of the watcher when disposed", async () => { await fileWatcher.initialize() diff --git a/src/services/code-index/processors/file-watcher.ts b/src/services/code-index/processors/file-watcher.ts index 0a0514a891a..00e82b15c36 100644 --- a/src/services/code-index/processors/file-watcher.ts +++ b/src/services/code-index/processors/file-watcher.ts @@ -1,5 +1,10 @@ import * as vscode from "vscode" -import { BATCH_SEGMENT_THRESHOLD, MAX_BATCH_RETRIES, INITIAL_RETRY_DELAY_MS } from "../constants" +import { + BATCH_SEGMENT_THRESHOLD, + MAX_BATCH_RETRIES, + INITIAL_RETRY_DELAY_MS, + CIRCUIT_BREAKER_BATCH_THRESHOLD, +} from "../constants" import { RooIgnoreController } from "../../../core/ignore/RooIgnoreController" import { Ignore } from "ignore" import { scannerExtensions } from "../shared/supported-extensions" @@ -33,6 +38,16 @@ export class FileWatcher implements IFileWatcher { private readonly FILE_PROCESSING_CONCURRENCY_LIMIT = 10 private readonly batchSegmentThreshold: number + // Per-workspace circuit breaker. A permanently broken embedder or vector store + // configuration used to re-trigger the failing pipeline on every file-system + // event with no backoff, flooding CODE_INDEX_ERROR telemetry (issue #830). + // After CIRCUIT_BREAKER_BATCH_THRESHOLD consecutive failed batches the watcher + // stops consuming events entirely until it is recreated — which happens when + // the embedder/vector-store configuration changes (CodeIndexManager + // _recreateServices) or the workspace re-initializes the watcher. + private consecutiveFailedBatches = 0 + private circuitBreakerOpen = false + private readonly _onDidStartBatchProcessing = new vscode.EventEmitter() private readonly _onBatchProgressUpdate = new vscode.EventEmitter<{ processedInBatch: number @@ -107,6 +122,10 @@ export class FileWatcher implements IFileWatcher { * Initializes the file watcher */ async initialize(): Promise { + // A fresh watcher subscription starts with a closed circuit breaker. + this.consecutiveFailedBatches = 0 + this.circuitBreakerOpen = false + // Create file watcher const filePattern = new vscode.RelativePattern( this.workspacePath, @@ -165,6 +184,12 @@ export class FileWatcher implements IFileWatcher { * Schedules batch processing with debounce */ private scheduleBatchProcessing(): void { + if (this.circuitBreakerOpen) { + // Circuit breaker is open: drop pending events instead of re-triggering + // a permanently failing embedder/vector-store pipeline. + this.accumulatedEvents.clear() + return + } if (this.batchProcessDebounceTimer) { clearTimeout(this.batchProcessDebounceTimer) } @@ -175,6 +200,12 @@ export class FileWatcher implements IFileWatcher { * Triggers processing of accumulated events */ private async triggerBatchProcessing(): Promise { + if (this.circuitBreakerOpen) { + // A debounce timer scheduled before the breaker opened must not flush + // the events it captured. + this.accumulatedEvents.clear() + return + } if (this.accumulatedEvents.size === 0) { return } @@ -483,6 +514,34 @@ export class FileWatcher implements IFileWatcher { overallBatchError, ) + // Circuit-breaker bookkeeping. A batch counts as failed when the batch-level + // pipeline broke (deletion/upsert errors) or every file attempted in the batch + // failed (e.g. a broken embedder rejecting every createEmbeddings call). + // Isolated per-file failures do not count, so one unreadable file cannot trip + // the breaker for healthy indexing. + const resultsByPath = new Map(batchResults.map((result) => [result.path, result])) + const allAttemptedFilesFailed = + filesToUpsertDetails.length > 0 && + filesToUpsertDetails.every((detail) => { + const status = resultsByPath.get(detail.path)?.status + return status === "error" || status === "local_error" + }) + + if (overallBatchError !== undefined || allAttemptedFilesFailed) { + this.consecutiveFailedBatches++ + } else { + this.consecutiveFailedBatches = 0 + } + + if (!this.circuitBreakerOpen && this.consecutiveFailedBatches >= CIRCUIT_BREAKER_BATCH_THRESHOLD) { + this.circuitBreakerOpen = true + this.accumulatedEvents.clear() + console.error( + `[FileWatcher] Circuit breaker opened after ${this.consecutiveFailedBatches} consecutive failed batches; ` + + `dropping further file-system events for this workspace until the embedder or vector store configuration changes.`, + ) + } + // Finalize this._onDidFinishBatchProcessing.fire({ processedFiles: batchResults, From d4b2cccdc0ef8058e538db566281e48625be37c5 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Fri, 20 Nov 2026 04:29:57 +0000 Subject: [PATCH 2/7] fix(telemetry): surface watcher breaker failures and add SDD coverage --- docs/architecture/tla/CodeIndexWatcher.tla | 36 ++++++ .../tla/CodeIndexWatcherMC.Silent.cfg | 7 ++ .../tla/CodeIndexWatcherMC.Unguarded.cfg | 7 ++ docs/architecture/tla/CodeIndexWatcherMC.cfg | 7 ++ docs/architecture/tla/CodeIndexWatcherMC.tla | 5 + docs/architecture/tla/TelemetryBoundary.tla | 28 +++++ .../tla/TelemetryBoundaryMC.PerCall.cfg | 8 ++ .../tla/TelemetryBoundaryMC.RawHost.cfg | 8 ++ .../tla/TelemetryBoundaryMC.RawWebview.cfg | 8 ++ docs/architecture/tla/TelemetryBoundaryMC.cfg | 8 ++ docs/architecture/tla/TelemetryBoundaryMC.tla | 5 + .../__tests__/distinct-id.property.test.ts | 50 ++++++++ ...tantMessage-tool-usage-attribution.spec.ts | 24 ++++ .../ClineProvider.sticky-profile.spec.ts | 21 ++++ .../watcher-boundary.property.spec.ts | 109 ++++++++++++++++++ .../code-index/interfaces/file-processor.ts | 2 + src/services/code-index/orchestrator.ts | 11 ++ .../code-index/processors/file-watcher.ts | 1 + 18 files changed, 345 insertions(+) create mode 100644 docs/architecture/tla/CodeIndexWatcher.tla create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.tla create mode 100644 docs/architecture/tla/TelemetryBoundary.tla create mode 100644 docs/architecture/tla/TelemetryBoundaryMC.PerCall.cfg create mode 100644 docs/architecture/tla/TelemetryBoundaryMC.RawHost.cfg create mode 100644 docs/architecture/tla/TelemetryBoundaryMC.RawWebview.cfg create mode 100644 docs/architecture/tla/TelemetryBoundaryMC.cfg create mode 100644 docs/architecture/tla/TelemetryBoundaryMC.tla create mode 100644 packages/telemetry/src/__tests__/distinct-id.property.test.ts create mode 100644 src/services/code-index/__tests__/watcher-boundary.property.spec.ts diff --git a/docs/architecture/tla/CodeIndexWatcher.tla b/docs/architecture/tla/CodeIndexWatcher.tla new file mode 100644 index 00000000000..18eee8b7f3b --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcher.tla @@ -0,0 +1,36 @@ +---- MODULE CodeIndexWatcher ---- +\* Sources: FileWatcher.scheduleBatchProcessing and triggerBatchProcessing; batch results are an oracle. +\* Sinks: processBatch finish/progress events and CodeIndexOrchestrator._startWatcher listeners. +\* Failure: work starts after the breaker trips. Invariant: NoStartAfterTrip. +\* Review ratchet: a tripped watcher must show Error. Invariant: TripIsVisible. +\* PR 2329, https://github.com/Zoo-Code-Org/Zoo-Code/pull/2329#discussion_r4485895183: added. +\* Expect: the old summary leaves Indexed on trip. Late progress must not clear Error. +\* Initial rules were recorded before review. The prior rebase exposed the fix summary: this spec is retrospective. +\* Scope: sequential batch results and arbitrary progress events. Providers and file results are oracles. +\* Gap: disposal and overlapping work are not modeled. No claim about cancellation or persistence. +\* Result: fixed passes (4 states). Silent fails (4 states); Unguarded fails (5 states). No new finding. +\* Replay: watcher-boundary.property.spec.ts failed on 20 of 64 histories before the summary fix; all 64 now pass. +\* Sabotage replay: silent summary, removed admission guards, and removed progress latch each fail test assertions. +\* Initial disposal rule is a gap in this model; event-emitter disposal needs a separate cancellation model. +\* Cost: two small model files, three configs, 64 test histories. Agent time is not measured; each TLC run took under 1 second. +\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 0, added 1, gap 0. +EXTENDS Naturals +CONSTANTS Threshold, Guard, Visible +VARIABLES failures, open, ui, badStart +vars == <> +Init == /\ failures = 0 /\ open = FALSE /\ ui = "Indexed" /\ badStart = FALSE +Batch(failed) == + /\ (~open \/ ~Guard) + /\ failures' = IF failed THEN IF failures < Threshold THEN failures + 1 ELSE Threshold ELSE 0 + /\ open' = (open \/ failures' >= Threshold) + /\ ui' = IF Visible /\ open' THEN "Error" ELSE "Indexed" + /\ badStart' = (badStart \/ open) +Progress == + /\ ui' = IF Visible /\ open THEN ui ELSE "Indexed" + /\ UNCHANGED <> +Restart == /\ failures' = 0 /\ open' = FALSE /\ ui' = "Indexed" /\ badStart' = FALSE +Next == Batch(TRUE) \/ Batch(FALSE) \/ Progress \/ Restart +Spec == Init /\ [][Next]_vars +NoStartAfterTrip == ~badStart +TripIsVisible == open => ui = "Error" +==== diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg new file mode 100644 index 00000000000..e5a726d9eed --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + Visible = FALSE +INVARIANTS NoStartAfterTrip TripIsVisible +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg new file mode 100644 index 00000000000..14af485a62d --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = FALSE + Visible = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.cfg b/docs/architecture/tla/CodeIndexWatcherMC.cfg new file mode 100644 index 00000000000..f2560f67134 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + Visible = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.tla b/docs/architecture/tla/CodeIndexWatcherMC.tla new file mode 100644 index 00000000000..e642d071491 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.tla @@ -0,0 +1,5 @@ +---- MODULE CodeIndexWatcherMC ---- +\* Small domains for the local TLC gate. +EXTENDS CodeIndexWatcher +BatchLimit == 3 +==== diff --git a/docs/architecture/tla/TelemetryBoundary.tla b/docs/architecture/tla/TelemetryBoundary.tla new file mode 100644 index 00000000000..44d3a4d7ee4 --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundary.tla @@ -0,0 +1,28 @@ +---- MODULE TelemetryBoundary ---- +\* Source: vscode.env.machineId; sinks: PostHogTelemetryClient and ClineProvider.getStateToPostToWebview. +\* Source: validated tool calls in presentAssistantMessage; sink: telemetry events and task usage counts. +\* Failures: raw IDs reach a sink; per-call events duplicate task usage. Invariants: HashedSinks, AggregateOnly. +\* Expected: the two identity sinks use the same projection; tool calls update only the aggregate. +\* Hash is an oracle with raw and pseudonymous classes. This does not model SHA-256 or payload privacy. +\* Initial rules preceded review. The prior rebase exposed the fix summary: this spec is retrospective. +\* Result: fixed passes (12 states). RawHost fails (2); RawWebview fails (3); PerCall fails (4). Null result: no new bug. +\* Replay: raw host and webview IDs, and an added per-call event each fail assertions in the real-code tests. +\* Tests: distinct-id.property.test.ts checks 36 IDs at capture and captureException; sticky-profile checks the same domain. +\* Tests: tool-usage-attribution checks four calls for static and MCP tools, aggregate counts, and no per-call event. +\* Scope excludes task completion delivery, removed unused APIs, policy text, other payload fields, and cloud sync. +\* Cost: two small model files, four configs, 36 IDs and two call sequences. Agent time is not measured; TLC runs took under 1 second. +\* Gate: TLA_JAR= ./check.sh TelemetryBoundaryMC. Review counts: covered 0, added 0, gap 0. +EXTENDS Naturals +CONSTANTS HashHost, HashWebview, PerCall, MaxCalls +VARIABLES host, webview, calls, aggregate, events +vars == <> +Init == /\ host = "none" /\ webview = "none" /\ calls = 0 /\ aggregate = 0 /\ events = 0 +Host == /\ host' = (IF HashHost THEN "hash" ELSE "raw") /\ UNCHANGED <> +Webview == /\ webview' = (IF HashWebview THEN "hash" ELSE "raw") /\ UNCHANGED <> +Tool == /\ calls < MaxCalls /\ calls' = calls + 1 /\ aggregate' = aggregate + 1 + /\ events' = (IF PerCall THEN events + 1 ELSE events) /\ UNCHANGED <> +Next == Host \/ Webview \/ Tool +Spec == Init /\ [][Next]_vars +HashedSinks == host # "raw" /\ webview # "raw" /\ (host # "none" /\ webview # "none" => host = webview) +AggregateOnly == events = 0 /\ aggregate = calls +==== diff --git a/docs/architecture/tla/TelemetryBoundaryMC.PerCall.cfg b/docs/architecture/tla/TelemetryBoundaryMC.PerCall.cfg new file mode 100644 index 00000000000..c5a63ee78a7 --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundaryMC.PerCall.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + MaxCalls <- CallLimit + HashHost = TRUE + HashWebview = TRUE + PerCall = TRUE +INVARIANTS HashedSinks AggregateOnly +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TelemetryBoundaryMC.RawHost.cfg b/docs/architecture/tla/TelemetryBoundaryMC.RawHost.cfg new file mode 100644 index 00000000000..87aa7250163 --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundaryMC.RawHost.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + MaxCalls <- CallLimit + HashHost = FALSE + HashWebview = TRUE + PerCall = FALSE +INVARIANTS HashedSinks AggregateOnly +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TelemetryBoundaryMC.RawWebview.cfg b/docs/architecture/tla/TelemetryBoundaryMC.RawWebview.cfg new file mode 100644 index 00000000000..5eb5f9dfb19 --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundaryMC.RawWebview.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + MaxCalls <- CallLimit + HashHost = TRUE + HashWebview = FALSE + PerCall = FALSE +INVARIANTS HashedSinks AggregateOnly +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TelemetryBoundaryMC.cfg b/docs/architecture/tla/TelemetryBoundaryMC.cfg new file mode 100644 index 00000000000..8374db2c840 --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundaryMC.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + MaxCalls <- CallLimit + HashHost = TRUE + HashWebview = TRUE + PerCall = FALSE +INVARIANTS HashedSinks AggregateOnly +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TelemetryBoundaryMC.tla b/docs/architecture/tla/TelemetryBoundaryMC.tla new file mode 100644 index 00000000000..5c2ceb181dc --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundaryMC.tla @@ -0,0 +1,5 @@ +---- MODULE TelemetryBoundaryMC ---- +\* Small domains for the local TLC gate. +EXTENDS TelemetryBoundary +CallLimit == 2 +==== diff --git a/packages/telemetry/src/__tests__/distinct-id.property.test.ts b/packages/telemetry/src/__tests__/distinct-id.property.test.ts new file mode 100644 index 00000000000..5937ebe83e7 --- /dev/null +++ b/packages/telemetry/src/__tests__/distinct-id.property.test.ts @@ -0,0 +1,50 @@ +import { createHash } from "node:crypto" +import { describe, expect, it, vi } from "vitest" +import * as vscode from "vscode" +import { TelemetryEventName } from "@roo-code/types" +import { PostHogTelemetryClient } from "../PostHogTelemetryClient" +import { hashDistinctId } from "../distinct-id" + +const sink = vi.hoisted(() => ({ capture: vi.fn(), captureException: vi.fn(), optIn: vi.fn(), optOut: vi.fn() })) +vi.mock("posthog-node", () => ({ + PostHog: class { + capture = sink.capture + captureException = sink.captureException + optIn = sink.optIn + optOut = sink.optOut + }, +})) +vi.mock("vscode", () => ({ + env: { + get machineId() { + return "test-machine-id" + }, + }, + workspace: { getConfiguration: () => ({ get: () => "all" }) }, +})) + +// Device IDs include UUIDs, unavailable-ID sentinels, Unicode, and generated opaque strings. +const ids = [ + "", + "someValue.machineId", + "01234567-89ab-cdef-0123-456789abcdef", + "机器-id", + ...Array.from({ length: 32 }, (_, i) => "device-" + i.toString(16).repeat(i + 1)), +] + +describe("analytics identity boundary", () => { + it.each(ids)("projects %j at both host sinks", async (raw) => { + vi.clearAllMocks() + vi.spyOn(vscode.env, "machineId", "get").mockReturnValue(raw) + const client = new PostHogTelemetryClient() + client.updateTelemetryState(true) + await client.capture({ event: TelemetryEventName.TASK_CREATED }) + await client.captureException(new Error("Unexpected index failure")) + const expected = createHash("sha256").update(`zoo-code-telemetry-distinct-id-v1:${raw}`).digest("hex") + expect(hashDistinctId(raw)).toBe(expected) + expect(hashDistinctId(raw)).toBe(hashDistinctId(raw)) + expect(expected).not.toBe(raw) + expect(sink.capture).toHaveBeenCalledWith(expect.objectContaining({ distinctId: expected })) + expect(sink.captureException).toHaveBeenCalledWith(expect.any(Error), expected, expect.anything()) + }) +}) diff --git a/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts b/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts index ef58608d807..5366b094ca7 100644 --- a/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts +++ b/src/core/assistant-message/__tests__/presentAssistantMessage-tool-usage-attribution.spec.ts @@ -150,6 +150,30 @@ describe("presentAssistantMessage - tool usage attribution", () => { }) }) + it.each(["read_file", "mcp_my_server_do_thing"])( + "records aggregate usage without per-call events for %s", + async (name) => { + for (let count = 1; count <= 4; count++) { + mockTask.didAlreadyUseTool = false + mockTask.currentStreamingContentIndex = 0 + mockTask.assistantMessageContent = [ + { + type: "tool_use", + id: `call_${count}`, + name, + params: { path: "test.txt" }, + nativeArgs: { path: "test.txt" }, + partial: false, + }, + ] + // The double supplies the presenter fields and callbacks declared in MockTask. + await presentAssistantMessage(mockTask as unknown as Task, baseSnapshot) + expect(mockTask.recordToolUsage).toHaveBeenCalledTimes(count) + expect(TelemetryService.instance.captureEvent).not.toHaveBeenCalled() + } + }, + ) + it("records exactly one attempt for a normal static tool", async () => { mockTask.assistantMessageContent = [ { diff --git a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts index 53930945d9e..9b5996a6ea1 100644 --- a/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto" import { WebviewFocusTracker } from "../WebviewFocusTracker" // npx vitest run core/webview/__tests__/ClineProvider.sticky-profile.spec.ts @@ -48,6 +49,9 @@ vi.mock("vscode", () => ({ onDidCloseTextDocument: vi.fn(() => ({ dispose: vi.fn() })), }, env: { + get machineId() { + return "test-machine-id" + }, uriScheme: "vscode", language: "en", appName: "Visual Studio Code", @@ -338,6 +342,23 @@ describe("ClineProvider - Sticky Provider Profile", () => { } }) + it("posts only the hashed identity for generated machine IDs", async () => { + const ids = [ + "", + "someValue.machineId", + "01234567-89ab-cdef-0123-456789abcdef", + "机器-id", + ...Array.from({ length: 32 }, (_, i) => "device-" + i.toString(16).repeat(i + 1)), + ] + for (const raw of ids) { + vi.spyOn(vscode.env, "machineId", "get").mockReturnValue(raw) + const state = await provider.getStateToPostToWebview() + const expected = createHash("sha256").update(`zoo-code-telemetry-distinct-id-v1:${raw}`).digest("hex") + expect(state.machineId).toBe(expected) + expect(state.machineId).not.toBe(raw) + } + }) + describe("activateProviderProfile", () => { beforeEach(async () => { await provider.resolveWebviewView(mockWebviewView) diff --git a/src/services/code-index/__tests__/watcher-boundary.property.spec.ts b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts new file mode 100644 index 00000000000..f57b7f82040 --- /dev/null +++ b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts @@ -0,0 +1,109 @@ +import { describe, expect, it, vi } from "vitest" +import * as vscode from "vscode" +import { FileWatcher } from "../processors/file-watcher" +import { CodeIndexOrchestrator } from "../orchestrator" +import { CodeIndexStateManager } from "../state-manager" +import type { CodeIndexConfigManager } from "../config-manager" +import type { CacheManager } from "../cache-manager" +import type { DirectoryScanner } from "../processors" +import type { IVectorStore } from "../interfaces" +import { makeUri } from "../../../test-utils/vscode" + +vi.mock("../processors/parser", () => ({ codeParser: {} })) +vi.mock("../processors/file-preparation", () => ({ FilePreparation: class {} })) +vi.mock("../../../core/ignore/RooIgnoreController", () => ({ RooIgnoreController: class {} })) +vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { instance: { captureEvent: vi.fn() } } })) +vi.mock("vscode", () => { + class EventEmitter { + private listeners = new Set<(value: T) => unknown>() + event = (listener: (value: T) => unknown) => { + this.listeners.add(listener) + return { + dispose: () => { + this.listeners.delete(listener) + }, + } + } + fire(value: T) { + for (const listener of this.listeners) listener(value) + } + dispose() { + this.listeners.clear() + } + } + return { + EventEmitter, + RelativePattern: class {}, + workspace: { + createFileSystemWatcher: () => ({ + onDidCreate: vi.fn(), + onDidChange: vi.fn(), + onDidDelete: vi.fn(), + dispose: vi.fn(), + }), + }, + } +}) + +function setup() { + // These doubles provide only the members used by watcher startup and the no-upsert batches below. + const config = { isFeatureConfigured: true } as CodeIndexConfigManager + const cache = {} as CacheManager + const store = {} as IVectorStore + const scanner = {} as DirectoryScanner + const context = {} as vscode.ExtensionContext + const watcher = new FileWatcher("/workspace", context, cache, undefined, store, undefined, undefined, 60) + const state = new CodeIndexStateManager() + const orchestrator = new CodeIndexOrchestrator(config, state, "/workspace", cache, store, scanner, watcher) + const prepare = vi.spyOn(watcher, "processFile") + return { watcher, state, orchestrator, prepare } +} + +// Exhaust all success/failure histories up to six batches; the model's provider result is an oracle. +const histories = Array.from({ length: 64 }, (_, mask) => + Array.from({ length: 6 }, (_, bit) => Boolean(mask & (1 << bit))), +) + +describe("watcher source-to-state properties", () => { + it.each(histories.map((history) => [history] as const))( + "keeps trips visible and rejects later work for %j", + async (history) => { + const { watcher, state, orchestrator, prepare } = setup() + await orchestrator["_startWatcher"]() + let failures = 0 + let open = false + try { + for (const [index, failed] of history.entries()) { + prepare.mockResolvedValue({ + path: `/workspace/${index}.ts`, + status: failed ? "local_error" : "skipped", + }) + const before = prepare.mock.calls.length + watcher["accumulatedEvents"].set(`/workspace/${index}.ts`, { + uri: makeUri(`/workspace/${index}.ts`), + type: "create", + }) + await watcher["triggerBatchProcessing"]() + expect(prepare.mock.calls.length - before).toBe(open ? 0 : 1) + if (!open) failures = failed ? failures + 1 : 0 + open ||= failures >= 3 + expect(state.state).toBe(open ? "Error" : "Indexed") + if (open) expect(state.getCurrentStatus().message).toMatch(/restart|re-run|configuration/i) + } + // A new subscription resets both the producer and consumer breaker state. + await orchestrator["_startWatcher"]() + prepare.mockResolvedValue({ path: "/workspace/recovered.ts", status: "skipped" }) + watcher["accumulatedEvents"].set("/workspace/recovered.ts", { + uri: makeUri("/workspace/recovered.ts"), + type: "create", + }) + const before = prepare.mock.calls.length + await watcher["triggerBatchProcessing"]() + expect(prepare.mock.calls.length).toBe(before + 1) + expect(state.state).toBe("Indexed") + } finally { + orchestrator.stopWatcher() + } + }, + ) +}) diff --git a/src/services/code-index/interfaces/file-processor.ts b/src/services/code-index/interfaces/file-processor.ts index 8ecdc518c8d..53c0412eb51 100644 --- a/src/services/code-index/interfaces/file-processor.ts +++ b/src/services/code-index/interfaces/file-processor.ts @@ -86,6 +86,8 @@ export interface IFileWatcher extends vscode.Disposable { } export interface BatchProcessingSummary { + /** True when this watcher has stopped accepting file events after repeated failures. */ + circuitBreakerOpen?: boolean /** All files attempted in the batch, including their final status. */ processedFiles: FileProcessingResult[] /** Optional error if the entire batch operation failed (e.g., database connection issue). */ diff --git a/src/services/code-index/orchestrator.ts b/src/services/code-index/orchestrator.ts index 445db2364ed..98f1cae1505 100644 --- a/src/services/code-index/orchestrator.ts +++ b/src/services/code-index/orchestrator.ts @@ -44,9 +44,13 @@ export class CodeIndexOrchestrator { try { await this.fileWatcher.initialize() + let circuitBreakerOpen = false + this._fileWatcherSubscriptions = [ this.fileWatcher.onDidStartBatchProcessing((_filePaths: string[]) => {}), this.fileWatcher.onBatchProgressUpdate(({ processedInBatch, totalInBatch, currentFile }) => { + // Final progress can arrive after the trip summary. Keep the failure visible. + if (circuitBreakerOpen) return if (totalInBatch > 0 && this.stateManager.state !== "Indexing") { this.stateManager.setSystemState("Indexing", "Processing file changes...") } @@ -69,6 +73,13 @@ export class CodeIndexOrchestrator { } }), this.fileWatcher.onDidFinishBatchProcessing((summary: BatchProcessingSummary) => { + if (summary.circuitBreakerOpen) { + circuitBreakerOpen = true + this.stateManager.setSystemState( + "Error", + "File watching stopped after repeated indexing failures. Check the embedder or vector store configuration, then restart indexing.", + ) + } if (summary.batchError) { console.error(`[CodeIndexOrchestrator] Batch processing failed:`, summary.batchError) } diff --git a/src/services/code-index/processors/file-watcher.ts b/src/services/code-index/processors/file-watcher.ts index 00e82b15c36..5c8b8c23fb4 100644 --- a/src/services/code-index/processors/file-watcher.ts +++ b/src/services/code-index/processors/file-watcher.ts @@ -546,6 +546,7 @@ export class FileWatcher implements IFileWatcher { this._onDidFinishBatchProcessing.fire({ processedFiles: batchResults, batchError: overallBatchError, + circuitBreakerOpen: this.circuitBreakerOpen, }) this._onBatchProgressUpdate.fire({ processedInBatch: totalFilesInBatch, From 35bf2b216a79bdc9eea409a1bc3912f3ce2f8d4f Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sat, 21 Nov 2026 16:03:02 +0000 Subject: [PATCH 3/7] fix(code-index): dispose watcher before error recovery clears services --- docs/architecture/tla/CodeIndexWatcher.tla | 28 ++++++++++++------- .../tla/CodeIndexWatcherMC.Leaked.cfg | 8 ++++++ .../tla/CodeIndexWatcherMC.Silent.cfg | 3 +- .../tla/CodeIndexWatcherMC.Unguarded.cfg | 3 +- docs/architecture/tla/CodeIndexWatcherMC.cfg | 3 +- .../code-index/__tests__/manager.spec.ts | 19 +++++++++++++ src/services/code-index/manager.ts | 2 ++ 7 files changed, 53 insertions(+), 13 deletions(-) create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg diff --git a/docs/architecture/tla/CodeIndexWatcher.tla b/docs/architecture/tla/CodeIndexWatcher.tla index 18eee8b7f3b..347b7c674c4 100644 --- a/docs/architecture/tla/CodeIndexWatcher.tla +++ b/docs/architecture/tla/CodeIndexWatcher.tla @@ -7,30 +7,38 @@ \* Expect: the old summary leaves Indexed on trip. Late progress must not clear Error. \* Initial rules were recorded before review. The prior rebase exposed the fix summary: this spec is retrospective. \* Scope: sequential batch results and arbitrary progress events. Providers and file results are oracles. -\* Gap: disposal and overlapping work are not modeled. No claim about cancellation or persistence. -\* Result: fixed passes (4 states). Silent fails (4 states); Unguarded fails (5 states). No new finding. +\* Recovery source: CodeIndexManager.recoverFromError; sink: CodeIndexOrchestrator.stopWatcher. +\* Failure: recovery loses a live watcher. Invariant: RecoveryDisposes. +\* Expect: recovery without disposal leaks after a trip. Overlapping work and cancellation remain outside scope. +\* PR 2329, https://github.com/Zoo-Code-Org/Zoo-Code/pull/2329#discussion_r4638535661: added. +\* Result: fixed passes (4 states). Silent fails (4 states); Unguarded fails (5 states). Leaked fails (5 states). No new finding. \* Replay: watcher-boundary.property.spec.ts failed on 20 of 64 histories before the summary fix; all 64 now pass. \* Sabotage replay: silent summary, removed admission guards, and removed progress latch each fail test assertions. -\* Initial disposal rule is a gap in this model; event-emitter disposal needs a separate cancellation model. -\* Cost: two small model files, three configs, 64 test histories. Agent time is not measured; each TLC run took under 1 second. -\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 0, added 1, gap 0. +\* Recovery replay: manager.spec.ts failed for 1, 2, and 4 recoveries before the fix; all pass with disposal. +\* Null result: the recovery rule reproduces the review finding and finds no additional failure. +\* Scope: disposal is an oracle. Tests check the call before the manager clears the owner. +\* Cost: two small model files, four configs, 64 batch histories and three recovery counts. Agent time is not measured; each TLC run took under 1 second. +\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 0, added 2, gap 0. EXTENDS Naturals -CONSTANTS Threshold, Guard, Visible -VARIABLES failures, open, ui, badStart -vars == <> -Init == /\ failures = 0 /\ open = FALSE /\ ui = "Indexed" /\ badStart = FALSE +CONSTANTS Threshold, Guard, Visible, DisposeOnRecovery +VARIABLES failures, open, ui, badStart, leaked +vars == <> +Init == /\ failures = 0 /\ open = FALSE /\ ui = "Indexed" /\ badStart = FALSE /\ leaked = FALSE Batch(failed) == /\ (~open \/ ~Guard) /\ failures' = IF failed THEN IF failures < Threshold THEN failures + 1 ELSE Threshold ELSE 0 /\ open' = (open \/ failures' >= Threshold) /\ ui' = IF Visible /\ open' THEN "Error" ELSE "Indexed" /\ badStart' = (badStart \/ open) + /\ UNCHANGED leaked Progress == /\ ui' = IF Visible /\ open THEN ui ELSE "Indexed" - /\ UNCHANGED <> + /\ UNCHANGED <> Restart == /\ failures' = 0 /\ open' = FALSE /\ ui' = "Indexed" /\ badStart' = FALSE + /\ leaked' = (leaked \/ (open /\ ~DisposeOnRecovery)) Next == Batch(TRUE) \/ Batch(FALSE) \/ Progress \/ Restart Spec == Init /\ [][Next]_vars NoStartAfterTrip == ~badStart TripIsVisible == open => ui = "Error" +RecoveryDisposes == ~leaked ==== diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg new file mode 100644 index 00000000000..2a92b0a8c8b --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = FALSE + Visible = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg index e5a726d9eed..79e27765ac0 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg @@ -2,6 +2,7 @@ SPECIFICATION Spec CONSTANTS Threshold <- BatchLimit Guard = TRUE + DisposeOnRecovery = TRUE Visible = FALSE -INVARIANTS NoStartAfterTrip TripIsVisible +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg index 14af485a62d..49c2adf6799 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg @@ -2,6 +2,7 @@ SPECIFICATION Spec CONSTANTS Threshold <- BatchLimit Guard = FALSE + DisposeOnRecovery = TRUE Visible = TRUE -INVARIANTS NoStartAfterTrip TripIsVisible +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.cfg b/docs/architecture/tla/CodeIndexWatcherMC.cfg index f2560f67134..dcd2f8433b9 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.cfg @@ -2,6 +2,7 @@ SPECIFICATION Spec CONSTANTS Threshold <- BatchLimit Guard = TRUE + DisposeOnRecovery = TRUE Visible = TRUE -INVARIANTS NoStartAfterTrip TripIsVisible +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CHECK_DEADLOCK FALSE diff --git a/src/services/code-index/__tests__/manager.spec.ts b/src/services/code-index/__tests__/manager.spec.ts index 1263aaef14c..d45f0042add 100644 --- a/src/services/code-index/__tests__/manager.spec.ts +++ b/src/services/code-index/__tests__/manager.spec.ts @@ -552,6 +552,25 @@ describe("CodeIndexManager - handleSettingsChange regression", () => { ;(manager as any)._serviceFactory = {} }) + it.each([1, 2, 4])( + "disposes each tripped watcher before clearing it across %i recoveries", + async (restarts) => { + const orchestrator = manager["_orchestrator"]! + for (let restart = 0; restart < restarts; restart++) { + const stop = vi.spyOn(orchestrator, "stopWatcher").mockImplementation(() => { + expect(manager["_orchestrator"]).toBe(orchestrator) + }) + manager["_orchestrator"] = orchestrator + await manager.recoverFromError() + expect(stop).toHaveBeenCalledTimes(1) + expect(manager["_orchestrator"]).toBeUndefined() + await manager.recoverFromError() + expect(stop).toHaveBeenCalledTimes(1) + stop.mockRestore() + } + }, + ) + it("should clear error state when recoverFromError is called", async () => { // Act await manager.recoverFromError() diff --git a/src/services/code-index/manager.ts b/src/services/code-index/manager.ts index 26ce8de5cc8..111c884d697 100644 --- a/src/services/code-index/manager.ts +++ b/src/services/code-index/manager.ts @@ -276,6 +276,8 @@ export class CodeIndexManager { this._isRecoveringFromError = true try { + // Dispose the watcher before recovery clears its owner. + this._orchestrator?.stopWatcher() // Clear error state this._stateManager.setSystemState("Standby", "") } catch (error) { From 12cd1c66f2f75a4d76d2060b7cbea2c592a3fd86 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sat, 21 Nov 2026 16:37:00 +0000 Subject: [PATCH 4/7] fix(code-index): prevent isolated file failures from opening the breaker --- PRIVACY.md | 34 +++--- docs/architecture/tla/CodeIndexWatcher.tla | 67 +++++++++-- .../tla/CodeIndexWatcherMC.Delete.cfg | 14 +++ .../tla/CodeIndexWatcherMC.Leaked.cfg | 8 +- .../tla/CodeIndexWatcherMC.Local.cfg | 14 +++ .../tla/CodeIndexWatcherMC.Queued.cfg | 14 +++ .../tla/CodeIndexWatcherMC.Silent.cfg | 8 +- .../CodeIndexWatcherMC.SingleEmbedding.cfg | 14 +++ .../tla/CodeIndexWatcherMC.StaleCount.cfg | 14 +++ .../tla/CodeIndexWatcherMC.Unguarded.cfg | 8 +- .../tla/CodeIndexWatcherMC.Unreported.cfg | 14 +++ docs/architecture/tla/CodeIndexWatcherMC.cfg | 8 +- docs/architecture/tla/TelemetryBoundary.tla | 7 +- src/eslint-suppressions.json | 2 +- .../code-index/__tests__/manager.spec.ts | 52 +++++--- .../watcher-boundary.property.spec.ts | 111 +++++++++++++++--- .../code-index/interfaces/file-processor.ts | 2 + .../__tests__/file-preparation.spec.ts | 7 +- .../processors/__tests__/file-watcher.spec.ts | 103 +++++++++++++--- .../code-index/processors/file-preparation.ts | 20 ++-- .../code-index/processors/file-watcher.ts | 29 ++--- 21 files changed, 440 insertions(+), 110 deletions(-) create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Local.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg diff --git a/PRIVACY.md b/PRIVACY.md index ad86ff61489..23a8b393db2 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -32,22 +32,24 @@ go—and, importantly, where they don't. - **API Keys & Credentials**: If you enter an API key (e.g., to connect an AI model), it is stored locally on your device and never sent to us or any third party, except the provider you have chosen. -- **Telemetry (Usage Data)**: We collect feature usage and error data to help us - improve Zoo Code. This telemetry is powered by PostHog and includes a salted, - hashed (pseudonymized) form of your VS Code machine ID, feature usage - patterns, and exception reports. The raw VS Code machine ID never leaves your - device; we use the hashed identifier only for product analytics and error - grouping. PostHog event data is retained for 12 months under our current - project configuration. This PostHog-based telemetry does **not** collect your - code or AI prompts. (Separately, if you sign in to Zoo Code Cloud and enable - Cloud sync, the Cloud sync pipeline — which is distinct from this PostHog - telemetry — does transmit task messages so they can be shared or synced - through your Cloud account; that feature is controlled by its own Cloud sync - settings.) Telemetry is on by default. To turn it off, choose "Disabled" in - the settings or in the notice shown on first use. The notice remains until - you explicitly Accept or Decline. Telemetry also follows VS Code's own - global telemetry setting: if you turn that off, Zoo Code stops sending - telemetry right away, even if the Zoo Code setting says "Enabled." +- **Telemetry (Usage Data)**: We collect feature usage and error data to help + us improve Zoo Code. This telemetry is powered by PostHog and includes a + salted, hashed (pseudonymized) form of your VS Code machine ID, feature + usage patterns, and exception reports. The hashed ID remains a persistent + identifier for each device and can still be personal data. The raw VS Code + machine ID never leaves your device; we use the hashed identifier only for + product analytics and error grouping. PostHog event data is retained for 12 + months under our current project configuration. This PostHog-based telemetry + does **not** collect your code or AI prompts. (Separately, if you sign in to + Zoo Code Cloud and enable Cloud sync, the Cloud sync pipeline — which is + distinct from this PostHog telemetry — does transmit task messages so they + can be shared or synced through your Cloud account; that feature is + controlled by its own Cloud sync settings.) Telemetry is on by default. To + turn it off, choose "Disabled" in the settings or in the notice shown on + first use. The notice remains until you explicitly Accept or Decline. + Telemetry also follows VS Code's own global telemetry setting: if you turn + that off, Zoo Code stops sending telemetry right away, even if the Zoo Code + setting says "Enabled." - **Marketplace Requests**: When you browse or search the Marketplace for Model Configuration Profiles (MCPs) or Custom Modes, Zoo Code makes a secure API call to Zoo Code's backend servers to retrieve listing information. These diff --git a/docs/architecture/tla/CodeIndexWatcher.tla b/docs/architecture/tla/CodeIndexWatcher.tla index 347b7c674c4..6d430acebaf 100644 --- a/docs/architecture/tla/CodeIndexWatcher.tla +++ b/docs/architecture/tla/CodeIndexWatcher.tla @@ -11,34 +11,75 @@ \* Failure: recovery loses a live watcher. Invariant: RecoveryDisposes. \* Expect: recovery without disposal leaks after a trip. Overlapping work and cancellation remain outside scope. \* PR 2329, https://github.com/Zoo-Code-Org/Zoo-Code/pull/2329#discussion_r4638535661: added. -\* Result: fixed passes (4 states). Silent fails (4 states); Unguarded fails (5 states). Leaked fails (5 states). No new finding. +\* Result: fixed passes (9 states). All nine sabotage configs fail. No additional failure was found. +\* Variant states: SingleEmbedding 3, Local 3, Delete 4, Silent 8, StaleCount 8, Unreported 8, Leaked 10, Queued 10, Unguarded 10. \* Replay: watcher-boundary.property.spec.ts failed on 20 of 64 histories before the summary fix; all 64 now pass. \* Sabotage replay: silent summary, removed admission guards, and removed progress latch each fail test assertions. -\* Recovery replay: manager.spec.ts failed for 1, 2, and 4 recoveries before the fix; all pass with disposal. -\* Null result: the recovery rule reproduces the review finding and finds no additional failure. +\* Prior recovery tests checked call counts. Review found that recovery could swallow their ordering assertion. +\* Recovery replay now records the owner during stop and checks it after await. Moving clear before stop fails. +\* Replay: stat, read, and parse errors each tripped after three single-file batches before the fix. They no longer trip. +\* Replay: the old code omitted the trip event. The new test failed before emission was added. \* Scope: disposal is an oracle. Tests check the call before the manager clears the owner. -\* Cost: two small model files, four configs, 64 batch histories and three recovery counts. Agent time is not measured; each TLC run took under 1 second. -\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 0, added 2, gap 0. +\* Cost: two model files, ten configs, 689 batch histories, and focused boundary tests. Each TLC run took under 1 second. +\* Review cost: five new configs, 256 new histories, and seven runtime sabotages. Agent time is not measured. +\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 1, added 7, gap 2. +\* Review round: PR 2329, user-supplied Code Review Summary, findings 1-8. No thread URL was supplied. +\* Expected: local failures must not count; delete-only failures must count; each trip sends one event. +\* Expected: an open watcher drops queued events; restart clears the failure count. +\* Sources: FilePreparation.prepareFile, FileWatcher.processBatch, scheduleBatchProcessing, and initialize. +\* Sinks: the breaker flag, pending events, and CODE_INDEX_ERROR with errorType circuit_breaker_open. +\* Ratchet: 1, 4, 5, 6 added; 8 covered by TripIsVisible and the real watcher-to-orchestrator test. +\* Gap 2: PR structure is outside the runtime model. The user chose to keep one PR. +\* Gap 3: the model cannot check swallowed test assertions or disposal exceptions. Tests cover both paths. +\* Gap 7 is recorded in TelemetryBoundary. This review preceded the new invariants. +\* Runtime sabotages fail: local classification, delete clause, queue clear, counter reset, recovery order, +\* progress latch, and embedding-source tag. A stop exception is logged; recovery clears references and releases its guard. +\* Test scope: disposal exceptions can leave native resources. The model does not claim cleanup after a thrown disposal. +\* Follow-up review: a single rejected embedding must not count as a workspace failure. +\* Expect: three single-file embedding failures trip the old code. Two-file embedding failures still count. +\* The embedding oracle now distinguishes one attempted file from two. Delete-only batches still count at size one. +\* Replay: the real single-file embedding test failed on the old guard and passes with the two-file minimum. +\* Result: fixed still has 9 states; SingleEmbedding fails at 3 states. No additional failure was found. +\* Cost: one new config and 369 additional histories. Privacy line wrapping is outside this model. +\* The counter update now uses one conditional expression. Runtime flags remain because the model excludes overlap. EXTENDS Naturals -CONSTANTS Threshold, Guard, Visible, DisposeOnRecovery -VARIABLES failures, open, ui, badStart, leaked -vars == <> +CONSTANTS Threshold, Guard, Visible, DisposeOnRecovery, + CountLocal, CountDelete, ReportTrip, ClearQueue, ResetFailures, CountSingleEmbedding +VARIABLES failures, open, ui, badStart, leaked, badClassification, queued, fresh, tripEvents +vars == <> +Kinds == {"success", "local", "singleEmbedding", "embedding", "delete"} +ServiceFailure(kind) == kind \in {"embedding", "delete"} +CountsAsFailure(kind) == kind = "embedding" \/ (kind = "delete" /\ CountDelete) + \/ (kind = "local" /\ CountLocal) \/ (kind = "singleEmbedding" /\ CountSingleEmbedding) Init == /\ failures = 0 /\ open = FALSE /\ ui = "Indexed" /\ badStart = FALSE /\ leaked = FALSE -Batch(failed) == + /\ badClassification = FALSE /\ queued = FALSE /\ fresh = TRUE /\ tripEvents = 0 +Batch(kind) == /\ (~open \/ ~Guard) - /\ failures' = IF failed THEN IF failures < Threshold THEN failures + 1 ELSE Threshold ELSE 0 + /\ failures' = IF CountsAsFailure(kind) THEN IF failures < Threshold THEN failures + 1 ELSE Threshold ELSE 0 /\ open' = (open \/ failures' >= Threshold) /\ ui' = IF Visible /\ open' THEN "Error" ELSE "Indexed" /\ badStart' = (badStart \/ open) + /\ badClassification' = (badClassification \/ (CountsAsFailure(kind) # ServiceFailure(kind))) + /\ tripEvents' = IF ~open /\ open' /\ ReportTrip THEN tripEvents + 1 ELSE tripEvents + /\ queued' = FALSE /\ fresh' = FALSE /\ UNCHANGED leaked +Queue == /\ queued' = IF open /\ ClearQueue THEN FALSE ELSE TRUE + /\ UNCHANGED <> Progress == /\ ui' = IF Visible /\ open THEN ui ELSE "Indexed" - /\ UNCHANGED <> -Restart == /\ failures' = 0 /\ open' = FALSE /\ ui' = "Indexed" /\ badStart' = FALSE + /\ UNCHANGED <> +Restart == /\ failures' = IF ResetFailures THEN 0 ELSE failures + /\ open' = FALSE /\ ui' = "Indexed" /\ badStart' = FALSE /\ leaked' = (leaked \/ (open /\ ~DisposeOnRecovery)) -Next == Batch(TRUE) \/ Batch(FALSE) \/ Progress \/ Restart + /\ queued' = FALSE /\ fresh' = TRUE /\ tripEvents' = 0 + /\ UNCHANGED badClassification +Next == (\E kind \in Kinds: Batch(kind)) \/ Queue \/ Progress \/ Restart Spec == Init /\ [][Next]_vars NoStartAfterTrip == ~badStart TripIsVisible == open => ui = "Error" RecoveryDisposes == ~leaked +CorrectFailureSource == ~badClassification +OpenQueueEmpty == open => ~queued +RestartIsFresh == fresh => failures = 0 +TripIsReported == tripEvents = (IF open THEN 1 ELSE 0) ==== diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg new file mode 100644 index 00000000000..73de552b727 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = FALSE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg index 2a92b0a8c8b..ad77b224460 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg @@ -4,5 +4,11 @@ CONSTANTS Guard = TRUE DisposeOnRecovery = FALSE Visible = TRUE -INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg new file mode 100644 index 00000000000..22886f14319 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = TRUE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg new file mode 100644 index 00000000000..3bd58d118aa --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = FALSE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg index 79e27765ac0..67abef78c23 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg @@ -4,5 +4,11 @@ CONSTANTS Guard = TRUE DisposeOnRecovery = TRUE Visible = FALSE -INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg b/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg new file mode 100644 index 00000000000..80292b68241 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = TRUE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg b/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg new file mode 100644 index 00000000000..a3462d181c5 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = FALSE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg index 49c2adf6799..25eb61cbb99 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg @@ -4,5 +4,11 @@ CONSTANTS Guard = FALSE DisposeOnRecovery = TRUE Visible = TRUE -INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg new file mode 100644 index 00000000000..d3fcc382983 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg @@ -0,0 +1,14 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = FALSE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.cfg b/docs/architecture/tla/CodeIndexWatcherMC.cfg index dcd2f8433b9..e1d65b4aa0e 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.cfg @@ -4,5 +4,11 @@ CONSTANTS Guard = TRUE DisposeOnRecovery = TRUE Visible = TRUE -INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TelemetryBoundary.tla b/docs/architecture/tla/TelemetryBoundary.tla index 44d3a4d7ee4..2e46b27507e 100644 --- a/docs/architecture/tla/TelemetryBoundary.tla +++ b/docs/architecture/tla/TelemetryBoundary.tla @@ -11,7 +11,12 @@ \* Tests: tool-usage-attribution checks four calls for static and MCP tools, aggregate counts, and no per-call event. \* Scope excludes task completion delivery, removed unused APIs, policy text, other payload fields, and cloud sync. \* Cost: two small model files, four configs, 36 IDs and two call sequences. Agent time is not measured; TLC runs took under 1 second. -\* Gate: TLA_JAR= ./check.sh TelemetryBoundaryMC. Review counts: covered 0, added 0, gap 0. +\* Gate: TLA_JAR= ./check.sh TelemetryBoundaryMC. Review counts: covered 0, added 0, gap 2. +\* PR 2329, user-supplied review finding 7: gap. No thread URL was supplied. +\* The model checks pseudonymous sinks, not privacy wording or resistance to joining known IDs. +\* PRIVACY.md now states that the hash remains a persistent device ID and can be personal data. +\* Expected and result: this text change does not alter identity projection. No new runtime finding is expected. +\* Follow-up privacy line wrapping: gap. Layout has no runtime state. Only whitespace changed. EXTENDS Naturals CONSTANTS HashHost, HashWebview, PerCall, MaxCalls VARIABLES host, webview, calls, aggregate, events diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index 4e010d814f3..ca728079e17 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -1111,7 +1111,7 @@ }, "services/code-index/processors/__tests__/file-watcher.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 25 + "count": 24 } }, "services/code-index/processors/__tests__/parser.spec.ts": { diff --git a/src/services/code-index/__tests__/manager.spec.ts b/src/services/code-index/__tests__/manager.spec.ts index d45f0042add..4d0f112a599 100644 --- a/src/services/code-index/__tests__/manager.spec.ts +++ b/src/services/code-index/__tests__/manager.spec.ts @@ -552,24 +552,40 @@ describe("CodeIndexManager - handleSettingsChange regression", () => { ;(manager as any)._serviceFactory = {} }) - it.each([1, 2, 4])( - "disposes each tripped watcher before clearing it across %i recoveries", - async (restarts) => { - const orchestrator = manager["_orchestrator"]! - for (let restart = 0; restart < restarts; restart++) { - const stop = vi.spyOn(orchestrator, "stopWatcher").mockImplementation(() => { - expect(manager["_orchestrator"]).toBe(orchestrator) - }) - manager["_orchestrator"] = orchestrator - await manager.recoverFromError() - expect(stop).toHaveBeenCalledTimes(1) - expect(manager["_orchestrator"]).toBeUndefined() - await manager.recoverFromError() - expect(stop).toHaveBeenCalledTimes(1) - stop.mockRestore() - } - }, - ) + it("stops the watcher before clearing its owner and accepts recovery without an owner", async () => { + const orchestrator = manager["_orchestrator"]! + const ownersAtStop: Array = [] + const stop = vi.spyOn(orchestrator, "stopWatcher").mockImplementation(() => { + ownersAtStop.push(manager["_orchestrator"]) + }) + await manager.recoverFromError() + expect(ownersAtStop).toEqual([orchestrator]) + expect(manager["_orchestrator"]).toBeUndefined() + await manager.recoverFromError() + expect(stop).toHaveBeenCalledTimes(1) + }) + + it("clears service references and releases the recovery guard when stopping the watcher throws", async () => { + const error = new Error("Watcher disposal failed") + const orchestrator = manager["_orchestrator"]! + const stop = vi.spyOn(orchestrator, "stopWatcher").mockImplementation(() => { + throw error + }) + const log = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + await expect(manager.recoverFromError()).resolves.toBeUndefined() + expect(stop).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith("Failed to clear error state during recovery:", error) + expect(manager["_orchestrator"]).toBeUndefined() + expect(manager["_configManager"]).toBeUndefined() + expect(manager["_serviceFactory"]).toBeUndefined() + expect(manager["_searchService"]).toBeUndefined() + await manager.recoverFromError() + expect(manager["_stateManager"].setSystemState).toHaveBeenCalledWith("Standby", "") + } finally { + log.mockRestore() + } + }) it("should clear error state when recoverFromError is called", async () => { // Act diff --git a/src/services/code-index/__tests__/watcher-boundary.property.spec.ts b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts index f57b7f82040..80aa1fb9b1a 100644 --- a/src/services/code-index/__tests__/watcher-boundary.property.spec.ts +++ b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts @@ -6,7 +6,8 @@ import { CodeIndexStateManager } from "../state-manager" import type { CodeIndexConfigManager } from "../config-manager" import type { CacheManager } from "../cache-manager" import type { DirectoryScanner } from "../processors" -import type { IVectorStore } from "../interfaces" +import type { FileProcessingResult, IVectorStore } from "../interfaces" +import { TelemetryService } from "@roo-code/telemetry" import { makeUri } from "../../../test-utils/vscode" vi.mock("../processors/parser", () => ({ codeParser: {} })) @@ -49,14 +50,33 @@ function setup() { // These doubles provide only the members used by watcher startup and the no-upsert batches below. const config = { isFeatureConfigured: true } as CodeIndexConfigManager const cache = {} as CacheManager - const store = {} as IVectorStore + const store = { + initialize: vi.fn(), + upsertPoints: vi.fn(), + search: vi.fn(), + deletePointsByFilePath: vi.fn(), + deletePointsByMultipleFilePaths: vi.fn(), + clearCollection: vi.fn(), + deleteCollection: vi.fn(), + collectionExists: vi.fn(), + hasIndexedData: vi.fn(), + markIndexingComplete: vi.fn(), + markIndexingIncomplete: vi.fn(), + } satisfies IVectorStore const scanner = {} as DirectoryScanner const context = {} as vscode.ExtensionContext const watcher = new FileWatcher("/workspace", context, cache, undefined, store, undefined, undefined, 60) const state = new CodeIndexStateManager() const orchestrator = new CodeIndexOrchestrator(config, state, "/workspace", cache, store, scanner, watcher) const prepare = vi.spyOn(watcher, "processFile") - return { watcher, state, orchestrator, prepare } + return { watcher, state, orchestrator, prepare, store } +} + +function enqueueBatch(watcher: FileWatcher, path: string, type: "create" | "delete" = "create", files = 1) { + for (let index = 0; index < files; index++) { + const filePath = index === 0 ? path : `${path}.peer.ts` + watcher["accumulatedEvents"].set(filePath, { uri: makeUri(filePath), type }) + } } // Exhaust all success/failure histories up to six batches; the model's provider result is an oracle. @@ -74,32 +94,37 @@ describe("watcher source-to-state properties", () => { let open = false try { for (const [index, failed] of history.entries()) { - prepare.mockResolvedValue({ - path: `/workspace/${index}.ts`, + prepare.mockImplementation(async (path) => ({ + path, status: failed ? "local_error" : "skipped", - }) + failureSource: failed ? "embedding" : undefined, + })) const before = prepare.mock.calls.length - watcher["accumulatedEvents"].set(`/workspace/${index}.ts`, { - uri: makeUri(`/workspace/${index}.ts`), - type: "create", - }) + enqueueBatch(watcher, `/workspace/${index}.ts`, "create", 2) await watcher["triggerBatchProcessing"]() - expect(prepare.mock.calls.length - before).toBe(open ? 0 : 1) + expect(prepare.mock.calls.length - before).toBe(open ? 0 : 2) if (!open) failures = failed ? failures + 1 : 0 open ||= failures >= 3 expect(state.state).toBe(open ? "Error" : "Indexed") - if (open) expect(state.getCurrentStatus().message).toMatch(/restart|re-run|configuration/i) + if (open) { + expect(state.getCurrentStatus().message).toMatch(/restart|re-run|configuration/i) + for (const total of [0, 1]) { + watcher["_onBatchProgressUpdate"].fire({ processedInBatch: total, totalInBatch: total }) + expect(state.state).toBe("Error") + } + } } // A new subscription resets both the producer and consumer breaker state. await orchestrator["_startWatcher"]() - prepare.mockResolvedValue({ path: "/workspace/recovered.ts", status: "skipped" }) - watcher["accumulatedEvents"].set("/workspace/recovered.ts", { - uri: makeUri("/workspace/recovered.ts"), - type: "create", - }) + prepare.mockImplementation(async (path) => ({ + path, + status: "local_error", + failureSource: "embedding", + })) + enqueueBatch(watcher, "/workspace/recovered.ts", "create", 2) const before = prepare.mock.calls.length await watcher["triggerBatchProcessing"]() - expect(prepare.mock.calls.length).toBe(before + 1) + expect(prepare.mock.calls.length).toBe(before + 2) expect(state.state).toBe("Indexed") } finally { orchestrator.stopWatcher() @@ -107,3 +132,53 @@ describe("watcher source-to-state properties", () => { }, ) }) + +const outcomes = ["success", "local", "singleEmbedding", "embedding", "delete"] as const +const sourceHistories = Array.from({ length: outcomes.length ** 4 }, (_, sequence) => + Array.from( + { length: 4 }, + (_, index) => outcomes[Math.floor(sequence / outcomes.length ** index) % outcomes.length], + ), +) + +describe("watcher failure-source properties", () => { + it.each(sourceHistories.map((history) => [history] as const))( + "counts only shared-service failures and reports one trip for %j", + async (history) => { + const { watcher, state, orchestrator, prepare, store } = setup() + const capture = vi.mocked(TelemetryService.instance.captureEvent) + capture.mockClear() + await orchestrator["_startWatcher"]() + let failures = 0 + let open = false + try { + for (const [index, outcome] of history.entries()) { + const path = `/workspace/${index}.ts` + const result: FileProcessingResult = { + path, + status: outcome === "success" ? "skipped" : "local_error", + ...(outcome === "embedding" || outcome === "singleEmbedding" + ? { failureSource: "embedding" as const } + : {}), + } + prepare.mockImplementation(async (path) => ({ ...result, path })) + vi.mocked(store.deletePointsByMultipleFilePaths).mockRejectedValue(new Error("Store unavailable")) + const files = outcome === "embedding" ? 2 : 1 + enqueueBatch(watcher, path, outcome === "delete" ? "delete" : "create", files) + const before = prepare.mock.calls.length + await watcher["triggerBatchProcessing"]() + expect(prepare.mock.calls.length - before).toBe(open || outcome === "delete" ? 0 : files) + if (!open) failures = outcome === "embedding" || outcome === "delete" ? failures + 1 : 0 + open ||= failures >= 3 + expect(state.state).toBe(open ? "Error" : "Indexed") + expect(watcher["accumulatedEvents"].size).toBe(0) + expect( + capture.mock.calls.filter(([, props]) => props?.errorType === "circuit_breaker_open"), + ).toHaveLength(open ? 1 : 0) + } + } finally { + orchestrator.stopWatcher() + } + }, + ) +}) diff --git a/src/services/code-index/interfaces/file-processor.ts b/src/services/code-index/interfaces/file-processor.ts index 53c0412eb51..484f6862133 100644 --- a/src/services/code-index/interfaces/file-processor.ts +++ b/src/services/code-index/interfaces/file-processor.ts @@ -97,6 +97,8 @@ export interface BatchProcessingSummary { export interface FileProcessingResult { path: string status: "success" | "skipped" | "error" | "processed_for_batching" | "local_error" + /** Set only when the embedding request fails, rather than file preparation. */ + failureSource?: "embedding" error?: Error reason?: string newHash?: string diff --git a/src/services/code-index/processors/__tests__/file-preparation.spec.ts b/src/services/code-index/processors/__tests__/file-preparation.spec.ts index 22020a9fddf..261300da586 100644 --- a/src/services/code-index/processors/__tests__/file-preparation.spec.ts +++ b/src/services/code-index/processors/__tests__/file-preparation.spec.ts @@ -310,7 +310,12 @@ describe.each(["posix", "win32"] as const)("FilePreparation (%s paths)", (platfo if (stage === "parse") dependencies.parser.parseFile.mockRejectedValue(error) if (stage === "embed") dependencies.embedder.createEmbeddings.mockRejectedValue(error) const result = await new FilePreparation(dependencies).prepareFile(filePath) - expect(result).toEqual({ path: filePath, status: "local_error", error }) + expect(result).toEqual({ + path: filePath, + status: "local_error", + error, + ...(stage === "embed" ? { failureSource: "embedding" } : {}), + }) expect(result.error).toBe(error) }, ) diff --git a/src/services/code-index/processors/__tests__/file-watcher.spec.ts b/src/services/code-index/processors/__tests__/file-watcher.spec.ts index 6575c698809..9604e7adeca 100644 --- a/src/services/code-index/processors/__tests__/file-watcher.spec.ts +++ b/src/services/code-index/processors/__tests__/file-watcher.spec.ts @@ -4,12 +4,15 @@ import * as vscode from "vscode" import { FileWatcher } from "../file-watcher" import { FilePreparation } from "../file-preparation" -import type { FileProcessingResult } from "../../interfaces" +import { TelemetryService } from "@roo-code/telemetry" +import { TelemetryEventName } from "@roo-code/types" +import { codeParser } from "../parser" +import type { BatchProcessingSummary, FileProcessingResult } from "../../interfaces" import { clearAllMocks } from "../../../../test-utils/reset" // Mock TelemetryService -vi.mock("../../../../../packages/telemetry/src/TelemetryService", () => ({ +vi.mock("@roo-code/telemetry", () => ({ TelemetryService: { instance: { captureEvent: vi.fn(), @@ -102,7 +105,7 @@ describe("FileWatcher", () => { let mockIgnoreInstance: any const waitForNextBatch = () => - new Promise((resolve) => { + new Promise((resolve) => { const disposable = fileWatcher.onDidFinishBatchProcessing((summary) => { disposable.dispose() resolve(summary) @@ -360,10 +363,14 @@ describe("FileWatcher", () => { }) describe("per-workspace circuit breaker", () => { - /** Fire one create event, flush the debounce window, and wait for the batch to finish. */ - const runBatch = async (filePath: string) => { + /** Queue file events, flush the debounce window, and wait for the batch to finish. */ + const runBatch = async (filePath: string, type: "create" | "delete" = "create", files = 1) => { const batchPromise = waitForNextBatch() - await mockOnDidCreate({ fsPath: filePath }) + for (let index = 0; index < files; index++) { + await (type === "delete" ? mockOnDidDelete : mockOnDidCreate)({ + fsPath: index === 0 ? filePath : `${filePath}.peer.ts`, + }) + } await vi.advanceTimersByTimeAsync(500) return batchPromise } @@ -374,11 +381,11 @@ describe("FileWatcher", () => { // Three consecutive all-fail batches trip the breaker on the third. for (let i = 0; i < 3; i++) { - const summary = await runBatch(`/mock/workspace/src/broken-${i}.ts`) - expect(summary.processedFiles).toHaveLength(1) + const summary = await runBatch(`/mock/workspace/src/broken-${i}.ts`, "create", 2) + expect(summary.processedFiles).toHaveLength(2) expect(summary.processedFiles[0].status).toBe("local_error") } - expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(3) + expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(6) // Further events are dropped: no batch starts and no embedder call is made. const started = vi.fn() @@ -386,7 +393,74 @@ describe("FileWatcher", () => { await mockOnDidCreate({ fsPath: "/mock/workspace/src/after-breaker.ts" }) await vi.advanceTimersByTimeAsync(500) expect(started).not.toHaveBeenCalled() - expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(3) + expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(6) + }) + + it.each(["stat", "read", "parse", "embed"] as const)( + "does not count repeated single-file %s failures as service failures", + async (stage) => { + await fileWatcher.initialize() + for (let index = 0; index < 4; index++) { + const error = new Error(`${stage} failed`) + if (stage === "stat") vi.mocked(vscode.workspace.fs.stat).mockRejectedValueOnce(error) + if (stage === "read") vi.mocked(vscode.workspace.fs.readFile).mockRejectedValueOnce(error) + if (stage === "parse") vi.mocked(codeParser.parseFile).mockRejectedValueOnce(error) + if (stage === "embed") mockEmbedder.createEmbeddings.mockRejectedValueOnce(error) + const summary = await runBatch(`/mock/workspace/src/local-${index}.ts`) + expect(summary.processedFiles).toEqual([ + { + path: `/mock/workspace/src/local-${index}.ts`, + status: "local_error", + error, + ...(stage === "embed" ? { failureSource: "embedding" } : {}), + }, + ]) + expect(summary.circuitBreakerOpen).toBe(false) + } + }, + ) + + it("counts failed delete-only batches and drops later deletions", async () => { + await fileWatcher.initialize() + const error = new Error("Vector store unavailable") + mockVectorStore.deletePointsByMultipleFilePaths.mockRejectedValue(error) + for (let index = 0; index < 3; index++) { + const summary = await runBatch(`/mock/workspace/src/deleted-${index}.ts`, "delete") + expect(summary.batchError).toBe(error) + expect(summary.circuitBreakerOpen).toBe(index === 2) + } + await mockOnDidDelete({ fsPath: "/mock/workspace/src/after-trip.ts" }) + expect(fileWatcher["accumulatedEvents"].size).toBe(0) + expect(vi.getTimerCount()).toBe(0) + await vi.advanceTimersByTimeAsync(500) + expect(mockVectorStore.deletePointsByMultipleFilePaths).toHaveBeenCalledTimes(3) + expect(mockEmbedder.createEmbeddings).not.toHaveBeenCalled() + }) + + it("reports one trip and clears events without scheduling more work", async () => { + await fileWatcher.initialize() + mockEmbedder.createEmbeddings.mockRejectedValue(new Error("Embedder unavailable")) + const capture = vi.mocked(TelemetryService.instance.captureEvent) + for (let index = 0; index < 3; index++) { + await runBatch(`/mock/workspace/src/broken-${index}.ts`, "create", 2) + expect( + capture.mock.calls.filter(([, props]) => props?.errorType === "circuit_breaker_open"), + ).toHaveLength(index === 2 ? 1 : 0) + } + for (let index = 0; index < 4; index++) { + await mockOnDidCreate({ fsPath: `/mock/workspace/src/dropped-${index}.ts` }) + expect(fileWatcher["accumulatedEvents"].size).toBe(0) + expect(vi.getTimerCount()).toBe(0) + } + expect(capture).toHaveBeenCalledWith(TelemetryEventName.CODE_INDEX_ERROR, { + error: "File watcher stopped after repeated indexing failures", + location: "FileWatcher.processBatch", + errorType: "circuit_breaker_open", + failedBatches: 3, + }) + expect(capture.mock.calls.filter(([, props]) => props?.errorType === "circuit_breaker_open")).toHaveLength( + 1, + ) }) it("resets the failure counter when a batch succeeds between failures", async () => { @@ -397,8 +471,8 @@ describe("FileWatcher", () => { // Two consecutive failures... fail() - await runBatch("/mock/workspace/src/fail-1.ts") - await runBatch("/mock/workspace/src/fail-2.ts") + await runBatch("/mock/workspace/src/fail-1.ts", "create", 2) + await runBatch("/mock/workspace/src/fail-2.ts", "create", 2) // ...then a success resets the counter. succeed() @@ -406,13 +480,14 @@ describe("FileWatcher", () => { // Only two failures since the reset: the breaker must stay closed. fail() - await runBatch("/mock/workspace/src/fail-3.ts") - await runBatch("/mock/workspace/src/fail-4.ts") + await runBatch("/mock/workspace/src/fail-3.ts", "create", 2) + await runBatch("/mock/workspace/src/fail-4.ts", "create", 2) const started = vi.fn() fileWatcher.onDidStartBatchProcessing(started) const batchPromise = waitForNextBatch() await mockOnDidCreate({ fsPath: "/mock/workspace/src/fail-5.ts" }) + await mockOnDidCreate({ fsPath: "/mock/workspace/src/fail-5-peer.ts" }) await vi.advanceTimersByTimeAsync(500) await batchPromise expect(started).toHaveBeenCalledTimes(1) diff --git a/src/services/code-index/processors/file-preparation.ts b/src/services/code-index/processors/file-preparation.ts index a99ff6b56a3..338e1e86380 100644 --- a/src/services/code-index/processors/file-preparation.ts +++ b/src/services/code-index/processors/file-preparation.ts @@ -28,7 +28,17 @@ export class FilePreparation { } const blocks = await dependencies.parser.parseFile(filePath, { content, fileHash: newHash }) - const pointsToUpsert = await this.preparePoints(blocks) + let pointsToUpsert: PointStruct[] = [] + if (dependencies.embedder && blocks.length > 0) { + let embeddings: number[][] + try { + const result = await dependencies.embedder.createEmbeddings(blocks.map((block) => block.content)) + embeddings = result.embeddings + } catch (error) { + return { path: filePath, status: "local_error", error: error as Error, failureSource: "embedding" } + } + pointsToUpsert = this.preparePoints(blocks, embeddings) + } return { path: filePath, @@ -71,14 +81,8 @@ export class FilePreparation { return { path: filePath, status: "skipped", reason } } - private async preparePoints(blocks: CodeBlock[]): Promise { + private preparePoints(blocks: CodeBlock[], embeddings: number[][]): PointStruct[] { const dependencies = this.dependencies - if (!dependencies.embedder || blocks.length === 0) { - return [] - } - - const texts = blocks.map((block) => block.content) - const { embeddings } = await dependencies.embedder.createEmbeddings(texts) return blocks.map((block, index) => { const normalizedAbsolutePath = generateNormalizedAbsolutePath(block.file_path, dependencies.workspacePath) diff --git a/src/services/code-index/processors/file-watcher.ts b/src/services/code-index/processors/file-watcher.ts index 5c8b8c23fb4..436ec356799 100644 --- a/src/services/code-index/processors/file-watcher.ts +++ b/src/services/code-index/processors/file-watcher.ts @@ -514,28 +514,25 @@ export class FileWatcher implements IFileWatcher { overallBatchError, ) - // Circuit-breaker bookkeeping. A batch counts as failed when the batch-level - // pipeline broke (deletion/upsert errors) or every file attempted in the batch - // failed (e.g. a broken embedder rejecting every createEmbeddings call). - // Isolated per-file failures do not count, so one unreadable file cannot trip - // the breaker for healthy indexing. + // A single rejected input does not establish an embedding service failure. + // Storage failures count at any batch size. File read and parse errors stay local. const resultsByPath = new Map(batchResults.map((result) => [result.path, result])) - const allAttemptedFilesFailed = - filesToUpsertDetails.length > 0 && - filesToUpsertDetails.every((detail) => { - const status = resultsByPath.get(detail.path)?.status - return status === "error" || status === "local_error" - }) + const allAttemptedEmbeddingsFailed = + filesToUpsertDetails.length >= 2 && + filesToUpsertDetails.every((detail) => resultsByPath.get(detail.path)?.failureSource === "embedding") - if (overallBatchError !== undefined || allAttemptedFilesFailed) { - this.consecutiveFailedBatches++ - } else { - this.consecutiveFailedBatches = 0 - } + this.consecutiveFailedBatches = + overallBatchError !== undefined || allAttemptedEmbeddingsFailed ? this.consecutiveFailedBatches + 1 : 0 if (!this.circuitBreakerOpen && this.consecutiveFailedBatches >= CIRCUIT_BREAKER_BATCH_THRESHOLD) { this.circuitBreakerOpen = true this.accumulatedEvents.clear() + TelemetryService.instance.captureEvent(TelemetryEventName.CODE_INDEX_ERROR, { + error: "File watcher stopped after repeated indexing failures", + location: "FileWatcher.processBatch", + errorType: "circuit_breaker_open", + failedBatches: this.consecutiveFailedBatches, + }) console.error( `[FileWatcher] Circuit breaker opened after ${this.consecutiveFailedBatches} consecutive failed batches; ` + `dropping further file-system events for this workspace until the embedder or vector store configuration changes.`, From 3b368b8d747a2b99f82c32688425630905363a04 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sat, 21 Nov 2026 20:12:33 +0000 Subject: [PATCH 5/7] fix(code-index): count embedding failures independently of skipped files --- PRIVACY.md | 4 +- docs/architecture/tla/CodeIndexWatcher.tla | 33 ++++++--- .../tla/CodeIndexWatcherMC.Delete.cfg | 2 + .../tla/CodeIndexWatcherMC.Idle.cfg | 16 +++++ .../tla/CodeIndexWatcherMC.Leaked.cfg | 2 + .../tla/CodeIndexWatcherMC.Local.cfg | 2 + .../tla/CodeIndexWatcherMC.Queued.cfg | 2 + .../tla/CodeIndexWatcherMC.Silent.cfg | 2 + .../CodeIndexWatcherMC.SingleEmbedding.cfg | 2 + .../tla/CodeIndexWatcherMC.Skipped.cfg | 16 +++++ .../tla/CodeIndexWatcherMC.StaleCount.cfg | 2 + .../tla/CodeIndexWatcherMC.Unguarded.cfg | 2 + .../tla/CodeIndexWatcherMC.Unreported.cfg | 2 + docs/architecture/tla/CodeIndexWatcherMC.cfg | 2 + docs/architecture/tla/TelemetryBoundary.tla | 3 +- .../watcher-boundary.property.spec.ts | 51 ++++++++++---- .../code-index/interfaces/file-processor.ts | 4 +- .../__tests__/file-preparation.spec.ts | 3 +- .../processors/__tests__/file-watcher.spec.ts | 70 ++++++++++++++++++- .../code-index/processors/file-preparation.ts | 6 +- .../code-index/processors/file-watcher.ts | 16 +++-- 21 files changed, 204 insertions(+), 38 deletions(-) create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Idle.cfg create mode 100644 docs/architecture/tla/CodeIndexWatcherMC.Skipped.cfg diff --git a/PRIVACY.md b/PRIVACY.md index 23a8b393db2..c592170f343 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -41,8 +41,8 @@ go—and, importantly, where they don't. product analytics and error grouping. PostHog event data is retained for 12 months under our current project configuration. This PostHog-based telemetry does **not** collect your code or AI prompts. (Separately, if you sign in to - Zoo Code Cloud and enable Cloud sync, the Cloud sync pipeline — which is - distinct from this PostHog telemetry — does transmit task messages so they + Zoo Code Cloud and enable Cloud sync, the Cloud sync pipeline, which is + distinct from this PostHog telemetry, does transmit task messages so they can be shared or synced through your Cloud account; that feature is controlled by its own Cloud sync settings.) Telemetry is on by default. To turn it off, choose "Disabled" in the settings or in the notice shown on diff --git a/docs/architecture/tla/CodeIndexWatcher.tla b/docs/architecture/tla/CodeIndexWatcher.tla index 6d430acebaf..d8ab60231a7 100644 --- a/docs/architecture/tla/CodeIndexWatcher.tla +++ b/docs/architecture/tla/CodeIndexWatcher.tla @@ -11,7 +11,7 @@ \* Failure: recovery loses a live watcher. Invariant: RecoveryDisposes. \* Expect: recovery without disposal leaks after a trip. Overlapping work and cancellation remain outside scope. \* PR 2329, https://github.com/Zoo-Code-Org/Zoo-Code/pull/2329#discussion_r4638535661: added. -\* Result: fixed passes (9 states). All nine sabotage configs fail. No additional failure was found. +\* Prior result: fixed passes (9 states). All nine sabotage configs fail. No additional failure was found. \* Variant states: SingleEmbedding 3, Local 3, Delete 4, Silent 8, StaleCount 8, Unreported 8, Leaked 10, Queued 10, Unguarded 10. \* Replay: watcher-boundary.property.spec.ts failed on 20 of 64 histories before the summary fix; all 64 now pass. \* Sabotage replay: silent summary, removed admission guards, and removed progress latch each fail test assertions. @@ -20,9 +20,9 @@ \* Replay: stat, read, and parse errors each tripped after three single-file batches before the fix. They no longer trip. \* Replay: the old code omitted the trip event. The new test failed before emission was added. \* Scope: disposal is an oracle. Tests check the call before the manager clears the owner. -\* Cost: two model files, ten configs, 689 batch histories, and focused boundary tests. Each TLC run took under 1 second. +\* Prior cost: two model files, ten configs, 689 batch histories, and focused boundary tests. Each TLC run took under 1 second. \* Review cost: five new configs, 256 new histories, and seven runtime sabotages. Agent time is not measured. -\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 1, added 7, gap 2. +\* Gate: TLA_JAR= ./check.sh CodeIndexWatcherMC. Review counts: covered 1, added 9, gap 4. \* Review round: PR 2329, user-supplied Code Review Summary, findings 1-8. No thread URL was supplied. \* Expected: local failures must not count; delete-only failures must count; each trip sends one event. \* Expected: an open watcher drops queued events; restart clears the failure count. @@ -41,25 +41,38 @@ \* Replay: the real single-file embedding test failed on the old guard and passes with the two-file minimum. \* Result: fixed still has 9 states; SingleEmbedding fails at 3 states. No additional failure was found. \* Cost: one new config and 369 additional histories. Privacy line wrapping is outside this model. -\* The counter update now uses one conditional expression. Runtime flags remain because the model excludes overlap. +\* Prior simplification used one conditional expression. Runtime flags remain because the model excludes overlap. +\* Incremental review at 12cd1c66f2: PR 2329, user-supplied summary, no thread URL. +\* Expect: skipped files must not mask two failed embedding attempts. Idle batches must preserve the count. +\* Failure: a skipped file hides an outage, or an idle batch resets outage evidence. Invariant: CorrectFailureSource. +\* Ratchet: findings 1 and 2 added through mixed and idle input rules. Finding 3 is a prose gap. +\* Finding 4 remains a scope gap. The user chose one PR. No new invariant preceded this supplied review. +\* Source: FilePreparation.prepareFile embeddingOutcome; sink: FileWatcher.processBatch failure counter. +\* Incremental result: fixed passes at 9 states. All eleven sabotage configs fail; no additional bug was found. +\* Skipped sabotage: 4 states. Idle-reset sabotage: 6 states. Both real-code regressions failed before the fix. +\* Replay: local-as-embedding, every-to-some, and idle-reset runtime mutations each fail focused tests. +\* Cost: two new configs and 3,471 more histories (4,160 total). No new state variable. Agent time is not measured. +\* Incremental ratchet: added 2, gap 2. PR prose and the optional split are outside the runtime model. EXTENDS Naturals CONSTANTS Threshold, Guard, Visible, DisposeOnRecovery, - CountLocal, CountDelete, ReportTrip, ClearQueue, ResetFailures, CountSingleEmbedding + CountLocal, CountDelete, ReportTrip, ClearQueue, ResetFailures, CountSingleEmbedding, IgnoreSkipped, ResetIdle VARIABLES failures, open, ui, badStart, leaked, badClassification, queued, fresh, tripEvents vars == <> -Kinds == {"success", "local", "singleEmbedding", "embedding", "delete"} -ServiceFailure(kind) == kind \in {"embedding", "delete"} -CountsAsFailure(kind) == kind = "embedding" \/ (kind = "delete" /\ CountDelete) +Kinds == {"success", "local", "singleEmbedding", "embedding", "delete", "embeddingSkipped", "idle", "mixed"} +ServiceFailure(kind) == kind \in {"embedding", "embeddingSkipped", "delete"} +CountsAsFailure(kind) == kind = "embedding" \/ (kind = "embeddingSkipped" /\ IgnoreSkipped) \/ (kind = "delete" /\ CountDelete) \/ (kind = "local" /\ CountLocal) \/ (kind = "singleEmbedding" /\ CountSingleEmbedding) Init == /\ failures = 0 /\ open = FALSE /\ ui = "Indexed" /\ badStart = FALSE /\ leaked = FALSE /\ badClassification = FALSE /\ queued = FALSE /\ fresh = TRUE /\ tripEvents = 0 Batch(kind) == /\ (~open \/ ~Guard) - /\ failures' = IF CountsAsFailure(kind) THEN IF failures < Threshold THEN failures + 1 ELSE Threshold ELSE 0 + /\ failures' = IF CountsAsFailure(kind) THEN IF failures < Threshold THEN failures + 1 ELSE Threshold + ELSE IF kind \in {"idle", "local"} /\ ~ResetIdle THEN failures ELSE 0 /\ open' = (open \/ failures' >= Threshold) /\ ui' = IF Visible /\ open' THEN "Error" ELSE "Indexed" /\ badStart' = (badStart \/ open) - /\ badClassification' = (badClassification \/ (CountsAsFailure(kind) # ServiceFailure(kind))) + /\ badClassification' = (badClassification \/ (CountsAsFailure(kind) # ServiceFailure(kind)) + \/ (kind \in {"idle", "local"} /\ ~CountsAsFailure(kind) /\ failures' # failures)) /\ tripEvents' = IF ~open /\ open' /\ ReportTrip THEN tripEvents + 1 ELSE tripEvents /\ queued' = FALSE /\ fresh' = FALSE /\ UNCHANGED leaked diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg index 73de552b727..bfb3a507e25 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = FALSE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Idle.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Idle.cfg new file mode 100644 index 00000000000..09addd8596d --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Idle.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = TRUE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg index ad77b224460..b7f53c10076 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg index 22886f14319..26553e53c19 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg index 3bd58d118aa..f774a1cfb6b 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Queued.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = FALSE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg index 67abef78c23..0cbf2bba02f 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg b/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg index 80292b68241..d408a5e5072 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Skipped.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Skipped.cfg new file mode 100644 index 00000000000..c81ad87aef6 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Skipped.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + CountDelete = TRUE + ReportTrip = TRUE + ClearQueue = TRUE + IgnoreSkipped = FALSE + ResetIdle = FALSE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg b/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg index a3462d181c5..c347a814e27 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = FALSE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg index 25eb61cbb99..e0aeaaffb74 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg b/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg index d3fcc382983..2978cc60d4b 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = FALSE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/CodeIndexWatcherMC.cfg b/docs/architecture/tla/CodeIndexWatcherMC.cfg index e1d65b4aa0e..e5cd60a7043 100644 --- a/docs/architecture/tla/CodeIndexWatcherMC.cfg +++ b/docs/architecture/tla/CodeIndexWatcherMC.cfg @@ -9,6 +9,8 @@ CONSTANTS CountDelete = TRUE ReportTrip = TRUE ClearQueue = TRUE + IgnoreSkipped = TRUE + ResetIdle = FALSE ResetFailures = TRUE INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TelemetryBoundary.tla b/docs/architecture/tla/TelemetryBoundary.tla index 2e46b27507e..ae7ab60b593 100644 --- a/docs/architecture/tla/TelemetryBoundary.tla +++ b/docs/architecture/tla/TelemetryBoundary.tla @@ -11,12 +11,13 @@ \* Tests: tool-usage-attribution checks four calls for static and MCP tools, aggregate counts, and no per-call event. \* Scope excludes task completion delivery, removed unused APIs, policy text, other payload fields, and cloud sync. \* Cost: two small model files, four configs, 36 IDs and two call sequences. Agent time is not measured; TLC runs took under 1 second. -\* Gate: TLA_JAR= ./check.sh TelemetryBoundaryMC. Review counts: covered 0, added 0, gap 2. +\* Gate: TLA_JAR= ./check.sh TelemetryBoundaryMC. Review counts: covered 0, added 0, gap 3. \* PR 2329, user-supplied review finding 7: gap. No thread URL was supplied. \* The model checks pseudonymous sinks, not privacy wording or resistance to joining known IDs. \* PRIVACY.md now states that the hash remains a persistent device ID and can be personal data. \* Expected and result: this text change does not alter identity projection. No new runtime finding is expected. \* Follow-up privacy line wrapping: gap. Layout has no runtime state. Only whitespace changed. +\* Incremental review: privacy punctuation is a prose gap. Replacing two em-dashes does not change the data flow. EXTENDS Naturals CONSTANTS HashHost, HashWebview, PerCall, MaxCalls VARIABLES host, webview, calls, aggregate, events diff --git a/src/services/code-index/__tests__/watcher-boundary.property.spec.ts b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts index 80aa1fb9b1a..0eb12307bee 100644 --- a/src/services/code-index/__tests__/watcher-boundary.property.spec.ts +++ b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts @@ -74,7 +74,7 @@ function setup() { function enqueueBatch(watcher: FileWatcher, path: string, type: "create" | "delete" = "create", files = 1) { for (let index = 0; index < files; index++) { - const filePath = index === 0 ? path : `${path}.peer.ts` + const filePath = index === 0 ? path : `${path}.peer-${index}.ts` watcher["accumulatedEvents"].set(filePath, { uri: makeUri(filePath), type }) } } @@ -96,8 +96,9 @@ describe("watcher source-to-state properties", () => { for (const [index, failed] of history.entries()) { prepare.mockImplementation(async (path) => ({ path, - status: failed ? "local_error" : "skipped", - failureSource: failed ? "embedding" : undefined, + status: failed ? "local_error" : "processed_for_batching", + pointsToUpsert: [], + embeddingOutcome: failed ? "failure" : "success", })) const before = prepare.mock.calls.length enqueueBatch(watcher, `/workspace/${index}.ts`, "create", 2) @@ -119,7 +120,7 @@ describe("watcher source-to-state properties", () => { prepare.mockImplementation(async (path) => ({ path, status: "local_error", - failureSource: "embedding", + embeddingOutcome: "failure", })) enqueueBatch(watcher, "/workspace/recovered.ts", "create", 2) const before = prepare.mock.calls.length @@ -133,7 +134,16 @@ describe("watcher source-to-state properties", () => { ) }) -const outcomes = ["success", "local", "singleEmbedding", "embedding", "delete"] as const +const outcomes = [ + "success", + "local", + "singleEmbedding", + "embedding", + "delete", + "idle", + "mixed", + "embeddingSkipped", +] as const const sourceHistories = Array.from({ length: outcomes.length ** 4 }, (_, sequence) => Array.from( { length: 4 }, @@ -154,21 +164,32 @@ describe("watcher failure-source properties", () => { try { for (const [index, outcome] of history.entries()) { const path = `/workspace/${index}.ts` - const result: FileProcessingResult = { - path, - status: outcome === "success" ? "skipped" : "local_error", - ...(outcome === "embedding" || outcome === "singleEmbedding" - ? { failureSource: "embedding" as const } - : {}), - } - prepare.mockImplementation(async (path) => ({ ...result, path })) + prepare.mockImplementation(async (filePath): Promise => { + if (outcome === "idle" || (outcome === "embeddingSkipped" && filePath.endsWith("peer-2.ts"))) { + return { path: filePath, status: "skipped" } + } + if (outcome === "local") return { path: filePath, status: "local_error" } + const succeeded = + outcome === "success" || (outcome === "mixed" && filePath.endsWith("peer-1.ts")) + return { + path: filePath, + status: succeeded ? "processed_for_batching" : "local_error", + pointsToUpsert: [], + embeddingOutcome: succeeded ? "success" : "failure", + } + }) vi.mocked(store.deletePointsByMultipleFilePaths).mockRejectedValue(new Error("Store unavailable")) - const files = outcome === "embedding" ? 2 : 1 + const files = + outcome === "embeddingSkipped" ? 3 : outcome === "embedding" || outcome === "mixed" ? 2 : 1 enqueueBatch(watcher, path, outcome === "delete" ? "delete" : "create", files) const before = prepare.mock.calls.length await watcher["triggerBatchProcessing"]() expect(prepare.mock.calls.length - before).toBe(open || outcome === "delete" ? 0 : files) - if (!open) failures = outcome === "embedding" || outcome === "delete" ? failures + 1 : 0 + if (!open) { + if (outcome === "embedding" || outcome === "embeddingSkipped" || outcome === "delete") + failures++ + else if (outcome !== "idle" && outcome !== "local") failures = 0 + } open ||= failures >= 3 expect(state.state).toBe(open ? "Error" : "Indexed") expect(watcher["accumulatedEvents"].size).toBe(0) diff --git a/src/services/code-index/interfaces/file-processor.ts b/src/services/code-index/interfaces/file-processor.ts index 484f6862133..edb474c842a 100644 --- a/src/services/code-index/interfaces/file-processor.ts +++ b/src/services/code-index/interfaces/file-processor.ts @@ -97,8 +97,8 @@ export interface BatchProcessingSummary { export interface FileProcessingResult { path: string status: "success" | "skipped" | "error" | "processed_for_batching" | "local_error" - /** Set only when the embedding request fails, rather than file preparation. */ - failureSource?: "embedding" + /** The embedding request outcome. Absent when no request was made. */ + embeddingOutcome?: "success" | "failure" error?: Error reason?: string newHash?: string diff --git a/src/services/code-index/processors/__tests__/file-preparation.spec.ts b/src/services/code-index/processors/__tests__/file-preparation.spec.ts index 261300da586..ef8143dfcce 100644 --- a/src/services/code-index/processors/__tests__/file-preparation.spec.ts +++ b/src/services/code-index/processors/__tests__/file-preparation.spec.ts @@ -188,6 +188,7 @@ describe.each(["posix", "win32"] as const)("FilePreparation (%s paths)", (platfo path: filePath, status: "processed_for_batching", newHash: hash, + embeddingOutcome: "success", pointsToUpsert: [ { id: uuidv5(`${normalizedFilePath}:2`, QDRANT_CODE_BLOCK_NAMESPACE), @@ -314,7 +315,7 @@ describe.each(["posix", "win32"] as const)("FilePreparation (%s paths)", (platfo path: filePath, status: "local_error", error, - ...(stage === "embed" ? { failureSource: "embedding" } : {}), + ...(stage === "embed" ? { embeddingOutcome: "failure" } : {}), }) expect(result.error).toBe(error) }, diff --git a/src/services/code-index/processors/__tests__/file-watcher.spec.ts b/src/services/code-index/processors/__tests__/file-watcher.spec.ts index 9604e7adeca..e9acf82833d 100644 --- a/src/services/code-index/processors/__tests__/file-watcher.spec.ts +++ b/src/services/code-index/processors/__tests__/file-watcher.spec.ts @@ -412,7 +412,7 @@ describe("FileWatcher", () => { path: `/mock/workspace/src/local-${index}.ts`, status: "local_error", error, - ...(stage === "embed" ? { failureSource: "embedding" } : {}), + ...(stage === "embed" ? { embeddingOutcome: "failure" } : {}), }, ]) expect(summary.circuitBreakerOpen).toBe(false) @@ -420,6 +420,74 @@ describe("FileWatcher", () => { }, ) + it.each(["stat", "read", "parse"] as const)( + "does not count two-file %s failures as embedding failures", + async (stage) => { + await fileWatcher.initialize() + const error = new Error(`${stage} failed`) + for (let index = 0; index < 4; index++) { + for (let file = 0; file < 2; file++) { + if (stage === "stat") vi.mocked(vscode.workspace.fs.stat).mockRejectedValueOnce(error) + if (stage === "read") vi.mocked(vscode.workspace.fs.readFile).mockRejectedValueOnce(error) + if (stage === "parse") vi.mocked(codeParser.parseFile).mockRejectedValueOnce(error) + } + const summary = await runBatch(`/mock/workspace/src/local-${index}.ts`, "create", 2) + expect(summary.processedFiles).toHaveLength(2) + expect(summary.processedFiles.every((result) => result.status === "local_error")).toBe(true) + expect(summary.circuitBreakerOpen).toBe(false) + } + expect(mockEmbedder.createEmbeddings).not.toHaveBeenCalled() + }, + ) + + it("resets the count when one embedding succeeds and another fails", async () => { + await fileWatcher.initialize() + mockEmbedder.createEmbeddings.mockRejectedValue(new Error("Embedding failed")) + await runBatch("/mock/workspace/src/before-1.ts", "create", 2) + await runBatch("/mock/workspace/src/before-2.ts", "create", 2) + mockEmbedder.createEmbeddings.mockResolvedValueOnce({ embeddings: [[0.1, 0.2, 0.3]] }) + const mixed = await runBatch("/mock/workspace/src/mixed.ts", "create", 2) + expect(mixed.processedFiles.map((result) => result.status).sort()).toEqual(["local_error", "success"]) + expect(mixed.circuitBreakerOpen).toBe(false) + for (let index = 0; index < 3; index++) { + const summary = await runBatch(`/mock/workspace/src/after-${index}.ts`, "create", 2) + expect(summary.circuitBreakerOpen).toBe(index === 2) + } + }) + + it("ignores skipped files when counting embedding attempts", async () => { + await fileWatcher.initialize() + mockEmbedder.createEmbeddings.mockRejectedValue(new Error("Embedder unavailable")) + // One embedding failure plus a file with no blocks is still below the minimum. + for (let index = 0; index < 3; index++) { + vi.mocked(codeParser.parseFile).mockResolvedValueOnce([]) + expect((await runBatch(`/mock/workspace/src/single-${index}.ts`, "create", 2)).circuitBreakerOpen).toBe( + false, + ) + } + for (let index = 0; index < 3; index++) { + const finished = waitForNextBatch() + await mockOnDidCreate({ fsPath: `/mock/workspace/src/broken-${index}.ts` }) + await mockOnDidCreate({ fsPath: `/mock/workspace/src/other-${index}.ts` }) + await mockOnDidCreate({ fsPath: `/mock/workspace/.hidden/skipped-${index}.ts` }) + await vi.advanceTimersByTimeAsync(500) + const summary = await finished + expect(summary.processedFiles.filter((result) => result.status === "skipped")).toHaveLength(1) + expect(summary.circuitBreakerOpen).toBe(index === 2) + } + }) + + it("preserves outage evidence across a batch with no embedding attempt", async () => { + await fileWatcher.initialize() + mockEmbedder.createEmbeddings.mockRejectedValue(new Error("Embedder unavailable")) + await runBatch("/mock/workspace/src/fail-1.ts", "create", 2) + await runBatch("/mock/workspace/src/fail-2.ts", "create", 2) + const skipped = await runBatch("/mock/workspace/.hidden/skipped.ts") + expect(skipped.processedFiles[0].status).toBe("skipped") + expect(skipped.circuitBreakerOpen).toBe(false) + expect((await runBatch("/mock/workspace/src/fail-3.ts", "create", 2)).circuitBreakerOpen).toBe(true) + }) + it("counts failed delete-only batches and drops later deletions", async () => { await fileWatcher.initialize() const error = new Error("Vector store unavailable") diff --git a/src/services/code-index/processors/file-preparation.ts b/src/services/code-index/processors/file-preparation.ts index 338e1e86380..c1630045d94 100644 --- a/src/services/code-index/processors/file-preparation.ts +++ b/src/services/code-index/processors/file-preparation.ts @@ -13,6 +13,7 @@ export class FilePreparation { public async prepareFile(filePath: string): Promise { const dependencies = this.dependencies + let embeddingOutcome: FileProcessingResult["embeddingOutcome"] try { const skipReason = await this.getSkipReason(filePath) if (skipReason !== undefined) { @@ -33,9 +34,10 @@ export class FilePreparation { let embeddings: number[][] try { const result = await dependencies.embedder.createEmbeddings(blocks.map((block) => block.content)) + embeddingOutcome = "success" embeddings = result.embeddings } catch (error) { - return { path: filePath, status: "local_error", error: error as Error, failureSource: "embedding" } + return { path: filePath, status: "local_error", error: error as Error, embeddingOutcome: "failure" } } pointsToUpsert = this.preparePoints(blocks, embeddings) } @@ -45,12 +47,14 @@ export class FilePreparation { status: "processed_for_batching", newHash, pointsToUpsert, + ...(embeddingOutcome ? { embeddingOutcome } : {}), } } catch (error) { return { path: filePath, status: "local_error", error: error as Error, + ...(embeddingOutcome ? { embeddingOutcome } : {}), } } } diff --git a/src/services/code-index/processors/file-watcher.ts b/src/services/code-index/processors/file-watcher.ts index 436ec356799..a21115233e0 100644 --- a/src/services/code-index/processors/file-watcher.ts +++ b/src/services/code-index/processors/file-watcher.ts @@ -290,10 +290,12 @@ export class FileWatcher implements IFileWatcher { pathsToExplicitlyDelete: string[], ): Promise<{ pointsForBatchUpsert: PointStruct[] + embeddingOutcomes: NonNullable[] successfullyProcessedForUpsert: Array<{ path: string; newHash?: string }> processedCount: number }> { const pointsForBatchUpsert: PointStruct[] = [] + const embeddingOutcomes: NonNullable[] = [] const successfullyProcessedForUpsert: Array<{ path: string; newHash?: string }> = [] const filesToProcessConcurrently = [...filesToUpsertDetails] @@ -328,6 +330,7 @@ export class FileWatcher implements IFileWatcher { if (directError) { batchResults.push({ path, status: "error", error: directError }) } else if (result) { + if (result.embeddingOutcome) embeddingOutcomes.push(result.embeddingOutcome) if (result.status === "skipped" || result.status === "local_error") { batchResults.push(result) } else if (result.status === "processed_for_batching" && result.pointsToUpsert) { @@ -377,6 +380,7 @@ export class FileWatcher implements IFileWatcher { return { pointsForBatchUpsert, + embeddingOutcomes, successfullyProcessedForUpsert, processedCount: processedCountInBatch, } @@ -495,6 +499,7 @@ export class FileWatcher implements IFileWatcher { // Phase 2: Process files and prepare upserts const { pointsForBatchUpsert, + embeddingOutcomes, successfullyProcessedForUpsert, processedCount: upsertCount, } = await this._processFilesAndPrepareUpserts( @@ -516,13 +521,14 @@ export class FileWatcher implements IFileWatcher { // A single rejected input does not establish an embedding service failure. // Storage failures count at any batch size. File read and parse errors stay local. - const resultsByPath = new Map(batchResults.map((result) => [result.path, result])) const allAttemptedEmbeddingsFailed = - filesToUpsertDetails.length >= 2 && - filesToUpsertDetails.every((detail) => resultsByPath.get(detail.path)?.failureSource === "embedding") + embeddingOutcomes.length >= 2 && embeddingOutcomes.every((outcome) => outcome === "failure") - this.consecutiveFailedBatches = - overallBatchError !== undefined || allAttemptedEmbeddingsFailed ? this.consecutiveFailedBatches + 1 : 0 + if (overallBatchError !== undefined || allAttemptedEmbeddingsFailed) { + this.consecutiveFailedBatches++ + } else if (embeddingOutcomes.length > 0) { + this.consecutiveFailedBatches = 0 + } if (!this.circuitBreakerOpen && this.consecutiveFailedBatches >= CIRCUIT_BREAKER_BATCH_THRESHOLD) { this.circuitBreakerOpen = true From bc05e5e091596b0809abc411af2e2ccdebbd22a9 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Tue, 24 Nov 2026 04:52:17 +0000 Subject: [PATCH 6/7] refactor: simplify watcher batches and test embedding outcome errors --- docs/architecture/tla/CodeIndexWatcher.tla | 18 +++++++++++++-- .../__tests__/file-preparation.spec.ts | 23 +++++++++++++++++++ .../code-index/processors/file-watcher.ts | 7 +++--- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/docs/architecture/tla/CodeIndexWatcher.tla b/docs/architecture/tla/CodeIndexWatcher.tla index d8ab60231a7..908743d67d4 100644 --- a/docs/architecture/tla/CodeIndexWatcher.tla +++ b/docs/architecture/tla/CodeIndexWatcher.tla @@ -11,8 +11,8 @@ \* Failure: recovery loses a live watcher. Invariant: RecoveryDisposes. \* Expect: recovery without disposal leaks after a trip. Overlapping work and cancellation remain outside scope. \* PR 2329, https://github.com/Zoo-Code-Org/Zoo-Code/pull/2329#discussion_r4638535661: added. -\* Prior result: fixed passes (9 states). All nine sabotage configs fail. No additional failure was found. -\* Variant states: SingleEmbedding 3, Local 3, Delete 4, Silent 8, StaleCount 8, Unreported 8, Leaked 10, Queued 10, Unguarded 10. +\* Prior result: fixed passes (9 states). All eleven sabotage configs fail. No additional failure was found. +\* Variant states: SingleEmbedding 3, Local 3, Delete 4, Silent 8, StaleCount 8, Unreported 8, Leaked 10, Queued 10, Unguarded 10, Idle 6, Skipped 4. \* Replay: watcher-boundary.property.spec.ts failed on 20 of 64 histories before the summary fix; all 64 now pass. \* Sabotage replay: silent summary, removed admission guards, and removed progress latch each fail test assertions. \* Prior recovery tests checked call counts. Review found that recovery could swallow their ordering assertion. @@ -53,6 +53,20 @@ \* Replay: local-as-embedding, every-to-some, and idle-reset runtime mutations each fail focused tests. \* Cost: two new configs and 3,471 more histories (4,160 total). No new state variable. Agent time is not measured. \* Incremental ratchet: added 2, gap 2. PR prose and the optional split are outside the runtime model. +\* Review at 3b368b8d: PR 2329, user-supplied summary, no thread URL. Ratchet: covered 0, added 0, gap 4. +\* Expect: a point error after embedding success must preserve that success in the returned local error. +\* Failure: FilePreparation.prepareFile loses embeddingOutcome before FileWatcher.processBatch reads it. +\* Invariant sentence: a later local error preserves the completed embedding outcome. +\* Gap 1: file results are oracles here. The real-code property checks three point errors on both path platforms. +\* Gap 2: the variant count is model metadata. The header now lists all eleven variants. +\* Gaps 3 and 4: PR prose and the optional split are outside the runtime model. Keep one PR for issue 830. +\* Result: fixed passes at 9 states; all eleven variants fail. The spread sabotage fails all six new test cases. +\* Cost: six real-code cases and one header update. No new model state. No additional bug was found. +\* Simplification: processBatch owns the file list; _processFilesAndPrepareUpserts reads it without a full copy. +\* Expect: removing the copy preserves batch results. The caller finishes the list before awaiting processing. +\* The parameter is ReadonlyArray. Array ownership is outside this model; no transition or invariant changes. +\* Result: fixed passes at 9 states; all eleven variants fail. Focused runtime tests pass; no new bug was found. +\* Cost: one runtime edit and this header entry. No new model state or tests. EXTENDS Naturals CONSTANTS Threshold, Guard, Visible, DisposeOnRecovery, CountLocal, CountDelete, ReportTrip, ClearQueue, ResetFailures, CountSingleEmbedding, IgnoreSkipped, ResetIdle diff --git a/src/services/code-index/processors/__tests__/file-preparation.spec.ts b/src/services/code-index/processors/__tests__/file-preparation.spec.ts index ef8143dfcce..fe405d348b7 100644 --- a/src/services/code-index/processors/__tests__/file-preparation.spec.ts +++ b/src/services/code-index/processors/__tests__/file-preparation.spec.ts @@ -321,6 +321,29 @@ describe.each(["posix", "win32"] as const)("FilePreparation (%s paths)", (platfo }, ) + it.each([Error, TypeError, RangeError])( + "preserves embedding success when point preparation throws %s", + async (ErrorType) => { + const dependencies = setup() + const error = new ErrorType("Point preparation failed") + dependencies.parser.parseFile.mockResolvedValue([ + { + ...block, + // Point preparation reads this path after the embedding request succeeds. + get file_path(): string { + throw error + }, + }, + ]) + + const result = await new FilePreparation(dependencies).prepareFile(filePath) + + expect(dependencies.embedder.createEmbeddings).toHaveBeenCalledExactlyOnceWith([content]) + expect(result).toEqual({ path: filePath, status: "local_error", error, embeddingOutcome: "success" }) + expect(result.error).toBe(error) + }, + ) + it("does not wrap non-Error rejections", async () => { const dependencies = setup() dependencies.fileSystem.readFile.mockRejectedValue("read failed") diff --git a/src/services/code-index/processors/file-watcher.ts b/src/services/code-index/processors/file-watcher.ts index a21115233e0..8c1ec8a53da 100644 --- a/src/services/code-index/processors/file-watcher.ts +++ b/src/services/code-index/processors/file-watcher.ts @@ -283,7 +283,7 @@ export class FileWatcher implements IFileWatcher { } private async _processFilesAndPrepareUpserts( - filesToUpsertDetails: Array<{ path: string; uri: vscode.Uri; originalType: "create" | "change" }>, + filesToUpsertDetails: ReadonlyArray<{ path: string; uri: vscode.Uri; originalType: "create" | "change" }>, batchResults: FileProcessingResult[], processedCountInBatch: number, totalFilesInBatch: number, @@ -297,10 +297,9 @@ export class FileWatcher implements IFileWatcher { const pointsForBatchUpsert: PointStruct[] = [] const embeddingOutcomes: NonNullable[] = [] const successfullyProcessedForUpsert: Array<{ path: string; newHash?: string }> = [] - const filesToProcessConcurrently = [...filesToUpsertDetails] - for (let i = 0; i < filesToProcessConcurrently.length; i += this.FILE_PROCESSING_CONCURRENCY_LIMIT) { - const chunkToProcess = filesToProcessConcurrently.slice(i, i + this.FILE_PROCESSING_CONCURRENCY_LIMIT) + for (let i = 0; i < filesToUpsertDetails.length; i += this.FILE_PROCESSING_CONCURRENCY_LIMIT) { + const chunkToProcess = filesToUpsertDetails.slice(i, i + this.FILE_PROCESSING_CONCURRENCY_LIMIT) const chunkProcessingPromises = chunkToProcess.map(async (fileDetail) => { this._onBatchProgressUpdate.fire({ From 0d26e5eb8597b173a371da4e5bf80765e20558b5 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Thu, 26 Nov 2026 05:00:23 +0000 Subject: [PATCH 7/7] fix(cloud): remove dead task message sync and correct PRIVACY.md --- PRIVACY.md | 31 +++++++--------- packages/cloud/src/CloudService.ts | 8 ----- .../cloud/src/__tests__/CloudService.test.ts | 18 +--------- src/core/task/Task.ts | 36 ------------------- 4 files changed, 14 insertions(+), 79 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index c592170f343..5166d5e25e7 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -32,24 +32,19 @@ go—and, importantly, where they don't. - **API Keys & Credentials**: If you enter an API key (e.g., to connect an AI model), it is stored locally on your device and never sent to us or any third party, except the provider you have chosen. -- **Telemetry (Usage Data)**: We collect feature usage and error data to help - us improve Zoo Code. This telemetry is powered by PostHog and includes a - salted, hashed (pseudonymized) form of your VS Code machine ID, feature - usage patterns, and exception reports. The hashed ID remains a persistent - identifier for each device and can still be personal data. The raw VS Code - machine ID never leaves your device; we use the hashed identifier only for - product analytics and error grouping. PostHog event data is retained for 12 - months under our current project configuration. This PostHog-based telemetry - does **not** collect your code or AI prompts. (Separately, if you sign in to - Zoo Code Cloud and enable Cloud sync, the Cloud sync pipeline, which is - distinct from this PostHog telemetry, does transmit task messages so they - can be shared or synced through your Cloud account; that feature is - controlled by its own Cloud sync settings.) Telemetry is on by default. To - turn it off, choose "Disabled" in the settings or in the notice shown on - first use. The notice remains until you explicitly Accept or Decline. - Telemetry also follows VS Code's own global telemetry setting: if you turn - that off, Zoo Code stops sending telemetry right away, even if the Zoo Code - setting says "Enabled." +- **Telemetry (Usage Data)**: We collect feature usage and error data to help us + improve Zoo Code. This telemetry is powered by PostHog and includes a salted + hash of your VS Code machine ID, feature usage patterns, and exception + reports. The hashed ID is a persistent identifier and may be personal data in + some jurisdictions. The raw machine ID never leaves your device. We use the + hashed ID only for product analytics and error grouping. + PostHog event data is retained for 12 months under our current project + configuration. This PostHog-based telemetry does **not** collect your code or AI + prompts. Telemetry is on by default. To turn it off, choose "Disabled" in + the settings or in the notice shown on first use. The notice remains until + you explicitly Accept or Decline. Telemetry also follows VS Code's own + global telemetry setting: if you turn that off, Zoo Code stops sending + telemetry right away, even if the Zoo Code setting says "Enabled." - **Marketplace Requests**: When you browse or search the Marketplace for Model Configuration Profiles (MCPs) or Custom Modes, Zoo Code makes a secure API call to Zoo Code's backend servers to retrieve listing information. These diff --git a/packages/cloud/src/CloudService.ts b/packages/cloud/src/CloudService.ts index 42e09fa6c37..a7c17f137dc 100644 --- a/packages/cloud/src/CloudService.ts +++ b/packages/cloud/src/CloudService.ts @@ -2,7 +2,6 @@ import type { Disposable, ExtensionContext } from "vscode" import EventEmitter from "events" import type { - TelemetryEvent, ClineMessage, CloudServiceEvents, AuthService, @@ -303,13 +302,6 @@ export class CloudService extends EventEmitter implements Di return this.settingsService!.isTaskSyncEnabled() } - // TelemetryClient - - public captureEvent(_event: TelemetryEvent): void { - this.ensureInitialized() - this.log("[CloudService] Skipping cloud telemetry capture in compatibility mode") - } - // ShareService public async shareTask( diff --git a/packages/cloud/src/__tests__/CloudService.test.ts b/packages/cloud/src/__tests__/CloudService.test.ts index b2cdb63b82f..099672d57a2 100644 --- a/packages/cloud/src/__tests__/CloudService.test.ts +++ b/packages/cloud/src/__tests__/CloudService.test.ts @@ -2,8 +2,7 @@ import * as vscode from "vscode" -import { TelemetryEventName } from "@roo-code/types" -import type { ClineMessage, TelemetryEvent } from "@roo-code/types" +import type { ClineMessage } from "@roo-code/types" import { TaskNotFoundError } from "../errors.js" import { CloudService } from "../CloudService.js" @@ -636,20 +635,5 @@ describe("CloudService", () => { expect(mockShareService.shareTask).toHaveBeenCalledWith(taskId, "organization") expect(result).toEqual(expectedResult) }) - - it("captureEvent is a no-op in compatibility mode", async () => { - const log = vi.fn() - const compatService = cloudService - vi.spyOn(compatService as unknown as { log: (...args: unknown[]) => void }, "log").mockImplementation(log) - - const telemetryEvent: TelemetryEvent = { - event: TelemetryEventName.TASK_CREATED, - properties: { taskId: "task-123" }, - } - - compatService.captureEvent(telemetryEvent) - - expect(log).toHaveBeenCalledWith("[CloudService] Skipping cloud telemetry capture in compatibility mode") - }) }) }) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 98b1e177376..8dc8e79bcb4 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -38,7 +38,6 @@ import { type ClineApiReqCancelReason, type ClineApiReqInfo, RooCodeEventName, - TelemetryEventName, TaskStatus, TodoItem, getApiProtocol, @@ -60,7 +59,6 @@ import { type MentionSegment, } from "@roo-code/types" import { TelemetryService } from "@roo-code/telemetry" -import { CloudService } from "@roo-code/cloud" // api import { ApiHandler, ApiHandlerCreateMessageMetadata, buildApiHandler } from "../../api" @@ -699,7 +697,6 @@ export class Task extends EventEmitter implements TaskLike { private debouncedEmitTokenUsage: ReturnType // Historical cloud sync tracking retained only to avoid task resume churn. - private cloudSyncedMessageTimestamps: Set = new Set() // Initial status for the task's history item (set at creation time to avoid race conditions) private readonly initialStatus?: "active" | "delegated" | "completed" | "interrupted" @@ -1728,17 +1725,6 @@ export class Task extends EventEmitter implements TaskLike { } this.emit(RooCodeEventName.Message, { action: "created", message }) await this.saveClineMessages() - - const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled() - - if (shouldCaptureMessage) { - CloudService.instance.captureEvent({ - event: TelemetryEventName.TASK_MESSAGE, - properties: { taskId: this.taskId, message }, - }) - // Track that this message has been synced to cloud - this.cloudSyncedMessageTimestamps.add(message.ts) - } } /** @@ -1755,15 +1741,6 @@ export class Task extends EventEmitter implements TaskLike { private hydrateClineMessages(messages: ClineMessage[]) { this.clineMessages = ensureMessageIdentifiers(messages) restoreTodoListForTask(this) - - // When hydrating or overwriting messages, repopulate the cloud sync tracking Set - // with timestamps from all non-partial messages to prevent re-syncing previously synced messages - this.cloudSyncedMessageTimestamps.clear() - for (const msg of messages) { - if (msg.partial !== true) { - this.cloudSyncedMessageTimestamps.add(msg.ts) - } - } } private hydrateApiConversationHistory(messages: ApiMessage[]) { @@ -1839,19 +1816,6 @@ export class Task extends EventEmitter implements TaskLike { const provider = this.providerRef.deref() await provider?.postMessageToWebview({ type: "messageUpdated", clineMessage: message }) this.emit(RooCodeEventName.Message, { action: "updated", message }) - - // Check if we should sync to cloud and haven't already synced this message - const shouldCaptureMessage = message.partial !== true && CloudService.isEnabled() - const hasNotBeenSynced = !this.cloudSyncedMessageTimestamps.has(message.ts) - - if (shouldCaptureMessage && hasNotBeenSynced) { - CloudService.instance.captureEvent({ - event: TelemetryEventName.TASK_MESSAGE, - properties: { taskId: this.taskId, message }, - }) - // Track that this message has been synced to cloud - this.cloudSyncedMessageTimestamps.add(message.ts) - } } /**