Repository navigation
[Fix] Stop code index telemetry storms and hash the machine ID - #2329
zoomote[bot] wants to merge 6 commits into
Conversation
|
Important Review skippedBot user detected. To trigger a single review, invoke the
|
| Check name | Status | Explanation |
|---|---|---|
| Security Boundaries | No changed path in PR #2329 (Zoo-Code-Org/Zoo-Code, author zoomote[bot]) leaks secrets or PII, trusts or executes unvalidated input, or bypasses approval/allowlist controls. Scope: I diffed the PR's o… |
|
| Persistence Integrity | PR #2329 (Zoo-Code-Org/Zoo-Code, base main, head fix/issue-830-telemetry-volume-privacy, author zoomote[bot]) was checked against the Persistence integrity criterion. I reviewed the PR's own commits (… |
|
| Lifecycle Resource Cleanup | The PR diff (base cd3ec48..HEAD) changes lifecycle code in the code-index watcher, orchestrator, and manager. I checked each changed path for leaks and duplicate work after disposal, cancellation, or … |
Full details: Security Boundaries
-
Explanation
No changed path in PR
#2329(Zoo-Code-Org/Zoo-Code, author zoomote[bot]) leaks secrets or PII, trusts or executes unvalidated input, or bypasses approval/allowlist controls. Scope: I diffed the PR's own commits (1faa089^..HEAD, base cd3ec48). A plain diff against the merge-base also pulls in unrelated main-branch changes, such as the removed ioIntelligence model-fetch path in webviewMessageHandler.ts and src/shared/api.ts. Those are not part of this PR and were excluded. Changed paths reviewed: - packages/telemetry/src/distinct-id.ts (new): SHA-256 over a fixed salt and the machine ID. This reduces PII exposure. The raw machine ID no longer becomes the PostHog distinct ID. - PostHogTelemetryClient.ts: the distinct ID is now hashDistinctId(vscode.env.machineId). Before this change, the raw ID was sent. - ClineProvider.ts (~line 3318): getStateToPostToWebview posts the hashed ID, so the raw machine ID no longer crosses into the webview. This is a reduction in exposure. - presentAssistantMessage.ts and TelemetryService.ts: two per-call Tool Used captures and the dead captureToolUsage and captureConversationMessage methods are removed. Only telemetry is affected. recordToolUsage and the validation gate are unchanged. - code-index file-watcher.ts, file-preparation.ts, orchestrator.ts, and manager.ts: circuit-breaker logic drops file-system events after repeated failures. It affects availability, not trust or authorization. The new telemetry payload has only static strings and counts. Embedding errors are not sent to telemetry. - PRIVACY.md: documentation. It describes the hashed ID and the separate Cloud sync pipeline. It adds no new data flow. - Test, TLA+ model, and types-only files: no runtime security impact. Caveats: the fixed salt is a public constant in source, so the hash is pseudonymous rather than secret. That is a privacy-strength limitation, not a new leak. The PR is a net reduction in raw identifier exposure. No failure condition in the custom check is met.
Full details: Persistence Integrity
-
Explanation
PR
#2329(Zoo-Code-Org/Zoo-Code, base main, head fix/issue-830-telemetry-volume-privacy, author zoomote[bot]) was checked against the Persistence integrity criterion. I reviewed the PR's own commits (1faa089 through 3b368b8) against their parent. Changed persistence-adjacent paths: 1. File watcher and hash cache (src/services/code-index/processors/file-watcher.ts). The new circuit breaker state (consecutiveFailedBatches, circuitBreakerOpen) is in memory only. It resets on initialize(), and the recreated watcher starts clean. Persisted-state writes are unchanged in behavior: - cacheManager.updateHash runs only after vectorStore.upsertPoints succeeds (lines 428-431). Files that fail embedding return local_error and never enter successfullyProcessedForUpsert, so their hashes stay stale and they are retried later. - Upsert and deletion are awaited, and upsert failures are retried and then reported through batchError. - When the breaker trips, it reports a CODE_INDEX_ERROR event, logs, and sets the orchestrator state to "Error" with a recovery message (orchestrator.ts). Dropped events are an explicit, reported partial-failure behavior, not a silent loss. 2. Embedding flow (file-preparation.ts). The embedder call is now awaited inside the try block. Its failure returns local_error with embeddingOutcome "failure". No write or hash update occurs on that path, so the behavior matches the prior catch-and-local_error handling. 3. Manager recovery (manager.ts recoverFromError). The new this._orchestrator?.stopWatcher() call is synchronous and runs before the services are cleared. It adds no unawaited persistence operation. 4. Telemetry changes (Task/presentAssistantMessage, TelemetryService, PostHog client). These remove per-call telemetry events and add hashDistinctId. They touch no persisted extension state. The hashed machineId is computed synchronously and posted in ExtensionState. The webview uses it only as its PostHog distinct ID and stores nothing else from it. 5. PRIVACY.md and TLA docs. Documentation only. I found no changed path that loses or corrupts state through an unawaited operation, a non-atomic write, missing rollback or partial-failure handling, or an unpropagated persisted default. The stale-index effect while the breaker is open is an intended, reported stop state, so it does not meet the criterion.
Full details: Lifecycle Resource Cleanup
-
Explanation
The PR diff (base cd3ec48..HEAD) changes lifecycle code in the code-index watcher, orchestrator, and manager. I checked each changed path for leaks and duplicate work after disposal, cancellation, or restart. I found no concrete changed path that causes a leak or duplicate work. Changed paths reviewed: - Breaker trip (
file-watcher.tsprocessBatch). After three counted failures, the watcher setscircuitBreakerOpen, clearsaccumulatedEvents, and fires one telemetry event. Thevscode.FileSystemWatcherstays alive but drops events inscheduleBatchProcessingandtriggerBatchProcessing. The orchestrator then sets state toError. The watcher is released bystopWatcher()throughrecoverFromError,_recreateServices,stopIndexing, and feature disable. - Debounce timer after a trip. A timer scheduled before the trip firestriggerBatchProcessing, which returns early. It does not flush events or repeat work. -manager.tsrecoverFromError. The PR addsthis._orchestrator?.stopWatcher()before the services are cleared. This releases the watcher that was previously left subscribed on recovery. It is a cleanup fix, not a new leak. The call sits inside the existing try/finally. -orchestrator.tssubscriptions. The breaker flag is a closure variable. The subscriptions are disposed bystopWatcher(). The progress handler returns early after a trip, which does not create new work. -file-preparation.ts. The embedding call moved intoprepareFile. It adds no timers, listeners, or watchers. - Telemetry and webview identity. ThecaptureToolUsageandcaptureConversationMessageremovals and thehashDistinctIdchanges inPostHogTelemetryClient,ClineProvider, andpresentAssistantMessageadd no listeners, timers, or providers. Pre-existing behavior I noted but did not attribute to this PR: -FileWatcher.initialize()does not dispose a previousFileSystemWatcher. This is unchanged. The new breaker reset is not on a reachable double-initialize path, because the manager routesErrorto recovery first. - An in-flightprocessBatchdoes not check disposal. The PR does not change this. - The workspace-disabled branch inmanager.initializedoes not stop a running watcher. The PR does not change this.
Full details: Regression Evidence
-
Explanation
PR
#2329(Zoo-Code-Org/Zoo-Code, author zoomote[bot]) changes several behaviors. Most have focused tests at a suitable layer. One changed behavior does not. Covered: - Watcher circuit breaker,src/services/code-index/processors/file-watcher.ts.file-watcher.spec.tsadds a "per-workspace circuit breaker" block. It covers the three-batch trip, single-file local failures, two-file failures, mixed outcomes, skipped files, idle batches, storage failures, retry exhaustion, the trip telemetry, and event rejection after a trip. -FilePreparationembedding-failure outcome,file-preparation.spec.ts. - Recovery ordering,manager.tsstopWatcher()before owner clear.manager.spec.tsadds two tests. - Salted distinct ID,distinct-id.ts.PostHogTelemetryClient.test.tsanddistinct-id.property.test.tscover it. - HashedmachineIdposted to the webview,ClineProvider.ts.ClineProvider.sticky-profile.spec.tsadds a test. - Per-callTool Usedremoval,presentAssistantMessage.ts. The attribution spec asserts onerecordToolUsageand no telemetry event. Not covered: - The orchestrator breaker handling insrc/services/code-index/orchestrator.ts(lines 47–86,_startWatcher). Whensummary.circuitBreakerOpenis true, it setssetSystemState("Error", "File watching stopped after repeated indexing failures..."). It also suppresses lateronBatchProgressUpdatecalls through acircuitBreakerOpenguard. The code comment says this guard exists because a trailing progress event could otherwise overwrite the error with "Indexed". - No test covers this.src/services/code-index/__tests__/orchestrator.spec.tsis unchanged in the PR. A search forcircuitBreakerOpenin that spec returns nothing. The watcher-level tests assert onlysummary.circuitBreakerOpen. They do not assert the orchestrator's state transition. This is a concrete regression scenario: a future change could drop the Error transition or the progress guard, and no test would fail. The lowest valid layer for this behavior isorchestrator.spec.ts, which already mocksonDidFinishBatchProcessingandonBatchProgressUpdate. Scope note: the PR adds no settings or UI controls. The new Error text is not a durable visual UI change, so no Playwright snapshot is required. Prior standing failure: details were unavailable. I re-checked the current state rather than relying on it. The orchestrator gap above remains open, so the prior concern is not resolved for this behavior.Resolution
Add orchestrator-layer tests in
src/services/code-index/__tests__/orchestrator.spec.ts. Capture the handler passed toonDidFinishBatchProcessingand fire a summary withcircuitBreakerOpen: true. Assert thatsetSystemStateis last called with"Error"and the "File watching stopped after repeated indexing failures" message. Then fireonBatchProgressUpdatewithprocessedInBatch === totalInBatchand assert that no"Indexed"state follows. Cover the case where the breaker stays closed (circuitBreakerOpenfalse or absent) so the normal path remains tested.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
|
1 issue outstanding. See session
Reviewed adefd5a |
Review statusThis PR was opened by an automated account. A human maintainer must verify the change intent, provenance, and validation before merging. Current step: Required CI passed. Waiting for automated review of the latest commit. If automated review does not start, a maintainer must restart it. Review-state labels are managed by this workflow; do not edit them manually. |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
fd1399f to
adefd5a
Compare
| 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.", | ||
| ) |
There was a problem hiding this comment.
Dispose the tripped watcher before error recovery recreates services.
This new Error path is handled by CodeIndexManager.startIndexing() through recoverFromError(). That method clears _orchestrator without calling stopWatcher(), so _recreateServices() can no longer dispose the old instance. The tripped VS Code FileSystemWatcher and its emitter subscriptions remain registered after each restart, accumulating native watchers and file-event callbacks. Please stop/dispose the existing orchestrator's watcher before clearing it, and add a breaker-restart disposal assertion.
There was a problem hiding this comment.
Fixed in 35bf2b2. recoverFromError() now calls the existing orchestrator's stopWatcher() before it clears the service references. This call disposes the file watcher and its event subscriptions.
The regression tests check that recovery calls stopWatcher() before clearing the owner. They cover repeated recovery and recovery with no orchestrator. All three cases failed before the fix and now pass.
The SDD model now includes RecoveryDisposes. The model passes, and the variant without disposal fails as expected. The model treats disposal as an oracle. It does not prove native resource cleanup.
Validation passed: 898 code-index tests, all 14 workspace tasks, extension type checks, lint, and both dead-code checks. ESLint suppression counts are unchanged.
…stinct IDs (#830) - Add a per-workspace circuit breaker to the code-index file watcher: after 3 consecutive failed batches it drops further file-system events until the watcher is recreated (embedder/vector-store config change), stopping the retry loop behind the 254k-event Code Index Error spike. - Remove the two per-call captureToolUsage sites re-added by #1073 so tool usage reports only as the aggregated toolsUsed breakdown on Task Completed; drop the dead captureToolUsage/captureConversationMessage methods from TelemetryService. - Salt-hash the PostHog distinct ID (SHA-256 + fixed salt) in PostHogTelemetryClient and before posting machineId to the webview, so the raw VS Code machine ID never leaves the extension host. - Update PRIVACY.md: hashed machine-ID wording and a clarification that the Cloud sync pipeline is separate from PostHog telemetry (issue #830).
adefd5a to
35bf2b2
Compare
Changed-code mutation testingReport for PR head
Details: mutants, guidance, and reproductionChanged-code mutation testing
Focused tests
Reproduce locallyFrom a full checkout containing both commits: Mutation reports
The workflow uploads generated reports in the Advisory findings
|
Related GitHub Issue
Closes: #830
Description
Issue #830 covers two goals: lower PostHog event volume and fix consent and privacy gaps. Earlier PRs already shipped most of the issue: task completion aggregation (#1071), model cache empty-response throttling, the consent banner with explicit Accept and Decline (#1069), the
vscode.env.isTelemetryEnabledgate with a live toggle listener, and the awaited shutdown (#1070). This PR closes the remaining gaps:Code Index Errorevents in the June spike. A batch counts as a failure when deletion or upsert operations fail. It also counts when at least two files reach the embedder and every embedding request fails. Skipped files and local preparation errors do not enter that embedding decision. Other batches with embedding requests reset the count. Batches without embedding requests preserve the count unless a storage operation fails. After three counted failures, the watcher reports one breaker event and drops further file-system events. A configuration change recreates the watcher and clears the count. A single failed embedding request cannot open the breaker. The telemetry-level breaker from fix(telemetry): add circuit breaker and shutdown draining to TelemetryService #1070 also caps event volume.Tool Usedevents (regression fix). feat(telemetry): aggregate task completion telemetry with delta installments #1071 moved tool usage into the aggregatedtoolsUsedbreakdown onTask Completed, but fix(telemetry): record tool usage once centrally, sanitize raw tool names #1073 re-added two per-callcaptureToolUsagecalls. Each tool call then sent two events. This PR removes both call sites and the now-deadcaptureToolUsageandcaptureConversationMessagemethods.recordToolUsagestill feeds the per-task breakdown, and a call-site reintroduction now fails typecheck.vscode.env.machineIdas the distinct ID. A newhashDistinctIdhelper (SHA-256 with a fixed application salt) now produces the ID inPostHogTelemetryClient.ClineProvideralso hashes the value before it posts state to the webview, so the raw machine ID never leaves the extension host. The webview keeps using the posted value as its own PostHog distinct ID, so analytics identity stays stable per device.PRIVACY.mdnow says the machine ID is salted and hashed before it leaves the device, and it states that the Cloud sync pipeline, which transmits task messages when Cloud sync is on, is separate from PostHog telemetry.The issue references
TELEMETRY_GAP_ANALYSIS.mdin the repo root. That file does not exist in the repository, so this PR follows the issue body alone.Test Procedure
PostHogTelemetryClient.test.tsnow asserts the PostHog distinct ID equals the salted hash and never contains the raw machine ID.presentAssistantMessage-tool-usage-attribution.spec.tsasserts onerecordToolUsageper validated call and no per-call telemetry event.pnpm --dir src exec vitest run services/code-index core/assistant-message,pnpm --filter @roo-code/telemetry test, thenpnpm run check-typesandpnpm test.every()and idle-reset mutations each fail the new tests.pnpm run check-typespasses (11/11 tasks) andpnpm test --forcepasses (14/14 tasks; 12,572 extension tests, 2,487 webview tests). ESLint suppression counts did not increase.Pre-Submission Checklist
src/test-utils/,@/utils/test-utils) are used only for mechanical duplication; test intent and scenario-specific mocks remain visible.*.visual.tsxsnapshot inwebview-ui/. Seewebview-ui/AGENTS.md→ "When a UI change needs a snapshot". (No UI change in this PR.)Visual Snapshots
No UI change. No snapshot required.
Videos (interaction / animation only)
No interaction change. No video required.
Documentation Updates
PRIVACY.mdand the models indocs/architecture/tla/.Zoo Code Docs needs no paired update. The breaker stops watcher indexing after repeated service failures and reports an error. This PR adds no settings or controls. The privacy policy changes are in
PRIVACY.md.Additional Notes
One operational note for reviewers: PostHog will see a new distinct-ID format after deployment. Existing event history keeps the old IDs, so before-and-after user counts will not join across the deploy boundary.
Get in Touch
0x7777777_