|
| 1 | +# SSE Streaming Duplication Fix |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +The API streaming endpoint (`/execute/stream`) is experiencing content duplication where each piece of LLM-generated content appears twice in the SSE stream. This creates poor user experience with garbled, repeated text output. |
| 6 | + |
| 7 | +## Root Cause Analysis |
| 8 | + |
| 9 | +The issue is caused by **double event emission** happening in two places simultaneously: |
| 10 | + |
| 11 | +1. **Direct SSE Integration**: The Task uses `SSEOutputAdapter` as its `userInterface`, so LLM streaming content flows directly through `showInformation()`, `showProgress()`, etc. |
| 12 | + |
| 13 | +2. **Message Forwarding**: The `ApiTaskExecutionHandler.onTaskMessage()` method is **ALSO** forwarding the same messages to the SSE adapter again. |
| 14 | + |
| 15 | +This creates a duplicate emission pipeline: |
| 16 | + |
| 17 | +- ✅ **First time**: Task → SSEOutputAdapter.showInformation() → SSE stream |
| 18 | +- ❌ **Second time**: Task → ApiTaskExecutionHandler.onTaskMessage() → SSEOutputAdapter.showInformation() → SSE stream |
| 19 | + |
| 20 | +## Architecture Diagram |
| 21 | + |
| 22 | +```mermaid |
| 23 | +graph TD |
| 24 | + A[LLM Response] --> B[Task Engine] |
| 25 | + B --> C[SSEOutputAdapter as userInterface] |
| 26 | + C --> D[SSE Stream] |
| 27 | +
|
| 28 | + B -.-> E[ApiTaskExecutionHandler.onTaskMessage] |
| 29 | + E -.-> F[SSEOutputAdapter.showInformation] |
| 30 | + F -.-> D |
| 31 | +
|
| 32 | + style E fill:#ffcccc |
| 33 | + style F fill:#ffcccc |
| 34 | +
|
| 35 | + classDef duplicate stroke:#ff0000,stroke-width:3px,stroke-dasharray: 5 5 |
| 36 | + class E,F duplicate |
| 37 | +``` |
| 38 | + |
| 39 | +## Stories |
| 40 | + |
| 41 | +### Story 1: Remove Duplicate Message Forwarding (HIGH PRIORITY) |
| 42 | + |
| 43 | +**Goal**: Eliminate the duplicate event emission by removing redundant message forwarding |
| 44 | + |
| 45 | +**Acceptance Criteria**: |
| 46 | + |
| 47 | +- [ ] LLM streaming content appears only once in SSE output |
| 48 | +- [ ] All essential task messages are still forwarded appropriately |
| 49 | +- [ ] No functionality regression in task execution |
| 50 | +- [ ] Logging shows single emission per content chunk |
| 51 | + |
| 52 | +**Tasks**: |
| 53 | + |
| 54 | +1. **Analyze current event flow** to confirm which path is the primary one |
| 55 | +2. **Modify ApiTaskExecutionHandler.onTaskMessage()** to remove duplicate forwarding: |
| 56 | + - Remove forwarding for `say` actions that are already handled by direct SSE integration |
| 57 | + - Keep forwarding only for events that aren't automatically handled by userInterface |
| 58 | +3. **Add source identification** in logs to track event origins |
| 59 | +4. **Test with various query types** to ensure no regression |
| 60 | + |
| 61 | +**Files to modify**: |
| 62 | + |
| 63 | +- `src/core/task/execution/ApiTaskExecutionHandler.ts` (lines 45-61) |
| 64 | + |
| 65 | +**Implementation Details**: |
| 66 | + |
| 67 | +```typescript |
| 68 | +async onTaskMessage(taskId: string, event: any): Promise<void> { |
| 69 | + if (this.verbose) { |
| 70 | + console.log(`[ApiTaskExecutionHandler] Task ${taskId} message:`, event.action) |
| 71 | + } |
| 72 | + |
| 73 | + // Remove duplicate forwarding - the Task already uses SSEOutputAdapter as userInterface |
| 74 | + // Only forward events that require special handling beyond the standard userInterface methods |
| 75 | + |
| 76 | + // Keep specialized forwarding for events that need custom handling |
| 77 | + if (event.action === "ask" && event.message?.text) { |
| 78 | + // Questions might need special SSE handling beyond standard askQuestion |
| 79 | + await this.sseAdapter.showInformation(`Question: ${event.message.text}`) |
| 80 | + } |
| 81 | + |
| 82 | + // Remove the duplicate "say" forwarding - this is handled by userInterface directly |
| 83 | + // if (event.action === "say" && event.message?.text) { |
| 84 | + // await this.sseAdapter.showInformation(event.message.text) // ← REMOVED |
| 85 | + // } |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +### Story 2: Add SSE Event Deduplication Safety Net (MEDIUM PRIORITY) |
| 90 | + |
| 91 | +**Goal**: Add deduplication logic as a safety measure to prevent future duplicate issues |
| 92 | + |
| 93 | +**Acceptance Criteria**: |
| 94 | + |
| 95 | +- [ ] SSEOutputAdapter can detect and prevent duplicate events |
| 96 | +- [ ] Deduplication window is configurable (default: 100ms) |
| 97 | +- [ ] Metrics track deduplication hits for monitoring |
| 98 | +- [ ] Performance impact is minimal (< 1ms overhead per event) |
| 99 | + |
| 100 | +**Tasks**: |
| 101 | + |
| 102 | +1. **Add event deduplication** in SSEOutputAdapter |
| 103 | +2. **Implement content hashing** for text-based events using fast hash |
| 104 | +3. **Add configurable deduplication window** with environment variable override |
| 105 | +4. **Add metrics collection** for duplicate detection rates |
| 106 | +5. **Add logging** for debugging duplicate detection |
| 107 | + |
| 108 | +**Files to modify**: |
| 109 | + |
| 110 | +- `src/api/streaming/SSEOutputAdapter.ts` |
| 111 | + |
| 112 | +**Implementation Details**: |
| 113 | + |
| 114 | +```typescript |
| 115 | +export class SSEOutputAdapter implements IUserInterface { |
| 116 | + private recentEvents = new Map<string, number>() // hash -> timestamp |
| 117 | + private deduplicationWindowMs = 100 |
| 118 | + |
| 119 | + private isDuplicateEvent(content: string): boolean { |
| 120 | + const hash = this.simpleHash(content) |
| 121 | + const now = Date.now() |
| 122 | + const lastEmitted = this.recentEvents.get(hash) |
| 123 | + |
| 124 | + if (lastEmitted && now - lastEmitted < this.deduplicationWindowMs) { |
| 125 | + return true |
| 126 | + } |
| 127 | + |
| 128 | + this.recentEvents.set(hash, now) |
| 129 | + // Cleanup old entries periodically |
| 130 | + if (this.recentEvents.size > 100) { |
| 131 | + this.cleanupOldEvents(now) |
| 132 | + } |
| 133 | + |
| 134 | + return false |
| 135 | + } |
| 136 | +} |
| 137 | +``` |
| 138 | + |
| 139 | +### Story 3: Improve Logging and Debugging (LOW PRIORITY) |
| 140 | + |
| 141 | +**Goal**: Add better observability to prevent and debug similar issues |
| 142 | + |
| 143 | +**Acceptance Criteria**: |
| 144 | + |
| 145 | +- [ ] Detailed SSE event logging with source identification |
| 146 | +- [ ] Flow tracing capability for debugging event paths |
| 147 | +- [ ] API debugging endpoints for SSE stream inspection |
| 148 | +- [ ] Integration tests verify single emission behavior |
| 149 | + |
| 150 | +**Tasks**: |
| 151 | + |
| 152 | +1. **Add detailed SSE event logging** with source metadata |
| 153 | +2. **Add flow tracing** to track event paths through the system |
| 154 | +3. **Create debugging endpoints** for SSE stream inspection (`/debug/streams`) |
| 155 | +4. **Add integration tests** to verify single emission per content chunk |
| 156 | +5. **Add performance monitoring** for SSE throughput |
| 157 | + |
| 158 | +**Files to modify**: |
| 159 | + |
| 160 | +- `src/api/streaming/SSEOutputAdapter.ts` |
| 161 | +- `src/api/streaming/__tests__/SSEOutputAdapter.test.ts` |
| 162 | +- `src/api/server/FastifyServer.ts` (for debug endpoints) |
| 163 | + |
| 164 | +## Testing Strategy |
| 165 | + |
| 166 | +### Unit Tests |
| 167 | + |
| 168 | +- [ ] Test ApiTaskExecutionHandler without duplicate forwarding |
| 169 | +- [ ] Test SSEOutputAdapter deduplication logic |
| 170 | +- [ ] Test event source identification |
| 171 | + |
| 172 | +### Integration Tests |
| 173 | + |
| 174 | +- [ ] Test `/execute/stream` endpoint with various query types |
| 175 | +- [ ] Verify single emission per LLM content chunk |
| 176 | +- [ ] Test error handling doesn't cause duplication |
| 177 | + |
| 178 | +### Manual Testing |
| 179 | + |
| 180 | +- [ ] Test with short queries (like "list MCP servers") |
| 181 | +- [ ] Test with long reasoning queries |
| 182 | +- [ ] Test with coding tasks that involve multiple tool uses |
| 183 | + |
| 184 | +## Implementation Priority |
| 185 | + |
| 186 | +**Phase 1 (Immediate Fix - 15 minutes)**: |
| 187 | + |
| 188 | +- Story 1: Remove duplicate message forwarding |
| 189 | + |
| 190 | +**Phase 2 (Safety & Monitoring - 75 minutes)**: |
| 191 | + |
| 192 | +- Story 2: Add deduplication safety net |
| 193 | +- Story 3: Improve logging and add tests |
| 194 | + |
| 195 | +## Success Metrics |
| 196 | + |
| 197 | +- [ ] Zero duplicate content in SSE streams |
| 198 | +- [ ] No regression in task execution functionality |
| 199 | +- [ ] Improved user experience with clean, single-emission content |
| 200 | +- [ ] Debugging capabilities for future SSE issues |
0 commit comments