diff --git a/PRIVACY.md b/PRIVACY.md index f43760023db..5166d5e25e7 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -33,10 +33,11 @@ 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. + 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 diff --git a/docs/architecture/tla/CodeIndexWatcher.tla b/docs/architecture/tla/CodeIndexWatcher.tla new file mode 100644 index 00000000000..908743d67d4 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcher.tla @@ -0,0 +1,112 @@ +---- 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. +\* 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. +\* 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. +\* 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. +\* 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 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. +\* 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. +\* 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. +\* 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 +VARIABLES failures, open, ui, badStart, leaked, badClassification, queued, fresh, tripEvents +vars == <> +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 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)) + \/ (kind \in {"idle", "local"} /\ ~CountsAsFailure(kind) /\ failures' # failures)) + /\ 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' = IF ResetFailures THEN 0 ELSE failures + /\ open' = FALSE /\ ui' = "Indexed" /\ badStart' = FALSE + /\ leaked' = (leaked \/ (open /\ ~DisposeOnRecovery)) + /\ 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..bfb3a507e25 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Delete.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + 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 new file mode 100644 index 00000000000..b7f53c10076 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Leaked.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = FALSE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + 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 new file mode 100644 index 00000000000..26553e53c19 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Local.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = TRUE + 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 new file mode 100644 index 00000000000..f774a1cfb6b --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Queued.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 = 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 new file mode 100644 index 00000000000..0cbf2bba02f --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Silent.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = FALSE + CountSingleEmbedding = FALSE + CountLocal = FALSE + 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 new file mode 100644 index 00000000000..d408a5e5072 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.SingleEmbedding.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = TRUE + CountLocal = FALSE + 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 new file mode 100644 index 00000000000..c347a814e27 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.StaleCount.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 = 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 new file mode 100644 index 00000000000..e0aeaaffb74 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unguarded.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = FALSE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + 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 new file mode 100644 index 00000000000..2978cc60d4b --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.Unreported.cfg @@ -0,0 +1,16 @@ +SPECIFICATION Spec +CONSTANTS + Threshold <- BatchLimit + Guard = TRUE + DisposeOnRecovery = TRUE + Visible = TRUE + CountSingleEmbedding = FALSE + CountLocal = FALSE + 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 new file mode 100644 index 00000000000..e5cd60a7043 --- /dev/null +++ b/docs/architecture/tla/CodeIndexWatcherMC.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 = FALSE + ResetFailures = TRUE +INVARIANTS NoStartAfterTrip TripIsVisible RecoveryDisposes CorrectFailureSource OpenQueueEmpty RestartIsFresh TripIsReported +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..ae7ab60b593 --- /dev/null +++ b/docs/architecture/tla/TelemetryBoundary.tla @@ -0,0 +1,34 @@ +---- 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 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 +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/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/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/__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/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..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 @@ -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(), }, @@ -151,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 = [ { @@ -167,8 +190,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 +207,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 +378,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 +419,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 +483,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 +548,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 +635,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/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) - } } /** 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..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", @@ -195,20 +199,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 @@ -332,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/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 1263aaef14c..4d0f112a599 100644 --- a/src/services/code-index/__tests__/manager.spec.ts +++ b/src/services/code-index/__tests__/manager.spec.ts @@ -552,6 +552,41 @@ describe("CodeIndexManager - handleSettingsChange regression", () => { ;(manager as any)._serviceFactory = {} }) + 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 await manager.recoverFromError() 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..0eb12307bee --- /dev/null +++ b/src/services/code-index/__tests__/watcher-boundary.property.spec.ts @@ -0,0 +1,205 @@ +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 { FileProcessingResult, IVectorStore } from "../interfaces" +import { TelemetryService } from "@roo-code/telemetry" +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 = { + 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, 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-${index}.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. +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.mockImplementation(async (path) => ({ + path, + 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) + await watcher["triggerBatchProcessing"]() + 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) + 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.mockImplementation(async (path) => ({ + path, + status: "local_error", + embeddingOutcome: "failure", + })) + enqueueBatch(watcher, "/workspace/recovered.ts", "create", 2) + const before = prepare.mock.calls.length + await watcher["triggerBatchProcessing"]() + expect(prepare.mock.calls.length).toBe(before + 2) + expect(state.state).toBe("Indexed") + } finally { + orchestrator.stopWatcher() + } + }, + ) +}) + +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 }, + (_, 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` + 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 === "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) { + 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) + 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/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/interfaces/file-processor.ts b/src/services/code-index/interfaces/file-processor.ts index 8ecdc518c8d..edb474c842a 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). */ @@ -95,6 +97,8 @@ export interface BatchProcessingSummary { export interface FileProcessingResult { path: string status: "success" | "skipped" | "error" | "processed_for_batching" | "local_error" + /** 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/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) { 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/__tests__/file-preparation.spec.ts b/src/services/code-index/processors/__tests__/file-preparation.spec.ts index 22020a9fddf..fe405d348b7 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), @@ -310,7 +311,35 @@ 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" ? { embeddingOutcome: "failure" } : {}), + }) + expect(result.error).toBe(error) + }, + ) + + 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) }, ) 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..e9acf82833d 100644 --- a/src/services/code-index/processors/__tests__/file-watcher.spec.ts +++ b/src/services/code-index/processors/__tests__/file-watcher.spec.ts @@ -4,11 +4,15 @@ import * as vscode from "vscode" import { FileWatcher } from "../file-watcher" import { FilePreparation } from "../file-preparation" +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(), @@ -101,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) @@ -358,6 +362,274 @@ describe("FileWatcher", () => { }) }) + describe("per-workspace circuit breaker", () => { + /** 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() + 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 + } + + 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`, "create", 2) + expect(summary.processedFiles).toHaveLength(2) + expect(summary.processedFiles[0].status).toBe("local_error") + } + expect(mockEmbedder.createEmbeddings).toHaveBeenCalledTimes(6) + + // 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(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" ? { embeddingOutcome: "failure" } : {}), + }, + ]) + expect(summary.circuitBreakerOpen).toBe(false) + } + }, + ) + + 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") + 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 () => { + 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", "create", 2) + await runBatch("/mock/workspace/src/fail-2.ts", "create", 2) + + // ...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", "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) + + // 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-preparation.ts b/src/services/code-index/processors/file-preparation.ts index a99ff6b56a3..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) { @@ -28,19 +29,32 @@ 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)) + embeddingOutcome = "success" + embeddings = result.embeddings + } catch (error) { + return { path: filePath, status: "local_error", error: error as Error, embeddingOutcome: "failure" } + } + pointsToUpsert = this.preparePoints(blocks, embeddings) + } return { path: filePath, status: "processed_for_batching", newHash, pointsToUpsert, + ...(embeddingOutcome ? { embeddingOutcome } : {}), } } catch (error) { return { path: filePath, status: "local_error", error: error as Error, + ...(embeddingOutcome ? { embeddingOutcome } : {}), } } } @@ -71,14 +85,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 0a0514a891a..8c1ec8a53da 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 } @@ -252,22 +283,23 @@ 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, 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] - 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({ @@ -297,6 +329,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) { @@ -346,6 +379,7 @@ export class FileWatcher implements IFileWatcher { return { pointsForBatchUpsert, + embeddingOutcomes, successfullyProcessedForUpsert, processedCount: processedCountInBatch, } @@ -464,6 +498,7 @@ export class FileWatcher implements IFileWatcher { // Phase 2: Process files and prepare upserts const { pointsForBatchUpsert, + embeddingOutcomes, successfullyProcessedForUpsert, processedCount: upsertCount, } = await this._processFilesAndPrepareUpserts( @@ -483,10 +518,37 @@ export class FileWatcher implements IFileWatcher { overallBatchError, ) + // 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 allAttemptedEmbeddingsFailed = + embeddingOutcomes.length >= 2 && embeddingOutcomes.every((outcome) => outcome === "failure") + + 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 + 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.`, + ) + } + // Finalize this._onDidFinishBatchProcessing.fire({ processedFiles: batchResults, batchError: overallBatchError, + circuitBreakerOpen: this.circuitBreakerOpen, }) this._onBatchProgressUpdate.fire({ processedInBatch: totalFilesInBatch,